@chrischall/microsoft-teams-mcp 0.3.0 → 0.5.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 (50) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +577 -93
  4. package/dist/auth-fetchproxy.js +138 -0
  5. package/dist/bundle.js +44324 -37483
  6. package/dist/capture-window.js +41 -0
  7. package/dist/chatsvc.js +580 -0
  8. package/dist/compose.js +241 -0
  9. package/dist/deps.js +1 -0
  10. package/dist/index.js +35 -6
  11. package/dist/model.js +603 -0
  12. package/dist/sharepoint-auth.js +162 -0
  13. package/dist/sharepoint-token-cache.js +105 -0
  14. package/dist/sharepoint.js +289 -0
  15. package/dist/substrate-auth.js +104 -0
  16. package/dist/substrate-token-cache.js +64 -0
  17. package/dist/substrate.js +319 -0
  18. package/dist/token-cache.js +67 -0
  19. package/dist/tools/activity.js +155 -19
  20. package/dist/tools/attachment.js +174 -0
  21. package/dist/tools/changes.js +241 -0
  22. package/dist/tools/channels.js +62 -44
  23. package/dist/tools/chat-search.js +65 -0
  24. package/dist/tools/chat.js +121 -41
  25. package/dist/tools/confirm.js +188 -0
  26. package/dist/tools/conversation.js +394 -30
  27. package/dist/tools/cursor.js +43 -0
  28. package/dist/tools/errors.js +18 -17
  29. package/dist/tools/format.js +135 -0
  30. package/dist/tools/healthcheck.js +91 -27
  31. package/dist/tools/limit.js +43 -12
  32. package/dist/tools/listing.js +180 -0
  33. package/dist/tools/markread.js +246 -0
  34. package/dist/tools/react.js +217 -0
  35. package/dist/tools/roots.js +73 -0
  36. package/dist/tools/search.js +426 -0
  37. package/dist/tools/send.js +309 -0
  38. package/dist/tools/timezone.js +38 -0
  39. package/dist/tools/titles.js +180 -0
  40. package/dist/tools/unread.js +263 -0
  41. package/dist/tools/untrusted.js +16 -1
  42. package/dist/version.js +1 -1
  43. package/mint.yaml +75 -20
  44. package/package.json +1 -2
  45. package/server.json +87 -3
  46. package/skills/teams-fpx/SKILL.md +111 -92
  47. package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
  48. package/skills/teams-fpx/references/teams-env.sh +146 -0
  49. package/dist/client.js +0 -290
  50. package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
package/dist/model.js ADDED
@@ -0,0 +1,603 @@
1
+ /**
2
+ * The user's own notes chat ("notes to self") — the one `48:*` system
3
+ * conversation that is a real chat. Every other `48:*` id (calendar,
4
+ * notifications, …) is not one and is never listed.
5
+ */
6
+ export const SELF_CHAT = '48:notes';
7
+ const SELF_CHAT_TITLE = 'Notes (self-chat)';
8
+ /** Names that resolve to {@link SELF_CHAT} outright, ahead of any substring match. */
9
+ export const SELF_CHAT_ALIASES = new Set(['notes', 'self']);
10
+ /**
11
+ * Message types a person wrote. Everything else is a system event that Teams
12
+ * never counts as unread: `RichText/Media_*` (call recordings, transcripts),
13
+ * `Event/*`, `ThreadActivity/*`, `Control/*`, ….
14
+ */
15
+ const USER_MESSAGE_TYPES = new Set(['Text', 'RichText/Html']);
16
+ /** Longest last-message preview a conversation summary carries. */
17
+ const PREVIEW_CHARS = 200;
18
+ /** The preview of a last message that is a system event (a call, a member added, …). */
19
+ const SYSTEM_EVENT_PREVIEW = '(system event)';
20
+ /** An untopiced group chat's title when no one but the user is known to have written in it. */
21
+ export const UNTITLED_GROUP_TITLE = '(untitled group chat)';
22
+ /** An untopiced 1:1's title when the other person's name is not known. */
23
+ export const UNTITLED_ONE_ON_ONE_TITLE = '(1:1 chat)';
24
+ /** What an untopiced group chat's participant title starts with (see `tools/titles.ts`). */
25
+ export const GROUP_TITLE_PREFIX = 'Group chat: ';
26
+ /** A channel's team name when the team's own thread is listed but names nothing. */
27
+ const UNNAMED_TEAM = '(team)';
28
+ /** Inline images live on Skype's AMS object store; only those are attachment refs. */
29
+ const IMAGE_HOST_SUFFIX = '.asm.skype.com';
30
+ const IMAGE_OBJECT_PATH = /^\/v1\/objects\/([^/]+)\/views\//;
31
+ export function conversationKind(c) {
32
+ const id = c.id;
33
+ if (id === SELF_CHAT)
34
+ return 'self';
35
+ if (id.endsWith('@thread.tacv2'))
36
+ return 'channel';
37
+ const tp = c.threadProperties ?? {};
38
+ if (id.startsWith('19:meeting_') ||
39
+ /meeting/i.test(tp.productThreadType ?? '') ||
40
+ /meeting/i.test(tp.threadType ?? '')) {
41
+ return 'meeting';
42
+ }
43
+ if (id.endsWith('@unq.gbl.spaces'))
44
+ return 'oneOnOne';
45
+ return 'group';
46
+ }
47
+ /**
48
+ * The arrival time (epoch ms) of the last message the user has read: the first
49
+ * segment of `consumptionhorizon` (`"<lastReadArrivalMs>;<clientMs>;<messageId>"`).
50
+ * 0 — everything unread — when absent or unparseable.
51
+ */
52
+ export function readHorizon(c) {
53
+ const raw = c.properties?.consumptionhorizon;
54
+ if (typeof raw !== 'string')
55
+ return 0;
56
+ const n = Number(raw.split(';')[0]);
57
+ return Number.isFinite(n) && n > 0 ? n : 0;
58
+ }
59
+ /** The sender's MRI (`8:orgid:<oid>`): `from` is a URL ending in it. */
60
+ export function senderMri(from) {
61
+ if (typeof from !== 'string' || from === '')
62
+ return undefined;
63
+ const mri = from.slice(from.lastIndexOf('/') + 1);
64
+ return mri === '' ? undefined : mri;
65
+ }
66
+ /** True for a message a person wrote, false for a system event. */
67
+ export function isUserMessage(m) {
68
+ return USER_MESSAGE_TYPES.has(m.messagetype ?? '');
69
+ }
70
+ function isDeleted(m) {
71
+ const t = m.properties?.deletetime;
72
+ return t !== undefined && t !== null && t !== '' && t !== 0;
73
+ }
74
+ /**
75
+ * Unread = arrived after the read horizon (a message id IS its arrival ms),
76
+ * written by someone other than the user, a real message, and not deleted.
77
+ */
78
+ export function isUnread(m, horizon, meMri) {
79
+ const arrival = Number(m.id);
80
+ if (!Number.isFinite(arrival) || arrival <= horizon)
81
+ return false;
82
+ if (senderMri(m.from) === meMri)
83
+ return false;
84
+ return isUserMessage(m) && !isDeleted(m);
85
+ }
86
+ function toIso(value) {
87
+ if (typeof value !== 'string' || value === '')
88
+ return undefined;
89
+ const d = new Date(value);
90
+ return Number.isNaN(d.getTime()) ? undefined : d.toISOString();
91
+ }
92
+ function nonEmpty(s) {
93
+ const t = s?.trim();
94
+ return t ? t : undefined;
95
+ }
96
+ /** A team's thread: its own `spaceId`, or a `space` thread type. */
97
+ function isTeamThread(c) {
98
+ const tp = c.threadProperties ?? {};
99
+ return tp.spaceId === c.id || tp.threadType === 'space';
100
+ }
101
+ /**
102
+ * A team's name from its own thread: the topic, else the space/topic-thread
103
+ * topic Teams sometimes carries instead, else {@link UNNAMED_TEAM}.
104
+ */
105
+ function teamName(team) {
106
+ const tp = team.threadProperties ?? {};
107
+ return nonEmpty(tp.topic) ?? nonEmpty(tp.spaceThreadTopic) ?? nonEmpty(tp.topicThreadTopic) ?? UNNAMED_TEAM;
108
+ }
109
+ /**
110
+ * `properties.lastimreceivedtime` as epoch ms. Despite the name it moves for
111
+ * system events too (a call recording sets it to that message's id), so it
112
+ * says only that SOMETHING arrived, not that a real message did. Seen as an ISO string; epoch ms (a number or a
113
+ * numeric string) is read too. `undefined` when absent or unparseable.
114
+ */
115
+ export function lastImReceivedMs(c) {
116
+ const raw = c.properties?.lastimreceivedtime;
117
+ let ms;
118
+ if (typeof raw === 'number')
119
+ ms = raw;
120
+ else if (typeof raw === 'string' && /^\s*\d+\s*$/.test(raw))
121
+ ms = Number(raw);
122
+ else if (typeof raw === 'string' && raw.trim() !== '')
123
+ ms = Date.parse(raw);
124
+ else
125
+ return undefined;
126
+ return Number.isFinite(ms) && ms > 0 ? ms : undefined;
127
+ }
128
+ /**
129
+ * The conversation's newest activity of any kind (epoch ms): the later of the
130
+ * last message's arrival (its id) and `lastimreceivedtime`, since either can
131
+ * lag the other. `undefined` when the listing carries neither. Nothing real
132
+ * can be unread after this, so it bounds how recent an unread message can be.
133
+ */
134
+ export function newestActivityMs(c) {
135
+ const lastArrival = c.lastMessage !== undefined ? Number(c.lastMessage.id) : NaN;
136
+ const signals = [lastArrival, lastImReceivedMs(c)].filter((n) => n !== undefined && Number.isFinite(n) && n > 0);
137
+ return signals.length === 0 ? undefined : Math.max(...signals);
138
+ }
139
+ /** A listing field that is epoch ms, as a number or a numeric string; `undefined` otherwise. */
140
+ function epochMs(raw) {
141
+ const ms = typeof raw === 'number' ? raw : typeof raw === 'string' && /^\s*\d+\s*$/.test(raw) ? Number(raw) : NaN;
142
+ return Number.isFinite(ms) && ms > 0 ? ms : undefined;
143
+ }
144
+ /**
145
+ * The conversation's newest change of any kind (epoch ms): {@link newestActivityMs}
146
+ * or the last updated message's id or version, whichever is later. Live
147
+ * (2026-10-12), a channel reply moves only `lastUpdatedMessageId` /
148
+ * `lastUpdatedMessageVersion` — `lastMessage` stays on the newest root post —
149
+ * so this is what says a channel thread got a reply. It also moves for an
150
+ * edit or a reaction, so a conversation past a time by this measure may hold
151
+ * no new message: only a read can tell. `undefined` when the listing carries
152
+ * none of them.
153
+ */
154
+ export function lastChangeMs(c) {
155
+ const signals = [newestActivityMs(c), epochMs(c.lastUpdatedMessageId), epochMs(c.lastUpdatedMessageVersion)].filter((n) => n !== undefined);
156
+ return signals.length === 0 ? undefined : Math.max(...signals);
157
+ }
158
+ /**
159
+ * Whether the conversation is an unread CANDIDATE: its newest activity — the
160
+ * later of `lastimreceivedtime` and the last message's arrival, of any type —
161
+ * is past the read horizon (0 for a conversation never opened), and is not
162
+ * the user's own doing.
163
+ *
164
+ * Only a candidate. Measured live (2026-10-10): `lastimreceivedtime` equals
165
+ * the last message's id even when that is a call recording, and `lastMessage`
166
+ * can be stale (older than system events after it), so neither can say a real
167
+ * message is waiting. The tools confirm a candidate by reading the messages
168
+ * past the horizon. A false here is reliable: nothing at all came after the
169
+ * horizon, or the newest thing is the user's own message.
170
+ */
171
+ export function isUnreadCandidate(c, meMri) {
172
+ const horizon = readHorizon(c);
173
+ const last = c.lastMessage;
174
+ const lastArrival = last !== undefined ? Number(last.id) : NaN;
175
+ const newest = newestActivityMs(c);
176
+ if (newest === undefined || newest <= horizon)
177
+ return false;
178
+ // The newest thing is the user's own doing: they were there for it.
179
+ const lastIsMine = last !== undefined && senderMri(last.from) === meMri;
180
+ return !(lastIsMine && lastArrival >= newest);
181
+ }
182
+ /**
183
+ * The other person's MRI in a 1:1: its id is `19:<oid>_<oid>@unq.gbl.spaces`,
184
+ * the two people's AAD object ids, so the one that is not the user's is
185
+ * theirs (`8:orgid:<oid>`). `undefined` when the id is not shaped so or does
186
+ * not name the user — then the listing cannot say who the other person is.
187
+ */
188
+ export function oneOnOnePeerMri(id, meMri) {
189
+ const m = /^19:([^_@]+)_([^_@]+)@unq\.gbl\.spaces$/.exec(id);
190
+ const prefix = '8:orgid:';
191
+ if (m === null || !meMri.startsWith(prefix))
192
+ return undefined;
193
+ const mine = meMri.slice(prefix.length).toLowerCase();
194
+ const [a, b] = [m[1], m[2]];
195
+ if (a.toLowerCase() === mine && b.toLowerCase() !== mine)
196
+ return `${prefix}${b}`;
197
+ if (b.toLowerCase() === mine && a.toLowerCase() !== mine)
198
+ return `${prefix}${a}`;
199
+ return undefined;
200
+ }
201
+ /** True when the sender's MRI is `mri`, ignoring case (oids are GUIDs). */
202
+ export function isFromMri(from, mri) {
203
+ return senderMri(from)?.toLowerCase() === mri.toLowerCase();
204
+ }
205
+ /** A `properties` flag Teams sends as `"true"` / `"True"` (or, defensively, a boolean). */
206
+ function flag(c, name) {
207
+ const v = c.properties?.[name];
208
+ return v === true || (typeof v === 'string' && v.trim().toLowerCase() === 'true');
209
+ }
210
+ /** A `properties` flag Teams sends as `"false"` / `"False"` (or a boolean) — absent is not false. */
211
+ function flagOff(c, name) {
212
+ const v = c.properties?.[name];
213
+ return v === false || (typeof v === 'string' && v.trim().toLowerCase() === 'false');
214
+ }
215
+ /** A channel the user has hidden in Teams. */
216
+ function isHiddenChannel(c) {
217
+ return c.memberProperties?.interest === 'NotInterested';
218
+ }
219
+ export function conversationSummary(c, meMri, all = []) {
220
+ const kind = conversationKind(c);
221
+ const tp = c.threadProperties ?? {};
222
+ const last = c.lastMessage;
223
+ const systemEvent = last !== undefined && !isUserMessage(last);
224
+ const lastFromMe = last !== undefined && senderMri(last.from) === meMri;
225
+ // A system event's display name is whoever triggered it, not a sender.
226
+ const lastSender = systemEvent ? undefined : nonEmpty(last?.imdisplayname);
227
+ const ownTeam = kind === 'channel' && isTeamThread(c);
228
+ let title = kind === 'self' ? SELF_CHAT_TITLE : ownTeam ? 'General' : nonEmpty(tp.topic);
229
+ let participants;
230
+ if (title === undefined && kind === 'oneOnOne') {
231
+ // A 1:1 is named after the other person, whom its id names. The listing
232
+ // knows their name only when they sent the last message; otherwise
233
+ // `tools/titles.ts` finds it in their recent messages.
234
+ const peer = oneOnOnePeerMri(c.id, meMri);
235
+ const fromPeer = peer !== undefined ? last !== undefined && isFromMri(last.from, peer) : !lastFromMe;
236
+ const name = fromPeer ? lastSender : undefined;
237
+ title = name ?? UNTITLED_ONE_ON_ONE_TITLE;
238
+ if (name !== undefined)
239
+ participants = [name];
240
+ }
241
+ else if (title === undefined) {
242
+ // An untopiced group chat's last sender is only a stand-in: `tools/titles.ts`
243
+ // names it after its recent participants instead.
244
+ const untitled = kind === 'group' ? UNTITLED_GROUP_TITLE : '(untitled chat)';
245
+ title = kind === 'channel' ? 'General' : (!lastFromMe ? lastSender : undefined) ?? untitled;
246
+ }
247
+ let team;
248
+ if (kind === 'channel') {
249
+ const teamThread = ownTeam ? c : tp.spaceId ? all.find((x) => x.id === tp.spaceId) : undefined;
250
+ if (teamThread !== undefined)
251
+ team = teamName(teamThread);
252
+ }
253
+ const lastActivity = last ? (toIso(last.originalarrivaltime) ?? toIso(last.composetime)) : undefined;
254
+ const preview = systemEvent ? SYSTEM_EVENT_PREVIEW : last?.content !== undefined ? htmlToText(last.content) : undefined;
255
+ const unread = isUnreadCandidate(c, meMri);
256
+ const hidden = kind === 'channel' && isHiddenChannel(c);
257
+ return {
258
+ id: c.id,
259
+ kind,
260
+ title,
261
+ ...(team !== undefined ? { team } : {}),
262
+ unread,
263
+ unread_confirmed: false,
264
+ ...(hidden ? { hidden: true } : {}),
265
+ ...(flagOff(c, 'alerts') ? { muted: true } : {}),
266
+ ...(flag(c, 'favorite') ? { favorite: true } : {}),
267
+ ...(flag(c, 'ispinned') ? { pinned: true } : {}),
268
+ ...(lastActivity !== undefined ? { lastActivity } : {}),
269
+ ...(preview ? { lastMessagePreview: truncate(preview, PREVIEW_CHARS) } : {}),
270
+ ...(lastSender !== undefined ? { lastSender } : {}),
271
+ ...(participants !== undefined ? { participants } : {}),
272
+ };
273
+ }
274
+ function truncate(s, max) {
275
+ return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
276
+ }
277
+ /*
278
+ * Placeholders that survive tag-stripping, so blockquote depth can be applied
279
+ * after the text is decoded. Control characters never come out of entity
280
+ * decoding (it drops them), so a message cannot forge one.
281
+ */
282
+ const QUOTE_OPEN = '\u0001';
283
+ const QUOTE_CLOSE = '\u0002';
284
+ const NAMED_ENTITIES = {
285
+ amp: '&',
286
+ lt: '<',
287
+ gt: '>',
288
+ quot: '"',
289
+ apos: "'",
290
+ nbsp: ' ',
291
+ };
292
+ function decodeEntities(s) {
293
+ // One pass, so `&amp;lt;` becomes `&lt;` and not `<`.
294
+ return s.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi, (whole, dec, hex, name) => {
295
+ if (name !== undefined)
296
+ return NAMED_ENTITIES[name.toLowerCase()] ?? whole;
297
+ const code = dec !== undefined ? Number(dec) : parseInt(hex, 16);
298
+ if (!Number.isFinite(code) || code > 0x10ffff)
299
+ return whole;
300
+ // Drop control characters (keeping tab/newline): they carry no text and
301
+ // would collide with the quote placeholders.
302
+ if (code < 0x20 && code !== 0x09 && code !== 0x0a)
303
+ return '';
304
+ return String.fromCodePoint(code);
305
+ });
306
+ }
307
+ function attr(tag, name) {
308
+ const m = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i').exec(tag);
309
+ return m ? (m[1] ?? m[2]) : undefined;
310
+ }
311
+ const stripTags = (s) => s.replace(/<\/?[a-z!][^>]*>/gi, '');
312
+ /**
313
+ * One table row on one line, its `<td>`/`<th>` cells joined by ` | ` — a
314
+ * pasted table (a file-monitor report, a status grid) otherwise runs its cells
315
+ * together. Line breaks inside a cell become spaces so the row stays whole.
316
+ */
317
+ function tableRow(row) {
318
+ const cells = [...row.matchAll(/<t[dh]\b[^>]*>([\s\S]*?)(?:<\/t[dh]\s*>|(?=<t[dh]\b)|$)/gi)].map(([, cell]) => cell
319
+ .replace(/[\u0001\u0002]/g, '')
320
+ .replace(/<br\s*\/?>|<\/?(p|div|li|h[1-6])\b[^>]*>|\r?\n/gi, ' ')
321
+ .trim());
322
+ return cells.length > 0 ? cells.join(' | ') : row;
323
+ }
324
+ /**
325
+ * A Teams message body as readable plain text. Links keep their target as
326
+ * `text (url)`, inline images become `[image]` (emoji become their alt text),
327
+ * a table row becomes one line of ` | `-separated cells, and a quoted reply's
328
+ * lines are prefixed `> `. Never truncated: a long body comes back whole. No
329
+ * HTML library: Teams bodies are a small, regular subset.
330
+ */
331
+ export function htmlToText(html) {
332
+ let s = html.replace(/[\u0001\u0002]/g, '');
333
+ s = s.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/gi, '');
334
+ s = s.replace(/<blockquote\b[^>]*>/gi, `\n${QUOTE_OPEN}\n`).replace(/<\/blockquote\s*>/gi, `\n${QUOTE_CLOSE}\n`);
335
+ s = s.replace(/<img\b[^>]*>/gi, (tag) => {
336
+ const alt = attr(tag, 'alt');
337
+ return /schema\.skype\.com\/Emoji/i.test(attr(tag, 'itemtype') ?? '') && alt ? alt : '[image]';
338
+ });
339
+ s = s.replace(/<a\b([^>]*)>([\s\S]*?)<\/a\s*>/gi, (_whole, attrs, inner) => {
340
+ const href = attr(` ${attrs}`, 'href');
341
+ const label = stripTags(inner).trim();
342
+ if (!href)
343
+ return inner;
344
+ if (label === '' || label === href)
345
+ return href;
346
+ return `${inner} (${href})`;
347
+ });
348
+ s = s.replace(/<tr\b[^>]*>([\s\S]*?)<\/tr\s*>/gi, (_whole, row) => `\n${tableRow(row)}\n`);
349
+ // Block elements start and end a line (a quote's author <strong> runs
350
+ // straight into its <p> otherwise); the blank lines this makes collapse below.
351
+ s = s.replace(/<br\s*\/?>/gi, '\n').replace(/<\/?(p|div|li|tr|h[1-6])\b[^>]*>/gi, '\n');
352
+ s = decodeEntities(stripTags(s));
353
+ const out = [];
354
+ let depth = 0;
355
+ for (const raw of s.split(/\r?\n/)) {
356
+ const line = raw.replace(/[ \t ]+/g, ' ').trim();
357
+ if (line === QUOTE_OPEN)
358
+ depth++;
359
+ else if (line === QUOTE_CLOSE)
360
+ depth = Math.max(0, depth - 1);
361
+ else if (line !== '')
362
+ out.push(`${'> '.repeat(depth)}${line}`);
363
+ }
364
+ return out.join('\n');
365
+ }
366
+ function fileAttachments(raw) {
367
+ let parsed = raw;
368
+ if (typeof raw === 'string') {
369
+ try {
370
+ parsed = JSON.parse(raw);
371
+ }
372
+ catch {
373
+ return [];
374
+ }
375
+ }
376
+ if (!Array.isArray(parsed))
377
+ return [];
378
+ const out = [];
379
+ for (const f of parsed) {
380
+ if (f === null || typeof f !== 'object')
381
+ continue;
382
+ const o = f;
383
+ const info = (o.fileInfo && typeof o.fileInfo === 'object' ? o.fileInfo : {});
384
+ const str = (v) => (typeof v === 'string' && v !== '' ? v : undefined);
385
+ const name = str(o.fileName) ?? str(o.title) ?? '(file)';
386
+ const type = str(o.fileType) ?? str(o.type);
387
+ const openUrl = str(o.openUrl) ?? str(info.shareUrl);
388
+ const url = str(o.objectUrl) ?? str(info.fileUrl);
389
+ out.push({
390
+ name,
391
+ ...(type !== undefined ? { type } : {}),
392
+ ...(openUrl !== undefined ? { openUrl } : {}),
393
+ ...(url !== undefined ? { url } : {}),
394
+ });
395
+ }
396
+ return out;
397
+ }
398
+ function imageAttachments(html) {
399
+ const out = [];
400
+ const seen = new Set();
401
+ for (const [tag] of html.matchAll(/<img\b[^>]*>/gi)) {
402
+ const src = attr(tag, 'src');
403
+ if (!src)
404
+ continue;
405
+ let u;
406
+ try {
407
+ u = new URL(decodeEntities(src));
408
+ }
409
+ catch {
410
+ continue;
411
+ }
412
+ if (u.protocol !== 'https:' || !u.hostname.endsWith(IMAGE_HOST_SUFFIX))
413
+ continue;
414
+ const ref = IMAGE_OBJECT_PATH.exec(u.pathname)?.[1];
415
+ if (!ref || seen.has(ref))
416
+ continue;
417
+ seen.add(ref);
418
+ out.push({ ref, url: u.toString() });
419
+ }
420
+ return out;
421
+ }
422
+ /**
423
+ * `properties.emotions`: a JSON string (or, sometimes, an already-parsed
424
+ * array) of `{ key, users: [{ mri, time }] }`. Keys nobody holds any more are
425
+ * dropped; anything unreadable yields no reactions rather than an error.
426
+ */
427
+ function reactionsOf(raw, meMri) {
428
+ let parsed = raw;
429
+ if (typeof raw === 'string') {
430
+ try {
431
+ parsed = JSON.parse(raw);
432
+ }
433
+ catch {
434
+ return [];
435
+ }
436
+ }
437
+ if (!Array.isArray(parsed))
438
+ return [];
439
+ const out = [];
440
+ for (const e of parsed) {
441
+ if (e === null || typeof e !== 'object')
442
+ continue;
443
+ const { key, users } = e;
444
+ if (typeof key !== 'string' || key === '' || !Array.isArray(users) || users.length === 0)
445
+ continue;
446
+ const byMe = users.some((u) => u?.mri === meMri);
447
+ out.push({ key, count: users.length, byMe });
448
+ }
449
+ return out;
450
+ }
451
+ /**
452
+ * Messages oldest first, by arrival (a message id IS its arrival ms).
453
+ *
454
+ * The service pages newest first but does not strictly order within a page:
455
+ * live, a quote-reply sent 6s after its original came back ahead of it, so a
456
+ * plain reverse() listed the reply first. Ids that are not numbers sort by
457
+ * originalarrivaltime instead, and keep their page order when that is missing.
458
+ */
459
+ export function oldestFirst(messages) {
460
+ const at = (m) => {
461
+ const id = Number(m.id);
462
+ if (Number.isFinite(id))
463
+ return id;
464
+ const t = Date.parse(m.originalarrivaltime ?? '');
465
+ return Number.isNaN(t) ? Number.NaN : t;
466
+ };
467
+ return messages
468
+ .map((m, i) => ({ m, i, t: at(m) }))
469
+ .reverse()
470
+ .sort((a, b) => (Number.isNaN(a.t) || Number.isNaN(b.t) ? 0 : a.t - b.t))
471
+ .map(({ m }) => m);
472
+ }
473
+ /** True when `Intl` knows `tz` as a time zone (an IANA name such as `America/New_York`, or `UTC`). */
474
+ export function isTimeZone(tz) {
475
+ if (tz.trim() === '')
476
+ return false;
477
+ try {
478
+ new Intl.DateTimeFormat('en-US', { timeZone: tz });
479
+ return true;
480
+ }
481
+ catch {
482
+ return false;
483
+ }
484
+ }
485
+ const pad = (n, width = 2) => String(n).padStart(width, '0');
486
+ /**
487
+ * An ISO instant as wall-clock time in `timeZone`, ISO 8601 with that zone's
488
+ * offset at that instant (`2026-10-09T08:05:00.000-04:00`) — so DST is right
489
+ * per message. `undefined` for an unreadable time; `timeZone` must be valid
490
+ * ({@link isTimeZone}).
491
+ */
492
+ export function localIsoTime(iso, timeZone) {
493
+ const ms = Date.parse(iso);
494
+ if (Number.isNaN(ms))
495
+ return undefined;
496
+ const parts = new Intl.DateTimeFormat('en-US', {
497
+ timeZone,
498
+ hourCycle: 'h23',
499
+ year: 'numeric',
500
+ month: '2-digit',
501
+ day: '2-digit',
502
+ hour: '2-digit',
503
+ minute: '2-digit',
504
+ second: '2-digit',
505
+ }).formatToParts(new Date(ms));
506
+ const get = (type) => Number(parts.find((p) => p.type === type)?.value);
507
+ const millis = ((ms % 1000) + 1000) % 1000;
508
+ const wall = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'), get('second'), millis);
509
+ const offsetMin = Math.round((wall - ms) / 60_000);
510
+ const sign = offsetMin < 0 ? '-' : '+';
511
+ const abs = Math.abs(offsetMin);
512
+ return (`${pad(get('year'), 4)}-${pad(get('month'))}-${pad(get('day'))}T${pad(get('hour'))}:${pad(get('minute'))}:` +
513
+ `${pad(get('second'))}.${pad(millis, 3)}${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`);
514
+ }
515
+ export function normaliseMessage(m, meMri, opts = {}) {
516
+ const props = m.properties ?? {};
517
+ const mri = senderMri(m.from);
518
+ const arrival = Number(m.id);
519
+ const time = toIso(m.originalarrivaltime) ??
520
+ toIso(m.composetime) ??
521
+ (Number.isFinite(arrival) ? new Date(arrival).toISOString() : '');
522
+ const subject = typeof props.subject === 'string' ? nonEmpty(props.subject) : undefined;
523
+ const root = /;messageid=(\d+)/.exec(m.conversationLink ?? '')?.[1];
524
+ const content = m.content ?? '';
525
+ const reactions = reactionsOf(props.emotions, meMri);
526
+ const timeLocal = opts.timeZone !== undefined ? localIsoTime(time, opts.timeZone) : undefined;
527
+ return {
528
+ id: m.id,
529
+ time,
530
+ ...(timeLocal !== undefined ? { time_local: timeLocal } : {}),
531
+ sender: nonEmpty(m.imdisplayname) ?? mri ?? 'unknown',
532
+ fromMe: mri !== undefined && mri === meMri,
533
+ text: htmlToText(content),
534
+ ...(subject !== undefined ? { subject } : {}),
535
+ ...(root !== undefined && root !== m.id ? { replyTo: root } : {}),
536
+ edited: props.edittime !== undefined && props.edittime !== null && props.edittime !== '',
537
+ ...(isDeleted(m) ? { deleted: true } : {}),
538
+ attachments: { files: fileAttachments(props.files), images: imageAttachments(content) },
539
+ ...(reactions.length > 0 ? { reactions } : {}),
540
+ };
541
+ }
542
+ /**
543
+ * Every conversation's summary, with the self-chat added when the listing did
544
+ * not carry it — so `48:notes` resolves by id or name whether or not Teams
545
+ * listed it.
546
+ */
547
+ export function summariseAll(raw, meMri) {
548
+ const out = raw.map((c) => conversationSummary(c, meMri, raw));
549
+ if (!out.some((s) => s.id === SELF_CHAT))
550
+ out.push(conversationSummary({ id: SELF_CHAT }, meMri));
551
+ return out;
552
+ }
553
+ /**
554
+ * Resolve a user's `conversation` argument: an exact id wins outright, then
555
+ * `notes` / `self` name the self-chat, else a case-insensitive substring of
556
+ * the title, team name, or one of an untitled group chat's participants (and,
557
+ * with `messages`, the last-message preview). A title this server made up —
558
+ * "Group chat: …", "(untitled group chat)", or an untitled 1:1's other person
559
+ * — is not itself matched, so "group" or "chat" does not hit every untitled
560
+ * group chat: such a chat matches by its participants instead. Each match is a
561
+ * copy carrying its {@link MatchReason} — the first that applies, in order.
562
+ */
563
+ export function matchConversations(summaries, query, { messages = false } = {}) {
564
+ const exact = summaries.find((s) => s.id === query);
565
+ if (exact)
566
+ return [{ ...exact, match_reason: 'id' }];
567
+ const q = query.trim().toLowerCase();
568
+ if (q === '')
569
+ return [];
570
+ if (SELF_CHAT_ALIASES.has(q)) {
571
+ const self = summaries.find((s) => s.id === SELF_CHAT);
572
+ if (self)
573
+ return [{ ...self, match_reason: 'title' }];
574
+ }
575
+ return summaries.flatMap((s) => {
576
+ const reason = matchReason(s, q, messages);
577
+ return reason === undefined ? [] : [{ ...s, match_reason: reason }];
578
+ });
579
+ }
580
+ /** The first reason `s` matches the lower-cased query `q`, or `undefined`. */
581
+ function matchReason(s, q, messages) {
582
+ if (hasRealTitle(s) && s.title.toLowerCase().includes(q))
583
+ return 'title';
584
+ if (s.team?.toLowerCase().includes(q))
585
+ return 'team';
586
+ if (s.participants?.some((p) => p.toLowerCase().includes(q)))
587
+ return 'participant';
588
+ if (messages && s.lastMessagePreview !== undefined && s.lastMessagePreview !== SYSTEM_EVENT_PREVIEW) {
589
+ if (s.lastMessagePreview.toLowerCase().includes(q))
590
+ return 'message';
591
+ }
592
+ return undefined;
593
+ }
594
+ /**
595
+ * False for a title made from participants (an untitled group chat's, or an
596
+ * untitled 1:1's other person — only such chats carry `participants`), or an
597
+ * untitled-group / untitled-1:1 stand-in.
598
+ */
599
+ function hasRealTitle(s) {
600
+ if (s.title === UNTITLED_GROUP_TITLE || s.title === UNTITLED_ONE_ON_ONE_TITLE)
601
+ return false;
602
+ return s.participants === undefined;
603
+ }