@infaris/calendar-cli 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1047 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { Command, Option } from "commander";
4
+ import { beginLogin, completeLogin, login, pendingLoginStatus, readLoginCode, } from "./auth.js";
5
+ import { addTaskAttachment, getTaskContext, commentOnTask, linkTaskPullRequest, createEvent, createMailDraft, createTask, deleteEvent, deleteTask, findEvent, getSettings, listCalendars, listEvents, listHours, listTasks, listTeamMembers, resolveTaskId, updateDefaultCalendar, updateEvent, updateTask, PRIORITIES, PRODUCTS, STATUSES, } from "./api.js";
6
+ import { formatDayHeading, formatTime, localDayKey, parseDateInput, resolveRange, startOfDay, endOfDay, } from "./dates.js";
7
+ import { computeFreeSlots, parseHm } from "./freebusy.js";
8
+ import { resolveCreateEventTimes } from "./event-input.js";
9
+ import { resolveAttendeeIds, resolveWritableCalendarId } from "./selectors.js";
10
+ import { crmFetch } from "./crm-api.js";
11
+ import { downloadTaskAttachments } from "./task-download.js";
12
+ import { registerHoursCommands } from "./hours-cli.js";
13
+ import { DEFAULT_BASE_URL, clearCredentials, credentialsPath, loadCredentials, } from "./config.js";
14
+ function fail(message) {
15
+ process.stderr.write(`\x1b[31mError:\x1b[0m ${message}\n`);
16
+ process.exit(1);
17
+ }
18
+ function ok(message) {
19
+ process.stdout.write(`\x1b[32mOK\x1b[0m ${message}\n`);
20
+ }
21
+ const program = new Command();
22
+ program
23
+ .name("infaris-calendar")
24
+ .description("Calendar CLI: agenda, tasks, mail drafts, and the urenstaat (hours).")
25
+ .version("0.9.0");
26
+ const loginCmd = program
27
+ .command("login")
28
+ .description("Sign in with Infaris in your browser and store a token")
29
+ .option("--url <url>", "Calendar base URL (defaults to $INFARIS_CALENDAR_URL or production)", DEFAULT_BASE_URL)
30
+ .option("--manual", "Paste the redirect back instead of a local browser callback (auto-enabled over SSH)")
31
+ .action(async (opts) => {
32
+ try {
33
+ const { credentials } = await login(opts.url, { manual: opts.manual });
34
+ ok(`Signed in as ${credentials.email || credentials.userId}`);
35
+ }
36
+ catch (err) {
37
+ fail(err instanceof Error ? err.message : String(err));
38
+ }
39
+ });
40
+ loginCmd
41
+ .command("link")
42
+ .description("Print a sign-in URL and exit; finish separately with `login code` " +
43
+ "(for an AI agent to relay the URL and code through chat). Re-running " +
44
+ "reuses a pending URL that is still valid")
45
+ .option("--url <url>", "Calendar base URL (defaults to $INFARIS_CALENDAR_URL or production)", DEFAULT_BASE_URL)
46
+ .option("--new", "Discard a pending sign-in and start a fresh one")
47
+ .option("--json", "Machine-readable output")
48
+ .action((opts) => {
49
+ const result = beginLogin(opts.url, { fresh: opts.new });
50
+ if (opts.json) {
51
+ process.stdout.write(`${JSON.stringify({ ...result, expiresAt: new Date(result.expiresAt).toISOString() })}\n`);
52
+ return;
53
+ }
54
+ process.stdout.write(`${result.authUrl}\n`);
55
+ });
56
+ loginCmd
57
+ .command("code [value]")
58
+ .description("Complete a sign-in started with `login link`, using the pasted redirect URL or code " +
59
+ "(pass `-` or pipe it in to keep the code out of shell history)")
60
+ .action(async (value) => {
61
+ try {
62
+ const { credentials } = await completeLogin(await readLoginCode(value));
63
+ ok(`Signed in as ${credentials.email || credentials.userId}`);
64
+ }
65
+ catch (err) {
66
+ fail(err instanceof Error ? err.message : String(err));
67
+ }
68
+ });
69
+ loginCmd
70
+ .command("status")
71
+ .description("Show the stored login and any pending `login link` flow (no secrets)")
72
+ .option("--json", "Machine-readable output")
73
+ .action((opts) => {
74
+ const status = sessionStatus();
75
+ if (opts.json) {
76
+ process.stdout.write(`${JSON.stringify(status, null, 2)}\n`);
77
+ return;
78
+ }
79
+ process.stdout.write(status.signedIn
80
+ ? `Signed in as ${status.email} (${status.baseUrl})\n`
81
+ : "Not signed in.\n");
82
+ process.stdout.write(status.pendingLogin
83
+ ? `Pending sign-in started ${status.pendingLogin.startedAt}, expires ${status.pendingLogin.expiresAt}\n`
84
+ : "No pending sign-in.\n");
85
+ });
86
+ /** Local session facts for `whoami` / `login status`; never includes tokens. */
87
+ function sessionStatus() {
88
+ const creds = loadCredentials();
89
+ const pending = pendingLoginStatus();
90
+ return {
91
+ signedIn: Boolean(creds),
92
+ email: creds?.email || creds?.userId || null,
93
+ baseUrl: creds?.baseUrl ?? null,
94
+ issuer: creds?.issuer ?? null,
95
+ accessTokenExpiresAt: creds ? new Date(creds.expiresAt).toISOString() : null,
96
+ canRefresh: Boolean(creds?.refreshToken),
97
+ credentialsFile: credentialsPath(),
98
+ pendingLogin: pending
99
+ ? {
100
+ baseUrl: pending.baseUrl,
101
+ startedAt: new Date(pending.startedAt).toISOString(),
102
+ expiresAt: new Date(pending.expiresAt).toISOString(),
103
+ }
104
+ : null,
105
+ };
106
+ }
107
+ program
108
+ .command("logout")
109
+ .description("Remove the stored token from this device")
110
+ .action(() => {
111
+ clearCredentials();
112
+ ok("Logged out.");
113
+ });
114
+ program
115
+ .command("whoami")
116
+ .description("Show the currently logged-in account (local credentials, no server check)")
117
+ .option("--json", "Machine-readable output")
118
+ .action((opts) => {
119
+ const creds = loadCredentials();
120
+ if (opts.json) {
121
+ process.stdout.write(`${JSON.stringify(sessionStatus(), null, 2)}\n`);
122
+ if (!creds)
123
+ process.exitCode = 1;
124
+ return;
125
+ }
126
+ if (!creds)
127
+ fail("Not logged in. Run `infaris-calendar login` first.");
128
+ process.stdout.write(`${creds.email || creds.userId}\n`);
129
+ process.stdout.write(` server: ${creds.baseUrl}\n`);
130
+ process.stdout.write(` token: ${credentialsPath()}\n`);
131
+ });
132
+ /** Best-effort calendar lookup: id -> name plus the set of visible calendars. */
133
+ async function loadCalendarInfo() {
134
+ const names = new Map();
135
+ const visible = new Set();
136
+ try {
137
+ const { accounts } = await listCalendars();
138
+ for (const account of accounts) {
139
+ for (const cal of account.calendars) {
140
+ names.set(cal.id, cal.name);
141
+ if (cal.isVisible)
142
+ visible.add(cal.id);
143
+ }
144
+ }
145
+ return { names, visible, loaded: true };
146
+ }
147
+ catch {
148
+ // best-effort; commands still work, just without names/visibility
149
+ return { names, visible, loaded: false };
150
+ }
151
+ }
152
+ /**
153
+ * Hide events from calendars the user turned off, mirroring the web app. Skipped
154
+ * when --include-hidden is set, when a specific --calendar was requested, or when
155
+ * calendar info couldn't be loaded (don't blank out the agenda on a failed call).
156
+ */
157
+ function filterVisible(events, info, opts) {
158
+ if (opts.includeHidden || opts.calendar || !info.loaded)
159
+ return events;
160
+ return events.filter((e) => info.visible.has(e.calendarId));
161
+ }
162
+ /** Default lookup window for by-id event commands: yesterday .. +1 year. */
163
+ function defaultEventWindow() {
164
+ return {
165
+ start: startOfDay(new Date(Date.now() - 1 * 86_400_000)),
166
+ end: endOfDay(new Date(Date.now() + 365 * 86_400_000)),
167
+ };
168
+ }
169
+ /** Best-effort settings load; returns null when unavailable so commands still run. */
170
+ async function loadSettings() {
171
+ try {
172
+ const { settings } = await getSettings();
173
+ return settings;
174
+ }
175
+ catch {
176
+ return null;
177
+ }
178
+ }
179
+ function warn(message) {
180
+ process.stderr.write(`\x1b[33mWarning:\x1b[0m ${message}\n`);
181
+ }
182
+ /** Collapse newlines/tabs to single spaces so one event prints on one line. */
183
+ function clean(value) {
184
+ return (value ?? "").replace(/\s*[\r\n\t]+\s*/g, " ").trim();
185
+ }
186
+ function matchesSearch(event, term) {
187
+ const needle = term.toLowerCase();
188
+ return [event.title, event.description, event.location]
189
+ .filter(Boolean)
190
+ .some((field) => field.toLowerCase().includes(needle));
191
+ }
192
+ /**
193
+ * Print a non-blocking warning if [start, end] overlaps existing (non-all-day,
194
+ * non-cancelled) events. excludeMasterId skips the event being edited.
195
+ */
196
+ async function warnConflicts(start, end, excludeMasterId) {
197
+ try {
198
+ const { events } = await listEvents({
199
+ start: startOfDay(start),
200
+ end: endOfDay(end),
201
+ expand: true,
202
+ });
203
+ const overlaps = events.filter((e) => {
204
+ if (e.isAllDay || e.status === "cancelled")
205
+ return false;
206
+ const masterId = (e.recurringEventId ?? e.id).split(":")[0];
207
+ if (excludeMasterId && masterId === excludeMasterId)
208
+ return false;
209
+ const s = new Date(e.startTime).getTime();
210
+ const en = new Date(e.endTime).getTime();
211
+ return s < end.getTime() && en > start.getTime();
212
+ });
213
+ if (overlaps.length === 0)
214
+ return;
215
+ warn(`overlaps ${overlaps.length} existing event(s):`);
216
+ for (const e of overlaps.slice(0, 5)) {
217
+ process.stderr.write(` ${formatTime(new Date(e.startTime))}-${formatTime(new Date(e.endTime))} ${e.title}\n`);
218
+ }
219
+ }
220
+ catch {
221
+ /* conflict check is best-effort */
222
+ }
223
+ }
224
+ async function runAgenda(opts) {
225
+ const [calendarInfo, settings] = await Promise.all([
226
+ loadCalendarInfo(),
227
+ loadSettings(),
228
+ ]);
229
+ const calendarNames = calendarInfo.names;
230
+ const { start, end } = resolveRange(opts, new Date(), settings?.weekStartsOn);
231
+ const { events: allEvents, baseUrl } = await listEvents({
232
+ start,
233
+ end,
234
+ calendarId: opts.calendar,
235
+ expand: opts.expand,
236
+ });
237
+ const visibleEvents = filterVisible(allEvents, calendarInfo, opts);
238
+ const events = opts.search
239
+ ? visibleEvents.filter((e) => matchesSearch(e, opts.search))
240
+ : visibleEvents;
241
+ if (opts.json) {
242
+ process.stdout.write(`${JSON.stringify({
243
+ range: { start: start.toISOString(), end: end.toISOString() },
244
+ events: events.map((e) => ({
245
+ ...e,
246
+ calendarName: calendarNames.get(e.calendarId) ?? null,
247
+ })),
248
+ }, null, 2)}\n`);
249
+ return;
250
+ }
251
+ if (events.length === 0) {
252
+ process.stdout.write(`No events between ${formatDayHeading(start)} and ${formatDayHeading(end)}.\n`);
253
+ return;
254
+ }
255
+ let currentDay = "";
256
+ for (const e of events) {
257
+ const evStart = new Date(e.startTime);
258
+ const evEnd = new Date(e.endTime);
259
+ const dayKey = localDayKey(evStart);
260
+ if (dayKey !== currentDay) {
261
+ currentDay = dayKey;
262
+ process.stdout.write(`\n${formatDayHeading(evStart)}\n`);
263
+ }
264
+ const time = e.isAllDay
265
+ ? "all-day".padEnd(11)
266
+ : `${formatTime(evStart)}-${formatTime(evEnd)}`.padEnd(11);
267
+ const calName = calendarNames.get(e.calendarId);
268
+ const parts = [` ${time} ${clean(e.title)}`];
269
+ if (e.location)
270
+ parts.push(`@ ${clean(e.location)}`);
271
+ if (calName)
272
+ parts.push(`[${calName}]`);
273
+ process.stdout.write(`${parts.join(" ")}\n`);
274
+ }
275
+ process.stdout.write(`\n${events.length} event(s) - ${baseUrl}\n`);
276
+ }
277
+ const agendaRangeOption = (cmd) => cmd
278
+ .option("--from <date>", "Range start (ISO, or today/tomorrow/+3d)")
279
+ .option("--to <date>", "Range end (inclusive)")
280
+ .option("--days <n>", "Number of days starting from --from or today")
281
+ .option("--today", "Only today (default)")
282
+ .option("--tomorrow", "Only tomorrow")
283
+ .option("--week", "The current week (Mon-Sun)")
284
+ .option("--month", "The current calendar month")
285
+ .option("--calendar <id>", "Only events from this calendar id")
286
+ .option("--include-hidden", "Also include calendars you turned off")
287
+ .option("--no-expand", "Do not expand recurring events into occurrences")
288
+ .option("--json", "Output events as JSON");
289
+ agendaRangeOption(program
290
+ .command("agenda")
291
+ .alias("events")
292
+ .description("Show your calendar events (defaults to today)"))
293
+ .option("--search <text>", "Filter events by title, description or location")
294
+ .action(async (opts) => {
295
+ try {
296
+ await runAgenda(opts);
297
+ }
298
+ catch (err) {
299
+ fail(err instanceof Error ? err.message : String(err));
300
+ }
301
+ });
302
+ program
303
+ .command("calendars")
304
+ .description("List your connected calendars (personal, location, etc.)")
305
+ .option("--set-default <id-or-name>", "Set your default writable calendar")
306
+ .option("--json", "Output as JSON")
307
+ .action(async (opts) => {
308
+ try {
309
+ const { accounts, baseUrl } = await listCalendars();
310
+ if (opts.setDefault) {
311
+ const calendarId = resolveWritableCalendarId(opts.setDefault, accounts);
312
+ const calendar = accounts
313
+ .flatMap((account) => account.calendars)
314
+ .find((item) => item.id === calendarId);
315
+ await updateDefaultCalendar(calendarId);
316
+ if (opts.json) {
317
+ process.stdout.write(`${JSON.stringify({ defaultCalendarId: calendarId, calendarName: calendar.name }, null, 2)}\n`);
318
+ }
319
+ else {
320
+ ok(`Default calendar set to ${calendar.name}`);
321
+ }
322
+ return;
323
+ }
324
+ if (opts.json) {
325
+ process.stdout.write(`${JSON.stringify(accounts, null, 2)}\n`);
326
+ return;
327
+ }
328
+ if (accounts.length === 0) {
329
+ process.stdout.write("No calendars connected.\n");
330
+ return;
331
+ }
332
+ for (const account of accounts) {
333
+ const label = account.email || account.provider;
334
+ process.stdout.write(`\n${label} (${account.provider})\n`);
335
+ for (const cal of account.calendars) {
336
+ const flags = [
337
+ cal.isPrimary ? "primary" : null,
338
+ cal.isReadOnly ? "read-only" : null,
339
+ cal.isVisible ? null : "hidden",
340
+ ].filter(Boolean);
341
+ const suffix = flags.length ? ` (${flags.join(", ")})` : "";
342
+ process.stdout.write(` ${cal.id} ${cal.name}${suffix}\n`);
343
+ }
344
+ }
345
+ process.stdout.write(`\n${baseUrl}\n`);
346
+ }
347
+ catch (err) {
348
+ fail(err instanceof Error ? err.message : String(err));
349
+ }
350
+ });
351
+ // --- create ... ---
352
+ const create = program
353
+ .command("create")
354
+ .description("Create resources in Calendar");
355
+ create
356
+ .command("task")
357
+ .description("Create a work task")
358
+ .requiredOption("-t, --title <title>", "Task title")
359
+ .addOption(new Option("-p, --product <product>", "Product the task belongs to")
360
+ .choices(PRODUCTS)
361
+ .default("pulseguard"))
362
+ .option("-d, --description <text>", "Task description (markdown)")
363
+ .option("--description-file <path>", "Read the description from a file ('-' for stdin)")
364
+ .addOption(new Option("--priority <priority>", "Task priority")
365
+ .choices(PRIORITIES)
366
+ .default("medium"))
367
+ .addOption(new Option("--status <status>", "Initial status")
368
+ .choices(STATUSES)
369
+ .default("not_started"))
370
+ .option("--type <types...>", "Task type(s): general, development, marketing")
371
+ .option("--category <categories...>", "Categorie(s): bug, refinement, feature_request")
372
+ .option("--relation-number <number>", "Linked customer relation number")
373
+ .option("--assignee <people...>", "Assign by exact name, email or id; use me for yourself")
374
+ .option("--due <date>", "Due date (ISO, e.g. 2026-06-30)")
375
+ .option("--image <paths...>", "Attach image(s) or a PDF (max 10 MB each)")
376
+ .option("--json", "Output the created task as JSON")
377
+ .action(async (opts) => {
378
+ try {
379
+ const description = resolveDescription(opts);
380
+ const { task, baseUrl } = await createTask({
381
+ title: opts.title,
382
+ product: opts.product,
383
+ description,
384
+ status: opts.status,
385
+ priority: opts.priority,
386
+ types: opts.type,
387
+ categories: opts.category,
388
+ relationNumber: opts.relationNumber,
389
+ dueDate: opts.due,
390
+ assigneeIds: opts.assignee
391
+ ? await resolveTaskAssignees(opts.assignee)
392
+ : undefined,
393
+ });
394
+ let attachments;
395
+ try {
396
+ attachments = await attachImages(task.id, opts.image);
397
+ }
398
+ catch (error) {
399
+ throw new Error(`Task #${task.taskKey} was created at ${baseUrl}/t/${task.taskKey}; attachment upload failed. Use attach task --id ${task.taskKey} to retry uploads, not create task. ${error instanceof Error ? error.message : error}`);
400
+ }
401
+ if (opts.json) {
402
+ process.stdout.write(`${JSON.stringify({ ...task, attachments }, null, 2)}\n`);
403
+ return;
404
+ }
405
+ ok(`Created #${task.taskKey} ${task.title}`);
406
+ process.stdout.write(` ${baseUrl}/t/${task.taskKey}\n`);
407
+ }
408
+ catch (err) {
409
+ fail(err instanceof Error ? err.message : String(err));
410
+ }
411
+ });
412
+ create
413
+ .command("event")
414
+ .description("Create a calendar event")
415
+ .requiredOption("-t, --title <title>", "Event title")
416
+ .requiredOption("-s, --start <datetime>", "Start (ISO, or 'tomorrow 09:00', '+1d 14:30')")
417
+ .option("-e, --end <datetime>", "End (ISO or relative; inclusive date with --all-day)")
418
+ .option("--duration <minutes>", "Duration in minutes when --end is omitted (defaults to your settings)")
419
+ .option("--all-day", "Create an all-day event")
420
+ .option("-a, --attendee <people...>", "Invite team members by name or email")
421
+ .option("-l, --location <text>", "Event location")
422
+ .option("-d, --description <text>", "Event description")
423
+ .option("--description-file <path>", "Read description from a file ('-' for stdin)")
424
+ .option("--calendar <id-or-name>", "Target writable calendar (defaults to your default calendar)")
425
+ .option("--no-conflict-check", "Skip the overlap warning")
426
+ .option("--json", "Output the created event as JSON")
427
+ .action(async (opts) => {
428
+ try {
429
+ const settings = await loadSettings();
430
+ const { startTime, endTime } = resolveCreateEventTimes(opts, settings?.defaultEventDuration ?? 60);
431
+ if (!opts.allDay && opts.conflictCheck !== false) {
432
+ await warnConflicts(startTime, endTime);
433
+ }
434
+ const description = resolveDescription(opts);
435
+ const attendeeIds = opts.attendee?.length
436
+ ? resolveAttendeeIds(opts.attendee, (await listTeamMembers()).members)
437
+ : undefined;
438
+ const calendarId = opts.calendar
439
+ ? resolveWritableCalendarId(opts.calendar, (await listCalendars()).accounts)
440
+ : undefined;
441
+ const { event, baseUrl } = await createEvent({
442
+ title: opts.title,
443
+ startTime: startTime.toISOString(),
444
+ endTime: endTime.toISOString(),
445
+ isAllDay: Boolean(opts.allDay),
446
+ location: opts.location,
447
+ description,
448
+ calendarId,
449
+ attendeeIds,
450
+ });
451
+ if (opts.json) {
452
+ process.stdout.write(`${JSON.stringify(event, null, 2)}\n`);
453
+ return;
454
+ }
455
+ ok(`Created event ${event.title}`);
456
+ process.stdout.write(` ${describeEventWhen(event)}\n`);
457
+ if (event.calendarId) {
458
+ const calendarNames = (await loadCalendarInfo()).names;
459
+ const calName = calendarNames.get(event.calendarId);
460
+ process.stdout.write(` calendar: ${calName ?? event.calendarId}${opts.calendar ? "" : " (default)"}\n`);
461
+ }
462
+ process.stdout.write(` ${baseUrl}\n`);
463
+ }
464
+ catch (err) {
465
+ fail(err instanceof Error ? err.message : String(err));
466
+ }
467
+ });
468
+ // --- next (upcoming events) ---
469
+ program
470
+ .command("next")
471
+ .description("Show your next upcoming event(s)")
472
+ .option("-n, --limit <n>", "How many upcoming events to show", "3")
473
+ .option("--days <n>", "How many days ahead to look", "30")
474
+ .option("--calendar <id>", "Only events from this calendar id")
475
+ .option("--include-hidden", "Also include calendars you turned off")
476
+ .option("--json", "Output as JSON")
477
+ .action(async (opts) => {
478
+ try {
479
+ const limit = Math.max(1, Number(opts.limit) || 3);
480
+ const daysAhead = Math.max(1, Number(opts.days) || 30);
481
+ const now = new Date();
482
+ const end = endOfDay(new Date(now.getTime() + daysAhead * 86_400_000));
483
+ const calendarInfo = await loadCalendarInfo();
484
+ const calendarNames = calendarInfo.names;
485
+ const { events: allEvents, baseUrl } = await listEvents({
486
+ start: now,
487
+ end,
488
+ calendarId: opts.calendar,
489
+ expand: true,
490
+ });
491
+ const upcoming = filterVisible(allEvents, calendarInfo, opts)
492
+ .filter((e) => new Date(e.endTime).getTime() > now.getTime())
493
+ .sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime())
494
+ .slice(0, limit);
495
+ if (opts.json) {
496
+ process.stdout.write(`${JSON.stringify(upcoming.map((e) => ({
497
+ ...e,
498
+ calendarName: calendarNames.get(e.calendarId) ?? null,
499
+ })), null, 2)}\n`);
500
+ return;
501
+ }
502
+ if (upcoming.length === 0) {
503
+ process.stdout.write(`No upcoming events in the next ${daysAhead} days.\n`);
504
+ return;
505
+ }
506
+ for (const e of upcoming) {
507
+ const calName = calendarNames.get(e.calendarId);
508
+ const parts = [`${describeEventWhen(e)} ${clean(e.title)}`];
509
+ if (e.location)
510
+ parts.push(`@ ${clean(e.location)}`);
511
+ if (calName)
512
+ parts.push(`[${calName}]`);
513
+ process.stdout.write(`${parts.join(" ")}\n`);
514
+ }
515
+ process.stdout.write(`\n${baseUrl}\n`);
516
+ }
517
+ catch (err) {
518
+ fail(err instanceof Error ? err.message : String(err));
519
+ }
520
+ });
521
+ // --- free (find open time slots) ---
522
+ agendaRangeOption(program
523
+ .command("free")
524
+ .description("Find free time slots within working hours (defaults to today)"))
525
+ .option("--work-start <HH:mm>", "Start of the working day (defaults to your settings)")
526
+ .option("--work-end <HH:mm>", "End of the working day (defaults to your settings)")
527
+ .option("--min <minutes>", "Minimum slot length to report", "30")
528
+ .option("--include-weekends", "Include Saturday and Sunday")
529
+ .option("--ignore-all-day", "Don't treat all-day events as busy")
530
+ .action(async (opts) => {
531
+ try {
532
+ const [settings, calendarInfo] = await Promise.all([
533
+ loadSettings(),
534
+ loadCalendarInfo(),
535
+ ]);
536
+ const { start, end } = resolveRange(opts, new Date(), settings?.weekStartsOn);
537
+ const minMinutes = Math.max(1, Number(opts.min) || 30);
538
+ const workStart = opts.workStart
539
+ ? parseHm(opts.workStart)
540
+ : { h: settings?.workingHoursStart ?? 9, m: 0 };
541
+ const workEnd = opts.workEnd
542
+ ? parseHm(opts.workEnd)
543
+ : { h: settings?.workingHoursEnd ?? 17, m: 0 };
544
+ const includeWeekends = opts.includeWeekends ?? settings?.showWeekends ?? false;
545
+ const { events: allEvents } = await listEvents({
546
+ start,
547
+ end,
548
+ calendarId: opts.calendar,
549
+ expand: opts.expand,
550
+ });
551
+ const events = filterVisible(allEvents, calendarInfo, opts);
552
+ const slots = computeFreeSlots(events, {
553
+ rangeStart: start,
554
+ rangeEnd: end,
555
+ workStart,
556
+ workEnd,
557
+ minMinutes,
558
+ includeWeekends,
559
+ ignoreAllDay: Boolean(opts.ignoreAllDay),
560
+ });
561
+ if (opts.json) {
562
+ process.stdout.write(`${JSON.stringify(slots.map((s) => ({
563
+ start: s.start.toISOString(),
564
+ end: s.end.toISOString(),
565
+ minutes: s.minutes,
566
+ })), null, 2)}\n`);
567
+ return;
568
+ }
569
+ if (slots.length === 0) {
570
+ process.stdout.write(`No free slots of >= ${minMinutes} min between ${formatDayHeading(start)} and ${formatDayHeading(end)}.\n`);
571
+ return;
572
+ }
573
+ let currentDay = "";
574
+ for (const s of slots) {
575
+ const dayKey = localDayKey(s.start);
576
+ if (dayKey !== currentDay) {
577
+ currentDay = dayKey;
578
+ process.stdout.write(`\n${formatDayHeading(s.start)}\n`);
579
+ }
580
+ const dur = s.minutes >= 60
581
+ ? `${Math.floor(s.minutes / 60)}h${s.minutes % 60 ? ` ${s.minutes % 60}m` : ""}`
582
+ : `${s.minutes}m`;
583
+ process.stdout.write(` ${formatTime(s.start)}-${formatTime(s.end)} (${dur})\n`);
584
+ }
585
+ process.stdout.write(`\n${slots.length} free slot(s)\n`);
586
+ }
587
+ catch (err) {
588
+ fail(err instanceof Error ? err.message : String(err));
589
+ }
590
+ });
591
+ // --- show / update / delete an event ---
592
+ const show = program.command("show").description("Show a single resource");
593
+ show
594
+ .command("event <id>")
595
+ .description("Show full details of one event (id from `agenda --json`)")
596
+ .option("--json", "Output as JSON")
597
+ .action(async (id, opts) => {
598
+ try {
599
+ const { event } = await findEvent(id, defaultEventWindow());
600
+ if (!event)
601
+ fail(`Event ${id} not found within the next year.`);
602
+ if (opts.json) {
603
+ process.stdout.write(`${JSON.stringify(event, null, 2)}\n`);
604
+ return;
605
+ }
606
+ const calendarNames = (await loadCalendarInfo()).names;
607
+ process.stdout.write(`${clean(event.title)}\n`);
608
+ process.stdout.write(` when: ${describeEventWhen(event)}\n`);
609
+ if (event.location)
610
+ process.stdout.write(` location: ${clean(event.location)}\n`);
611
+ const calName = calendarNames.get(event.calendarId);
612
+ if (calName)
613
+ process.stdout.write(` calendar: ${calName}\n`);
614
+ if (event.status)
615
+ process.stdout.write(` status: ${event.status}\n`);
616
+ if (event.isRecurring)
617
+ process.stdout.write(` recurring: yes\n`);
618
+ if (event.url)
619
+ process.stdout.write(` url: ${event.url}\n`);
620
+ if (event.attendees?.length) {
621
+ const names = event.attendees
622
+ .map((a) => a.name || a.email || a.userId)
623
+ .filter(Boolean)
624
+ .join(", ");
625
+ process.stdout.write(` attendees: ${names}\n`);
626
+ }
627
+ if (event.description) {
628
+ process.stdout.write(`\n${event.description}\n`);
629
+ }
630
+ }
631
+ catch (err) {
632
+ fail(err instanceof Error ? err.message : String(err));
633
+ }
634
+ });
635
+ const update = program.command("update").description("Update a resource");
636
+ update
637
+ .command("event")
638
+ .description("Reschedule or edit a calendar event")
639
+ .requiredOption("--id <id>", "Event id (from `agenda --json`)")
640
+ .option("-t, --title <title>", "New title")
641
+ .option("-s, --start <datetime>", "New start (ISO or relative)")
642
+ .option("-e, --end <datetime>", "New end (ISO or relative)")
643
+ .option("--shift <minutes>", "Move the event by N minutes (+ later, - earlier)")
644
+ .option("-l, --location <text>", "New location")
645
+ .option("-d, --description <text>", "New description")
646
+ .option("--calendar <id-or-name>", "Move to a different writable calendar")
647
+ .option("-a, --attendee <people...>", "Replace attendees by team member name or email")
648
+ .option("--clear-attendees", "Remove all attendees")
649
+ .option("--no-conflict-check", "Skip the overlap warning")
650
+ .option("--json", "Output the updated event as JSON")
651
+ .action(async (opts) => {
652
+ try {
653
+ if (opts.title === undefined &&
654
+ opts.location === undefined &&
655
+ opts.description === undefined &&
656
+ opts.calendar === undefined &&
657
+ opts.attendee === undefined &&
658
+ opts.clearAttendees === undefined &&
659
+ opts.start === undefined &&
660
+ opts.end === undefined &&
661
+ opts.shift === undefined) {
662
+ fail("Nothing to update. Pass at least one field (e.g. --start, --title).");
663
+ }
664
+ // Recurring occurrences carry a ":<iso>" suffix; edits apply to the series.
665
+ const masterId = String(opts.id).split(":")[0];
666
+ const isOccurrence = masterId !== String(opts.id);
667
+ const patch = { id: masterId };
668
+ if (opts.title !== undefined)
669
+ patch.title = opts.title;
670
+ if (opts.location !== undefined)
671
+ patch.location = opts.location;
672
+ if (opts.description !== undefined)
673
+ patch.description = opts.description;
674
+ if (opts.calendar !== undefined) {
675
+ patch.calendarId = resolveWritableCalendarId(opts.calendar, (await listCalendars()).accounts);
676
+ }
677
+ if (opts.attendee !== undefined && opts.clearAttendees) {
678
+ fail("Use either --attendee or --clear-attendees, not both.");
679
+ }
680
+ if (opts.attendee !== undefined) {
681
+ patch.attendeeIds = resolveAttendeeIds(opts.attendee, (await listTeamMembers()).members);
682
+ }
683
+ else if (opts.clearAttendees) {
684
+ patch.attendeeIds = [];
685
+ }
686
+ if (opts.shift !== undefined) {
687
+ const minutes = Number(opts.shift);
688
+ if (!Number.isFinite(minutes))
689
+ fail(`Invalid --shift: ${opts.shift}`);
690
+ const { event } = await findEvent(opts.id, defaultEventWindow());
691
+ if (!event)
692
+ fail(`Event ${opts.id} not found; cannot shift.`);
693
+ patch.startTime = new Date(new Date(event.startTime).getTime() + minutes * 60_000).toISOString();
694
+ patch.endTime = new Date(new Date(event.endTime).getTime() + minutes * 60_000).toISOString();
695
+ }
696
+ else {
697
+ if (opts.start !== undefined) {
698
+ const s = parseDateInput(opts.start);
699
+ if (!s)
700
+ fail(`Invalid --start: ${opts.start}`);
701
+ patch.startTime = s.toISOString();
702
+ }
703
+ if (opts.end !== undefined) {
704
+ const e = parseDateInput(opts.end);
705
+ if (!e)
706
+ fail(`Invalid --end: ${opts.end}`);
707
+ patch.endTime = e.toISOString();
708
+ }
709
+ }
710
+ if (opts.conflictCheck !== false && patch.startTime && patch.endTime) {
711
+ await warnConflicts(new Date(patch.startTime), new Date(patch.endTime), masterId);
712
+ }
713
+ const { event, baseUrl } = await updateEvent(patch);
714
+ if (opts.json) {
715
+ process.stdout.write(`${JSON.stringify(event, null, 2)}\n`);
716
+ return;
717
+ }
718
+ ok(`Updated ${event.title}`);
719
+ process.stdout.write(` ${describeEventWhen(event)}\n`);
720
+ if (isOccurrence) {
721
+ process.stdout.write(` note: this is a recurring event - the change applies to the whole series.\n`);
722
+ }
723
+ process.stdout.write(` ${baseUrl}\n`);
724
+ }
725
+ catch (err) {
726
+ fail(err instanceof Error ? err.message : String(err));
727
+ }
728
+ });
729
+ update
730
+ .command("task")
731
+ .description("Edit or close a work task")
732
+ .requiredOption("--id <id>", "Task key (e.g. 427 or #427) or id")
733
+ .option("-t, --title <title>", "New title")
734
+ .option("-d, --description <text>", "New description (markdown)")
735
+ .option("--description-file <path>", "Read the new description from a file ('-' for stdin)")
736
+ .addOption(new Option("--status <status>", "New status").choices(STATUSES))
737
+ .addOption(new Option("--priority <priority>", "New priority").choices(PRIORITIES))
738
+ .addOption(new Option("-p, --product <product>", "Move to a different product").choices(PRODUCTS))
739
+ .option("--type <types...>", "Replace task type(s)")
740
+ .option("--category <categories...>", "Replace categorie(s)")
741
+ .option("--relation-number <number>", "Linked customer relation number")
742
+ .option("--assignee <people...>", "Replace assignees by exact name, email or id")
743
+ .option("--clear-assignees", "Remove all assignees")
744
+ .option("--due <date>", "New due date (ISO), or 'none' to clear it")
745
+ .option("--json", "Output the updated task as JSON")
746
+ .action(async (opts) => {
747
+ try {
748
+ const description = resolveDescription(opts);
749
+ if (opts.assignee && opts.clearAssignees)
750
+ throw new Error("Choose --assignee or --clear-assignees");
751
+ if (opts.title === undefined &&
752
+ description === undefined &&
753
+ opts.status === undefined &&
754
+ opts.priority === undefined &&
755
+ opts.product === undefined &&
756
+ opts.type === undefined &&
757
+ opts.category === undefined &&
758
+ opts.relationNumber === undefined &&
759
+ opts.due === undefined &&
760
+ opts.assignee === undefined &&
761
+ !opts.clearAssignees) {
762
+ fail("Nothing to update. Pass at least one field (e.g. --status, --title).");
763
+ }
764
+ const id = await resolveTaskId(opts.id);
765
+ const { task, baseUrl } = await updateTask({
766
+ id,
767
+ title: opts.title,
768
+ description,
769
+ status: opts.status,
770
+ priority: opts.priority,
771
+ product: opts.product,
772
+ types: opts.type,
773
+ categories: opts.category,
774
+ relationNumber: opts.relationNumber,
775
+ assigneeIds: opts.clearAssignees
776
+ ? []
777
+ : opts.assignee
778
+ ? await resolveTaskAssignees(opts.assignee)
779
+ : undefined,
780
+ dueDate: opts.due === undefined
781
+ ? undefined
782
+ : opts.due === "none"
783
+ ? null
784
+ : opts.due,
785
+ });
786
+ if (opts.json) {
787
+ process.stdout.write(`${JSON.stringify(task, null, 2)}\n`);
788
+ return;
789
+ }
790
+ ok(`Updated #${task.taskKey} ${task.title}`);
791
+ process.stdout.write(` ${baseUrl}/t/${task.taskKey}\n`);
792
+ }
793
+ catch (err) {
794
+ fail(err instanceof Error ? err.message : String(err));
795
+ }
796
+ });
797
+ const del = program.command("delete").description("Delete (cancel) a resource");
798
+ del
799
+ .command("task")
800
+ .description("Permanently delete a work task (use `update task --status done` to close it instead)")
801
+ .requiredOption("--id <id>", "Task key (e.g. 427 or #427) or id")
802
+ .action(async (opts) => {
803
+ try {
804
+ const id = await resolveTaskId(opts.id);
805
+ await deleteTask(id);
806
+ ok(`Deleted task ${opts.id}`);
807
+ }
808
+ catch (err) {
809
+ fail(err instanceof Error ? err.message : String(err));
810
+ }
811
+ });
812
+ del
813
+ .command("event")
814
+ .description("Delete a calendar event")
815
+ .requiredOption("--id <id>", "Event id (from `agenda --json`)")
816
+ .action(async (opts) => {
817
+ try {
818
+ const masterId = String(opts.id).split(":")[0];
819
+ await deleteEvent(masterId);
820
+ ok(`Deleted event ${masterId}`);
821
+ if (masterId !== String(opts.id)) {
822
+ process.stdout.write(` note: recurring event - the whole series was removed.\n`);
823
+ }
824
+ }
825
+ catch (err) {
826
+ fail(err instanceof Error ? err.message : String(err));
827
+ }
828
+ });
829
+ // --- attach ... ---
830
+ const attach = program
831
+ .command("attach")
832
+ .description("Attach files to an existing resource");
833
+ attach
834
+ .command("task")
835
+ .description("Attach image(s) or a PDF to an existing work task")
836
+ .requiredOption("--id <id>", "Task key (e.g. 427 or #427) or id")
837
+ .argument("<paths...>", "Path(s) to the file(s) to attach (max 10 MB each)")
838
+ .option("--json", "Output uploaded attachment metadata")
839
+ .action(async (paths, opts) => {
840
+ try {
841
+ const id = await resolveTaskId(opts.id);
842
+ const attachments = await attachImages(id, paths);
843
+ if (opts.json)
844
+ process.stdout.write(`${JSON.stringify({ attachments }, null, 2)}\n`);
845
+ }
846
+ catch (err) {
847
+ fail(err instanceof Error ? err.message : String(err));
848
+ }
849
+ });
850
+ // --- mail ... ---
851
+ const mail = program.command("mail").description("Stage mail concepts");
852
+ mail
853
+ .command("draft")
854
+ .description("Stage a mail concept in your own webmail; never sends it directly. --body is the message above the automatic signature; do not include the signature in the HTML.")
855
+ .requiredOption("--to <email>", "Recipient email address")
856
+ .option("--subject <text>", "Subject")
857
+ .option("--body <html>", "Body HTML placed above the automatic signature (never include the signature)")
858
+ .option("--body-file <path>", "Read the HTML body from a file ('-' for stdin)")
859
+ .option("--from <email>", "Preferred sender mailbox address")
860
+ .option("--attach <path>", "Path to an image or PDF to attach (max 10 MB)")
861
+ .option("--json", "Output the draft id/url as JSON")
862
+ .action(async (opts) => {
863
+ try {
864
+ const html = resolveDescription({
865
+ description: opts.body,
866
+ descriptionFile: opts.bodyFile,
867
+ });
868
+ const { id, url } = await createMailDraft({
869
+ to: opts.to,
870
+ subject: opts.subject,
871
+ html,
872
+ fromAddress: opts.from,
873
+ attachmentPath: opts.attach,
874
+ });
875
+ if (opts.json) {
876
+ process.stdout.write(`${JSON.stringify({ id, url }, null, 2)}\n`);
877
+ return;
878
+ }
879
+ ok("Draft staged");
880
+ process.stdout.write(` ${url}\n`);
881
+ }
882
+ catch (err) {
883
+ fail(err instanceof Error ? err.message : String(err));
884
+ }
885
+ });
886
+ // --- list ... ---
887
+ const list = program.command("list").description("List resources in Calendar");
888
+ list
889
+ .command("tasks")
890
+ .description("List work tasks")
891
+ .option("--status <status>", "Filter by status")
892
+ .option("--search <text>", "Filter by search term")
893
+ .option("--relation-number <number>", "Only tickets for this customer")
894
+ .option("--include-done", "Include completed tasks")
895
+ .option("--assignee <id>", "Filter by assignee id, or `me`")
896
+ .option("--json", "Output tasks as JSON")
897
+ .action(async (opts) => {
898
+ try {
899
+ let assigneeId = opts.assignee;
900
+ if (assigneeId === "me") {
901
+ const day = localDayKey(new Date());
902
+ const { hours } = await listHours({ from: day, to: day });
903
+ assigneeId = hours.currentUserId;
904
+ }
905
+ const { tasks, baseUrl } = await listTasks({
906
+ status: opts.status,
907
+ search: opts.search,
908
+ includeDone: Boolean(opts.includeDone),
909
+ relationNumber: opts.relationNumber,
910
+ assigneeId,
911
+ });
912
+ if (opts.json) {
913
+ process.stdout.write(`${JSON.stringify(tasks, null, 2)}\n`);
914
+ return;
915
+ }
916
+ if (tasks.length === 0) {
917
+ process.stdout.write("No tasks found.\n");
918
+ return;
919
+ }
920
+ for (const task of tasks) {
921
+ const key = `#${task.taskKey}`.padEnd(7);
922
+ const product = (task.product || "").padEnd(13);
923
+ const status = (task.status || "").padEnd(13);
924
+ process.stdout.write(`${key} ${product} ${status} ${task.title}\n`);
925
+ }
926
+ process.stdout.write(`\n${tasks.length} task(s) - ${baseUrl}\n`);
927
+ }
928
+ catch (err) {
929
+ fail(err instanceof Error ? err.message : String(err));
930
+ }
931
+ });
932
+ // `list events` mirrors `agenda` for discoverability.
933
+ agendaRangeOption(list.command("events").description("List calendar events (same as `agenda`)"))
934
+ .option("--search <text>", "Filter events by title, description or location")
935
+ .action(async (opts) => {
936
+ try {
937
+ await runAgenda(opts);
938
+ }
939
+ catch (err) {
940
+ fail(err instanceof Error ? err.message : String(err));
941
+ }
942
+ });
943
+ // `list calendars` mirrors `calendars`.
944
+ list
945
+ .command("calendars")
946
+ .description("List connected calendars (same as `calendars`)")
947
+ .option("--json", "Output as JSON")
948
+ .action(async (opts) => {
949
+ try {
950
+ const { accounts, baseUrl } = await listCalendars();
951
+ if (opts.json) {
952
+ process.stdout.write(`${JSON.stringify(accounts, null, 2)}\n`);
953
+ return;
954
+ }
955
+ for (const account of accounts) {
956
+ process.stdout.write(`\n${account.email || account.provider} (${account.provider})\n`);
957
+ for (const cal of account.calendars) {
958
+ process.stdout.write(` ${cal.id} ${cal.name}\n`);
959
+ }
960
+ }
961
+ process.stdout.write(`\n${baseUrl}\n`);
962
+ }
963
+ catch (err) {
964
+ fail(err instanceof Error ? err.message : String(err));
965
+ }
966
+ });
967
+ /** Uploads each path as a task attachment, printing progress and stopping on the first failure. */
968
+ async function attachImages(taskId, paths) {
969
+ if (!paths?.length)
970
+ return [];
971
+ const uploaded = [];
972
+ for (const path of paths) {
973
+ const { attachment } = await addTaskAttachment(taskId, path);
974
+ process.stderr.write(`Attached ${attachment.fileName}\n`);
975
+ uploaded.push({ id: attachment.id, fileName: attachment.fileName });
976
+ }
977
+ return uploaded;
978
+ }
979
+ function resolveDescription(opts) {
980
+ if (opts.descriptionFile) {
981
+ const source = opts.descriptionFile === "-" ? 0 : opts.descriptionFile;
982
+ return readFileSync(source, "utf8");
983
+ }
984
+ return opts.description;
985
+ }
986
+ function describeEventWhen(event) {
987
+ const start = new Date(event.startTime);
988
+ const end = new Date(event.endTime);
989
+ if (event.isAllDay)
990
+ return `${formatDayHeading(start)} (all-day)`;
991
+ return `${formatDayHeading(start)} ${formatTime(start)}-${formatTime(end)}`;
992
+ }
993
+ async function resolveTaskAssignees(people) {
994
+ const { members } = await listTeamMembers();
995
+ const creds = loadCredentials();
996
+ return resolveAttendeeIds(people.map((person) => (person === "me" ? creds?.email || person : person)), members);
997
+ }
998
+ show
999
+ .command("task <reference>")
1000
+ .description("Read ticket, comments, PRs, subtasks and attachment URLs")
1001
+ .option("--customer-context", "Include the linked CRM dossier")
1002
+ .option("--download-dir <path>", "Download all attachments into a new local folder")
1003
+ .option("--json", "Machine-readable complete context")
1004
+ .action(async (reference, opts) => {
1005
+ const context = await getTaskContext(reference);
1006
+ const downloadedFiles = opts.downloadDir
1007
+ ? await downloadTaskAttachments(context.task.id, context.attachments, opts.downloadDir)
1008
+ : undefined;
1009
+ const customer = opts.customerContext && context.task.relationNumber
1010
+ ? await crmFetch(`/relations/${encodeURIComponent(context.task.relationNumber)}`)
1011
+ : undefined;
1012
+ const result = { ...context, downloadedFiles, customer };
1013
+ process.stdout.write(opts.json
1014
+ ? `${JSON.stringify(result, null, 2)}\n`
1015
+ : `#${context.task.taskKey} ${context.task.title}\n${context.url}\n${JSON.stringify(result, null, 2)}\n`);
1016
+ });
1017
+ program
1018
+ .command("comment <reference>")
1019
+ .description("Append an investigation or handoff to a ticket")
1020
+ .option("--body <text>", "Comment text")
1021
+ .option("--body-file <path>", "Read text from file, or '-' for stdin")
1022
+ .option("--json", "Output the saved comment")
1023
+ .action(async (reference, opts) => {
1024
+ if (opts.body !== undefined && opts.bodyFile !== undefined)
1025
+ throw new Error("Choose --body or --body-file");
1026
+ const body = opts.bodyFile
1027
+ ? readFileSync(opts.bodyFile === "-" ? 0 : opts.bodyFile, "utf8")
1028
+ : opts.body;
1029
+ if (!body?.trim())
1030
+ throw new Error("Pass --body or --body-file");
1031
+ const result = await commentOnTask(reference, body);
1032
+ process.stdout.write(opts.json ? `${JSON.stringify(result, null, 2)}\n` : "Comment saved\n");
1033
+ });
1034
+ program
1035
+ .command("link-pr <reference> <pr>")
1036
+ .description("Link a GitHub PR to a ticket (also posts the task link on GitHub)")
1037
+ .option("--json", "Output the linked PR and ticket")
1038
+ .action(async (reference, pr, opts) => {
1039
+ const result = await linkTaskPullRequest(reference, pr);
1040
+ process.stdout.write(opts.json
1041
+ ? `${JSON.stringify(result, null, 2)}\n`
1042
+ : "Pull request linked\n");
1043
+ });
1044
+ registerHoursCommands(program);
1045
+ program.parseAsync(process.argv).catch((err) => {
1046
+ fail(err instanceof Error ? err.message : String(err));
1047
+ });