@commandgarden/cli 2.0.0 → 2.2.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.
Files changed (54) hide show
  1. package/dist/main.js +74 -10
  2. package/node_modules/@commandgarden/app/dist/client/assets/index-Cglxej9D.css +1 -0
  3. package/node_modules/@commandgarden/app/dist/client/assets/index-Cju0_G1Y.js +397 -0
  4. package/node_modules/@commandgarden/app/dist/client/index.html +19 -19
  5. package/node_modules/@commandgarden/app/dist/server/routes/connectors.js +3 -0
  6. package/node_modules/@commandgarden/app/dist/server/routes/index.js +4 -0
  7. package/node_modules/@commandgarden/app/dist/server/routes/security-news-cache.d.ts +3 -0
  8. package/node_modules/@commandgarden/app/dist/server/routes/security-news-cache.js +17 -0
  9. package/node_modules/@commandgarden/app/dist/server/routes/skills.d.ts +2 -0
  10. package/node_modules/@commandgarden/app/dist/server/routes/skills.js +65 -0
  11. package/node_modules/@commandgarden/app/dist/server/store.d.ts +5 -0
  12. package/node_modules/@commandgarden/app/dist/server/store.js +46 -27
  13. package/node_modules/@commandgarden/app/package.json +42 -42
  14. package/node_modules/@commandgarden/chrome/dist/content-script.js.map +1 -1
  15. package/node_modules/@commandgarden/chrome/dist/manifest.json +16 -16
  16. package/node_modules/@commandgarden/chrome/dist/popup.html +218 -197
  17. package/node_modules/@commandgarden/chrome/dist/popup.js.map +1 -1
  18. package/node_modules/@commandgarden/chrome/dist/service-worker.js.map +1 -1
  19. package/node_modules/@commandgarden/chrome/package.json +25 -25
  20. package/node_modules/@commandgarden/daemon/connectors/ado-git-commits.eval.js +143 -143
  21. package/node_modules/@commandgarden/daemon/connectors/ado-git-commits.yaml +70 -70
  22. package/node_modules/@commandgarden/daemon/connectors/gcs-kb-content.yaml +58 -58
  23. package/node_modules/@commandgarden/daemon/connectors/gcs-kb-pages.yaml +47 -47
  24. package/node_modules/@commandgarden/daemon/connectors/jira-my-tickets.eval.js +115 -115
  25. package/node_modules/@commandgarden/daemon/connectors/jira-my-tickets.yaml +54 -54
  26. package/node_modules/@commandgarden/daemon/connectors/lib/msal-token.js +20 -20
  27. package/node_modules/@commandgarden/daemon/connectors/outlook-my-meetings.eval.js +186 -186
  28. package/node_modules/@commandgarden/daemon/connectors/outlook-my-meetings.yaml +41 -41
  29. package/node_modules/@commandgarden/daemon/connectors/saba-pending-training.eval.js +94 -0
  30. package/node_modules/@commandgarden/daemon/connectors/saba-pending-training.yaml +34 -0
  31. package/node_modules/@commandgarden/daemon/connectors/socket-security-news.yaml +63 -63
  32. package/node_modules/@commandgarden/daemon/connectors/teams-room-availability.eval.js +341 -341
  33. package/node_modules/@commandgarden/daemon/connectors/teams-room-availability.yaml +46 -46
  34. package/node_modules/@commandgarden/daemon/connectors/timetracking-projects.eval.js +52 -52
  35. package/node_modules/@commandgarden/daemon/connectors/timetracking-projects.yaml +42 -42
  36. package/node_modules/@commandgarden/daemon/connectors/timetracking-report.eval.js +81 -81
  37. package/node_modules/@commandgarden/daemon/connectors/timetracking-report.yaml +52 -52
  38. package/node_modules/@commandgarden/daemon/connectors/tldrsec-newsletter.eval.js +27 -0
  39. package/node_modules/@commandgarden/daemon/connectors/tldrsec-newsletter.yaml +38 -0
  40. package/node_modules/@commandgarden/daemon/connectors/tokenmaster-clients-list.yaml +55 -55
  41. package/node_modules/@commandgarden/daemon/dist/audit-store.js +8 -8
  42. package/node_modules/@commandgarden/daemon/package.json +32 -32
  43. package/node_modules/@commandgarden/shared/package.json +32 -32
  44. package/package.json +58 -57
  45. package/node_modules/@commandgarden/app/dist/client/assets/index-CThI0UCl.css +0 -1
  46. package/node_modules/@commandgarden/app/dist/client/assets/index-WANip_um.js +0 -252
  47. package/node_modules/@commandgarden/app/dist/server/daemon-client.test.js +0 -47
  48. package/node_modules/@commandgarden/app/dist/server/routes/routes.test.js +0 -137
  49. package/node_modules/@commandgarden/app/dist/server/store.test.js +0 -59
  50. package/node_modules/@commandgarden/chrome/dist/fetch-interceptor.js +0 -44
  51. package/node_modules/@commandgarden/daemon/dist/cdp-client.d.ts +0 -24
  52. package/node_modules/@commandgarden/daemon/dist/cdp-client.d.ts.map +0 -1
  53. package/node_modules/@commandgarden/daemon/dist/cdp-client.js +0 -150
  54. package/node_modules/@commandgarden/daemon/dist/cdp-client.js.map +0 -1
@@ -1,341 +1,341 @@
1
- // Runs in page context via js_evaluate step.
2
- // Drives the Outlook Scheduling Assistant to fetch a meeting-room's free/busy
3
- // timeline for a single day. Strategy: reuse the authenticated browser session,
4
- // drive the UI to trigger the page's own GraphQL getSchedule call, and intercept
5
- // the response (the endpoint 401s on replay).
6
- //
7
- // Template variables interpolated before execution:
8
- // ${{ args.room }}
9
- // ${{ args.date | default("") }}
10
-
11
- const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June',
12
- 'July', 'August', 'September', 'October', 'November', 'December'];
13
- const DATE_RE = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
14
- const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
15
-
16
- function pad2(n) { return String(n).padStart(2, '0'); }
17
- function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
18
-
19
- function todayLocalISO() {
20
- const d = new Date();
21
- return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
22
- }
23
-
24
- /** "2026-06-18" -> "18, June, 2026" (matches the OWA date-cell aria-label). */
25
- function dateCellLabel(iso) {
26
- const [y, m, d] = iso.split('-').map(Number);
27
- return `${d}, ${MONTHS[m - 1]}, ${y}`;
28
- }
29
-
30
- /** querySelector shorthand, returns null if not found. */
31
- function $(sel) { return document.querySelector(sel); }
32
-
33
- /** True when an element matching the selector exists. */
34
- function exists(sel) { return !!$(sel); }
35
-
36
- /**
37
- * Click a button/link by accessible name (aria-label OR visible text).
38
- * Returns true if an element was found and clicked.
39
- */
40
- function clickByName(name) {
41
- const els = Array.from(document.querySelectorAll('button,a,[role=button]'));
42
- const el = els.find(e => {
43
- if (!e.offsetParent) return false;
44
- const al = (e.getAttribute('aria-label') || '').trim();
45
- const tx = (e.textContent || '').replace(/\s+/g, ' ').trim();
46
- return al === name || al.includes(name) || tx.includes(name);
47
- });
48
- if (!el) return false;
49
- el.scrollIntoView({ block: 'center' });
50
- el.click();
51
- return true;
52
- }
53
-
54
- /** True when the Scheduling Assistant view (with its Start date picker) is rendered. */
55
- function schedulingAssistantOpen() {
56
- return Array.from(document.querySelectorAll('input')).some(
57
- e => (e.getAttribute('aria-label') || '') === 'Start date'
58
- );
59
- }
60
-
61
- /** Type text into an input by selector (focus, set value, dispatch events). */
62
- function typeText(sel, text) {
63
- const el = $(sel);
64
- if (!el) throw new Error(`Element "${sel}" not found for typing`);
65
- el.focus();
66
- const setter = Object.getOwnPropertyDescriptor(
67
- window.HTMLInputElement.prototype, 'value'
68
- ).set;
69
- setter.call(el, text);
70
- el.dispatchEvent(new Event('input', { bubbles: true }));
71
- el.dispatchEvent(new Event('change', { bubbles: true }));
72
- }
73
-
74
- // ── Fetch interceptor ────────────────────────────────────────────────
75
- // Captures getSchedule GraphQL responses (the page's own authenticated
76
- // request — the endpoint 401s on replay).
77
- if (!window.__rfb) {
78
- window.__rfb = [];
79
- const origFetch = window.fetch;
80
- window.fetch = function () {
81
- const a = arguments;
82
- const u = (a[0] && a[0].url) || a[0] || '';
83
- const rb = (a[1] && a[1].body) || '';
84
- return origFetch.apply(this, a).then(r => {
85
- try {
86
- if (String(u).indexOf('graphql') > -1) {
87
- r.clone().text().then(t => {
88
- if (t.indexOf('getSchedule') > -1 && t.indexOf('availabilityView') > -1) {
89
- window.__rfb.push({ req: String(rb || ''), body: t });
90
- }
91
- }).catch(() => {});
92
- }
93
- } catch (_e) { /* ignore */ }
94
- return r;
95
- });
96
- };
97
- }
98
-
99
- /** Read and clear captured {req, body} pairs. */
100
- function readCapture() {
101
- const d = window.__rfb || [];
102
- window.__rfb = [];
103
- return d;
104
- }
105
-
106
- /** Map of scheduleId (lowercased) -> schedule object from a captured response body. */
107
- function schedulesFromPair(pair) {
108
- let body;
109
- try { body = JSON.parse(pair.body); } catch (_e) { return new Map(); }
110
- const byId = new Map();
111
- const nodes = Array.isArray(body) ? body : [body];
112
- for (const node of nodes) {
113
- const schedules = node?.data?.getSchedule?.schedules;
114
- if (Array.isArray(schedules)) {
115
- for (const s of schedules) {
116
- if (s?.scheduleId) byId.set(String(s.scheduleId).toLowerCase(), s);
117
- }
118
- }
119
- }
120
- return byId;
121
- }
122
-
123
- /**
124
- * Build a free/busy timeline (busy/tentative/oof/elsewhere blocks + free gaps)
125
- * for one local day from getSchedule scheduleItems.
126
- */
127
- function buildTimeline(items, dateIso) {
128
- const PRIORITY = { oof: 4, busy: 3, tentative: 2, elsewhere: 1, free: 0 };
129
- const mapStatus = st => ({
130
- Busy: 'busy', Tentative: 'tentative', Oof: 'oof', WorkingElsewhere: 'elsewhere', Free: 'free',
131
- }[st] || 'busy');
132
-
133
- const dayStart = new Date(`${dateIso}T00:00:00`);
134
- const dayEnd = new Date(dayStart.getTime() + 86400000);
135
- const fmt = ms => {
136
- if (ms >= dayEnd.getTime()) return '24:00';
137
- const d = new Date(ms);
138
- return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
139
- };
140
-
141
- const blocks = [];
142
- for (const it of items) {
143
- if (!it || !it.startTime || !it.endTime) continue;
144
- const s = new Date(it.startTime.dateTime).getTime();
145
- const e = new Date(it.endTime.dateTime).getTime();
146
- const cs = Math.max(s, dayStart.getTime());
147
- const ce = Math.min(e, dayEnd.getTime());
148
- if (ce > cs) blocks.push({ state: mapStatus(it.status), s: cs, e: ce });
149
- }
150
- blocks.sort((a, b) => a.s - b.s);
151
-
152
- // Merge overlapping/adjacent busy blocks.
153
- const merged = [];
154
- for (const b of blocks) {
155
- const last = merged[merged.length - 1];
156
- if (last && b.s <= last.e) {
157
- last.e = Math.max(last.e, b.e);
158
- if (PRIORITY[b.state] > PRIORITY[last.state]) last.state = b.state;
159
- } else {
160
- merged.push({ ...b });
161
- }
162
- }
163
-
164
- const rows = [];
165
- let cursor = dayStart.getTime();
166
- for (const b of merged) {
167
- if (b.s > cursor) rows.push({ state: 'free', s: cursor, e: b.s });
168
- rows.push({ state: b.state, s: b.s, e: b.e });
169
- cursor = b.e;
170
- }
171
- if (cursor < dayEnd.getTime()) rows.push({ state: 'free', s: cursor, e: dayEnd.getTime() });
172
-
173
- return rows.map(r => ({
174
- date: dateIso,
175
- state: r.state,
176
- start: fmt(r.s),
177
- end: fmt(r.e),
178
- durationMin: Math.round((r.e - r.s) / 60000),
179
- }));
180
- }
181
-
182
- // ── Main flow ────────────────────────────────────────────────────────
183
-
184
- const room = '${{ args.room }}'.trim();
185
- if (!room) throw new Error('Missing room argument — pass a room name or email');
186
- const isEmail = EMAIL_RE.test(room);
187
-
188
- let date = '${{ args.date | default("") }}'.trim();
189
- if (!date) date = todayLocalISO();
190
- if (!DATE_RE.test(date)) throw new Error(`Invalid date "${date}" — use YYYY-MM-DD`);
191
-
192
- // Wait for compose form controls (handles SSO redirect delays).
193
- const __deadline = Date.now() + 30000;
194
- while (Date.now() < __deadline) {
195
- if (exists("button[aria-label='Open Scheduling Assistant']") ||
196
- exists("input[aria-label='Start date']")) break;
197
- await sleep(1000);
198
- }
199
- if (!exists("button[aria-label='Open Scheduling Assistant']") &&
200
- !exists("input[aria-label='Start date']")) {
201
- if (/login\.|\/oauth2\/|signin|sso/i.test(location.href)) {
202
- throw new Error('Not signed in to Outlook/Teams — log in and retry');
203
- }
204
- throw new Error('Calendar compose form did not load');
205
- }
206
-
207
- // Open the Scheduling Assistant (free/busy view).
208
- for (let i = 0; i < 12 && !schedulingAssistantOpen(); i++) {
209
- clickByName('Open Scheduling Assistant');
210
- await sleep(1000);
211
- }
212
- if (!schedulingAssistantOpen()) {
213
- throw new Error('Could not open the Scheduling Assistant');
214
- }
215
-
216
- // ── Set the date ─────────────────────────────────────────────────────
217
- const cellSel = `button[aria-label='${dateCellLabel(date)}']`;
218
- const target = new Date(`${date}T00:00:00`);
219
- const now = new Date();
220
- const navSel = target >= new Date(now.getFullYear(), now.getMonth(), now.getDate())
221
- ? "button[aria-label^='Go to next month']"
222
- : "button[aria-label^='Go to previous month']";
223
-
224
- const dateInput = $("input[aria-label='Start date']");
225
- if (dateInput) dateInput.click();
226
-
227
- for (let i = 0; i < 30; i++) {
228
- if (exists(cellSel)) {
229
- $(cellSel).click();
230
- break;
231
- }
232
- if (exists(navSel)) {
233
- try { $(navSel).click(); } catch (_e) { /* retry */ }
234
- } else {
235
- const di = $("input[aria-label='Start date']");
236
- if (di) di.click();
237
- }
238
- await sleep(1000);
239
- }
240
- if (!exists(cellSel)) {
241
- // If the cell is gone, the click succeeded; otherwise error.
242
- // (After clicking a date, the picker closes and the cell is removed from DOM.)
243
- }
244
-
245
- // ── Capture pre-existing mailbox IDs (organizer) ─────────────────────
246
- const seen = new Set();
247
- for (let i = 0; i < 3; i++) {
248
- await sleep(1000);
249
- for (const pair of readCapture()) {
250
- for (const id of schedulesFromPair(pair).keys()) seen.add(id);
251
- }
252
- }
253
-
254
- // ── Add the room ─────────────────────────────────────────────────────
255
- if (isEmail) {
256
- // Email -> attendee picker (resolves SMTP).
257
- clickByName('Expand Required attendees');
258
- await sleep(1000);
259
-
260
- const inputSel = "input[aria-label*='required attendees']";
261
- for (let i = 0; i < 12 && !exists(inputSel); i++) {
262
- clickByName('Add required attendee');
263
- await sleep(1000);
264
- }
265
- if (!exists(inputSel)) {
266
- throw new Error('Could not open the required-attendee field');
267
- }
268
- typeText(inputSel, room);
269
-
270
- const optionSel = `[role=option][aria-label*='${room}']`;
271
- let found = false;
272
- for (let i = 0; i < 12 && !found; i++) {
273
- await sleep(1000);
274
- found = exists(optionSel);
275
- }
276
- if (!found) {
277
- throw new Error(`Room "${room}" was not found in the directory`);
278
- }
279
- $(optionSel).click();
280
- } else {
281
- // Name -> room finder.
282
- const inputSel = "input[aria-label='Add a room']";
283
- for (let i = 0; i < 10 && !exists(inputSel); i++) {
284
- clickByName('Add a room');
285
- await sleep(1000);
286
- }
287
- if (!exists(inputSel)) {
288
- throw new Error('Could not open the room finder');
289
- }
290
- typeText(inputSel, room);
291
-
292
- let label = null;
293
- for (let i = 0; i < 14 && !label; i++) {
294
- await sleep(1000);
295
- const opts = Array.from(document.querySelectorAll('[role=option]'));
296
- const el = opts.find(o => /capacity/i.test(o.getAttribute('aria-label') || '') && o.offsetParent);
297
- if (el) {
298
- el.scrollIntoView({ block: 'center' });
299
- el.click();
300
- label = el.getAttribute('aria-label');
301
- }
302
- }
303
- if (!label) {
304
- throw new Error(`No room matched "${room}"`);
305
- }
306
- }
307
-
308
- // ── Collect the room's free/busy from intercepted responses ──────────
309
- let roomId = null;
310
- let errMsg = null;
311
- let sawView = false;
312
- const itemsById = new Map();
313
- const isRoomId = id => (isEmail ? id === room.toLowerCase() : !seen.has(id));
314
-
315
- let stable = 0;
316
- for (let i = 0; i < 30; i++) {
317
- await sleep(1000);
318
- for (const pair of readCapture()) {
319
- for (const [id, s] of schedulesFromPair(pair)) {
320
- if (!isRoomId(id)) continue;
321
- if (!roomId) roomId = s.scheduleId;
322
- if (s.error) errMsg = s.error.message || s.error.responseCode || 'unknown';
323
- if (s.availabilityView && s.availabilityView.length) sawView = true;
324
- for (const it of (s.scheduleItems || [])) {
325
- const key = it && it.id ? it.id : JSON.stringify(it && [it.startTime, it.endTime, it.subject]);
326
- if (it) itemsById.set(key, it);
327
- }
328
- }
329
- }
330
- if (sawView) { stable += 1; if (stable >= 3) break; }
331
- }
332
-
333
- if (!roomId) {
334
- throw new Error(`No free/busy returned for "${room}" on ${date}`);
335
- }
336
- if (errMsg && !sawView) {
337
- throw new Error(`Free/busy error for "${room}": ${errMsg}`);
338
- }
339
-
340
- const timeline = buildTimeline([...itemsById.values()], date);
341
- return timeline.map(r => ({ room: roomId, ...r }));
1
+ // Runs in page context via js_evaluate step.
2
+ // Drives the Outlook Scheduling Assistant to fetch a meeting-room's free/busy
3
+ // timeline for a single day. Strategy: reuse the authenticated browser session,
4
+ // drive the UI to trigger the page's own GraphQL getSchedule call, and intercept
5
+ // the response (the endpoint 401s on replay).
6
+ //
7
+ // Template variables interpolated before execution:
8
+ // ${{ args.room }}
9
+ // ${{ args.date | default("") }}
10
+
11
+ const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June',
12
+ 'July', 'August', 'September', 'October', 'November', 'December'];
13
+ const DATE_RE = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
14
+ const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
15
+
16
+ function pad2(n) { return String(n).padStart(2, '0'); }
17
+ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
18
+
19
+ function todayLocalISO() {
20
+ const d = new Date();
21
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
22
+ }
23
+
24
+ /** "2026-06-18" -> "18, June, 2026" (matches the OWA date-cell aria-label). */
25
+ function dateCellLabel(iso) {
26
+ const [y, m, d] = iso.split('-').map(Number);
27
+ return `${d}, ${MONTHS[m - 1]}, ${y}`;
28
+ }
29
+
30
+ /** querySelector shorthand, returns null if not found. */
31
+ function $(sel) { return document.querySelector(sel); }
32
+
33
+ /** True when an element matching the selector exists. */
34
+ function exists(sel) { return !!$(sel); }
35
+
36
+ /**
37
+ * Click a button/link by accessible name (aria-label OR visible text).
38
+ * Returns true if an element was found and clicked.
39
+ */
40
+ function clickByName(name) {
41
+ const els = Array.from(document.querySelectorAll('button,a,[role=button]'));
42
+ const el = els.find(e => {
43
+ if (!e.offsetParent) return false;
44
+ const al = (e.getAttribute('aria-label') || '').trim();
45
+ const tx = (e.textContent || '').replace(/\s+/g, ' ').trim();
46
+ return al === name || al.includes(name) || tx.includes(name);
47
+ });
48
+ if (!el) return false;
49
+ el.scrollIntoView({ block: 'center' });
50
+ el.click();
51
+ return true;
52
+ }
53
+
54
+ /** True when the Scheduling Assistant view (with its Start date picker) is rendered. */
55
+ function schedulingAssistantOpen() {
56
+ return Array.from(document.querySelectorAll('input')).some(
57
+ e => (e.getAttribute('aria-label') || '') === 'Start date'
58
+ );
59
+ }
60
+
61
+ /** Type text into an input by selector (focus, set value, dispatch events). */
62
+ function typeText(sel, text) {
63
+ const el = $(sel);
64
+ if (!el) throw new Error(`Element "${sel}" not found for typing`);
65
+ el.focus();
66
+ const setter = Object.getOwnPropertyDescriptor(
67
+ window.HTMLInputElement.prototype, 'value'
68
+ ).set;
69
+ setter.call(el, text);
70
+ el.dispatchEvent(new Event('input', { bubbles: true }));
71
+ el.dispatchEvent(new Event('change', { bubbles: true }));
72
+ }
73
+
74
+ // ── Fetch interceptor ────────────────────────────────────────────────
75
+ // Captures getSchedule GraphQL responses (the page's own authenticated
76
+ // request — the endpoint 401s on replay).
77
+ if (!window.__rfb) {
78
+ window.__rfb = [];
79
+ const origFetch = window.fetch;
80
+ window.fetch = function () {
81
+ const a = arguments;
82
+ const u = (a[0] && a[0].url) || a[0] || '';
83
+ const rb = (a[1] && a[1].body) || '';
84
+ return origFetch.apply(this, a).then(r => {
85
+ try {
86
+ if (String(u).indexOf('graphql') > -1) {
87
+ r.clone().text().then(t => {
88
+ if (t.indexOf('getSchedule') > -1 && t.indexOf('availabilityView') > -1) {
89
+ window.__rfb.push({ req: String(rb || ''), body: t });
90
+ }
91
+ }).catch(() => {});
92
+ }
93
+ } catch (_e) { /* ignore */ }
94
+ return r;
95
+ });
96
+ };
97
+ }
98
+
99
+ /** Read and clear captured {req, body} pairs. */
100
+ function readCapture() {
101
+ const d = window.__rfb || [];
102
+ window.__rfb = [];
103
+ return d;
104
+ }
105
+
106
+ /** Map of scheduleId (lowercased) -> schedule object from a captured response body. */
107
+ function schedulesFromPair(pair) {
108
+ let body;
109
+ try { body = JSON.parse(pair.body); } catch (_e) { return new Map(); }
110
+ const byId = new Map();
111
+ const nodes = Array.isArray(body) ? body : [body];
112
+ for (const node of nodes) {
113
+ const schedules = node?.data?.getSchedule?.schedules;
114
+ if (Array.isArray(schedules)) {
115
+ for (const s of schedules) {
116
+ if (s?.scheduleId) byId.set(String(s.scheduleId).toLowerCase(), s);
117
+ }
118
+ }
119
+ }
120
+ return byId;
121
+ }
122
+
123
+ /**
124
+ * Build a free/busy timeline (busy/tentative/oof/elsewhere blocks + free gaps)
125
+ * for one local day from getSchedule scheduleItems.
126
+ */
127
+ function buildTimeline(items, dateIso) {
128
+ const PRIORITY = { oof: 4, busy: 3, tentative: 2, elsewhere: 1, free: 0 };
129
+ const mapStatus = st => ({
130
+ Busy: 'busy', Tentative: 'tentative', Oof: 'oof', WorkingElsewhere: 'elsewhere', Free: 'free',
131
+ }[st] || 'busy');
132
+
133
+ const dayStart = new Date(`${dateIso}T00:00:00`);
134
+ const dayEnd = new Date(dayStart.getTime() + 86400000);
135
+ const fmt = ms => {
136
+ if (ms >= dayEnd.getTime()) return '24:00';
137
+ const d = new Date(ms);
138
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
139
+ };
140
+
141
+ const blocks = [];
142
+ for (const it of items) {
143
+ if (!it || !it.startTime || !it.endTime) continue;
144
+ const s = new Date(it.startTime.dateTime).getTime();
145
+ const e = new Date(it.endTime.dateTime).getTime();
146
+ const cs = Math.max(s, dayStart.getTime());
147
+ const ce = Math.min(e, dayEnd.getTime());
148
+ if (ce > cs) blocks.push({ state: mapStatus(it.status), s: cs, e: ce });
149
+ }
150
+ blocks.sort((a, b) => a.s - b.s);
151
+
152
+ // Merge overlapping/adjacent busy blocks.
153
+ const merged = [];
154
+ for (const b of blocks) {
155
+ const last = merged[merged.length - 1];
156
+ if (last && b.s <= last.e) {
157
+ last.e = Math.max(last.e, b.e);
158
+ if (PRIORITY[b.state] > PRIORITY[last.state]) last.state = b.state;
159
+ } else {
160
+ merged.push({ ...b });
161
+ }
162
+ }
163
+
164
+ const rows = [];
165
+ let cursor = dayStart.getTime();
166
+ for (const b of merged) {
167
+ if (b.s > cursor) rows.push({ state: 'free', s: cursor, e: b.s });
168
+ rows.push({ state: b.state, s: b.s, e: b.e });
169
+ cursor = b.e;
170
+ }
171
+ if (cursor < dayEnd.getTime()) rows.push({ state: 'free', s: cursor, e: dayEnd.getTime() });
172
+
173
+ return rows.map(r => ({
174
+ date: dateIso,
175
+ state: r.state,
176
+ start: fmt(r.s),
177
+ end: fmt(r.e),
178
+ durationMin: Math.round((r.e - r.s) / 60000),
179
+ }));
180
+ }
181
+
182
+ // ── Main flow ────────────────────────────────────────────────────────
183
+
184
+ const room = '${{ args.room }}'.trim();
185
+ if (!room) throw new Error('Missing room argument — pass a room name or email');
186
+ const isEmail = EMAIL_RE.test(room);
187
+
188
+ let date = '${{ args.date | default("") }}'.trim();
189
+ if (!date) date = todayLocalISO();
190
+ if (!DATE_RE.test(date)) throw new Error(`Invalid date "${date}" — use YYYY-MM-DD`);
191
+
192
+ // Wait for compose form controls (handles SSO redirect delays).
193
+ const __deadline = Date.now() + 30000;
194
+ while (Date.now() < __deadline) {
195
+ if (exists("button[aria-label='Open Scheduling Assistant']") ||
196
+ exists("input[aria-label='Start date']")) break;
197
+ await sleep(1000);
198
+ }
199
+ if (!exists("button[aria-label='Open Scheduling Assistant']") &&
200
+ !exists("input[aria-label='Start date']")) {
201
+ if (/login\.|\/oauth2\/|signin|sso/i.test(location.href)) {
202
+ throw new Error('Not signed in to Outlook/Teams — log in and retry');
203
+ }
204
+ throw new Error('Calendar compose form did not load');
205
+ }
206
+
207
+ // Open the Scheduling Assistant (free/busy view).
208
+ for (let i = 0; i < 12 && !schedulingAssistantOpen(); i++) {
209
+ clickByName('Open Scheduling Assistant');
210
+ await sleep(1000);
211
+ }
212
+ if (!schedulingAssistantOpen()) {
213
+ throw new Error('Could not open the Scheduling Assistant');
214
+ }
215
+
216
+ // ── Set the date ─────────────────────────────────────────────────────
217
+ const cellSel = `button[aria-label='${dateCellLabel(date)}']`;
218
+ const target = new Date(`${date}T00:00:00`);
219
+ const now = new Date();
220
+ const navSel = target >= new Date(now.getFullYear(), now.getMonth(), now.getDate())
221
+ ? "button[aria-label^='Go to next month']"
222
+ : "button[aria-label^='Go to previous month']";
223
+
224
+ const dateInput = $("input[aria-label='Start date']");
225
+ if (dateInput) dateInput.click();
226
+
227
+ for (let i = 0; i < 30; i++) {
228
+ if (exists(cellSel)) {
229
+ $(cellSel).click();
230
+ break;
231
+ }
232
+ if (exists(navSel)) {
233
+ try { $(navSel).click(); } catch (_e) { /* retry */ }
234
+ } else {
235
+ const di = $("input[aria-label='Start date']");
236
+ if (di) di.click();
237
+ }
238
+ await sleep(1000);
239
+ }
240
+ if (!exists(cellSel)) {
241
+ // If the cell is gone, the click succeeded; otherwise error.
242
+ // (After clicking a date, the picker closes and the cell is removed from DOM.)
243
+ }
244
+
245
+ // ── Capture pre-existing mailbox IDs (organizer) ─────────────────────
246
+ const seen = new Set();
247
+ for (let i = 0; i < 3; i++) {
248
+ await sleep(1000);
249
+ for (const pair of readCapture()) {
250
+ for (const id of schedulesFromPair(pair).keys()) seen.add(id);
251
+ }
252
+ }
253
+
254
+ // ── Add the room ─────────────────────────────────────────────────────
255
+ if (isEmail) {
256
+ // Email -> attendee picker (resolves SMTP).
257
+ clickByName('Expand Required attendees');
258
+ await sleep(1000);
259
+
260
+ const inputSel = "input[aria-label*='required attendees']";
261
+ for (let i = 0; i < 12 && !exists(inputSel); i++) {
262
+ clickByName('Add required attendee');
263
+ await sleep(1000);
264
+ }
265
+ if (!exists(inputSel)) {
266
+ throw new Error('Could not open the required-attendee field');
267
+ }
268
+ typeText(inputSel, room);
269
+
270
+ const optionSel = `[role=option][aria-label*='${room}']`;
271
+ let found = false;
272
+ for (let i = 0; i < 12 && !found; i++) {
273
+ await sleep(1000);
274
+ found = exists(optionSel);
275
+ }
276
+ if (!found) {
277
+ throw new Error(`Room "${room}" was not found in the directory`);
278
+ }
279
+ $(optionSel).click();
280
+ } else {
281
+ // Name -> room finder.
282
+ const inputSel = "input[aria-label='Add a room']";
283
+ for (let i = 0; i < 10 && !exists(inputSel); i++) {
284
+ clickByName('Add a room');
285
+ await sleep(1000);
286
+ }
287
+ if (!exists(inputSel)) {
288
+ throw new Error('Could not open the room finder');
289
+ }
290
+ typeText(inputSel, room);
291
+
292
+ let label = null;
293
+ for (let i = 0; i < 14 && !label; i++) {
294
+ await sleep(1000);
295
+ const opts = Array.from(document.querySelectorAll('[role=option]'));
296
+ const el = opts.find(o => /capacity/i.test(o.getAttribute('aria-label') || '') && o.offsetParent);
297
+ if (el) {
298
+ el.scrollIntoView({ block: 'center' });
299
+ el.click();
300
+ label = el.getAttribute('aria-label');
301
+ }
302
+ }
303
+ if (!label) {
304
+ throw new Error(`No room matched "${room}"`);
305
+ }
306
+ }
307
+
308
+ // ── Collect the room's free/busy from intercepted responses ──────────
309
+ let roomId = null;
310
+ let errMsg = null;
311
+ let sawView = false;
312
+ const itemsById = new Map();
313
+ const isRoomId = id => (isEmail ? id === room.toLowerCase() : !seen.has(id));
314
+
315
+ let stable = 0;
316
+ for (let i = 0; i < 30; i++) {
317
+ await sleep(1000);
318
+ for (const pair of readCapture()) {
319
+ for (const [id, s] of schedulesFromPair(pair)) {
320
+ if (!isRoomId(id)) continue;
321
+ if (!roomId) roomId = s.scheduleId;
322
+ if (s.error) errMsg = s.error.message || s.error.responseCode || 'unknown';
323
+ if (s.availabilityView && s.availabilityView.length) sawView = true;
324
+ for (const it of (s.scheduleItems || [])) {
325
+ const key = it && it.id ? it.id : JSON.stringify(it && [it.startTime, it.endTime, it.subject]);
326
+ if (it) itemsById.set(key, it);
327
+ }
328
+ }
329
+ }
330
+ if (sawView) { stable += 1; if (stable >= 3) break; }
331
+ }
332
+
333
+ if (!roomId) {
334
+ throw new Error(`No free/busy returned for "${room}" on ${date}`);
335
+ }
336
+ if (errMsg && !sawView) {
337
+ throw new Error(`Free/busy error for "${room}": ${errMsg}`);
338
+ }
339
+
340
+ const timeline = buildTimeline([...itemsById.values()], date);
341
+ return timeline.map(r => ({ room: roomId, ...r }));