@usejunior/provider-microsoft 0.1.9 → 0.1.11

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.
@@ -1,4 +1,4 @@
1
- import { AttachmentNotSupportedError, AttachmentNotFoundError } from '@usejunior/email-core';
1
+ import { AttachmentNotSupportedError, AttachmentNotFoundError, ProviderError } from '@usejunior/email-core';
2
2
  const BODY_SIZE_LIMIT = 3.5 * 1024 * 1024; // 3.5MB
3
3
  const SUBJECT_MAX_LENGTH = 255;
4
4
  // Microsoft Graph's hard cap is on the *encoded write request* size, not the
@@ -42,6 +42,15 @@ function checkGraphAttachmentLimits(attachments, opts) {
42
42
  }
43
43
  return null;
44
44
  }
45
+ /**
46
+ * Map an address list to Graph `recipient` resources. Returns `undefined` for a
47
+ * missing list so callers can spread it into a payload without emitting an
48
+ * explicit `null` — on a PATCH that would clear the field rather than leave it
49
+ * untouched.
50
+ */
51
+ function toGraphRecipients(addrs) {
52
+ return addrs?.map(r => ({ emailAddress: { address: r.email, name: r.name } }));
53
+ }
45
54
  /** Build a Graph `fileAttachment` resource from an OutboundAttachment. */
46
55
  function toGraphFileAttachment(att) {
47
56
  return {
@@ -68,6 +77,8 @@ class GraphAttachmentError extends Error {
68
77
  }
69
78
  // Sent message tracking via custom extended property
70
79
  const TRACKING_PROPERTY = 'String {66f5a359-4659-4830-9070-00047ec6ac6e} Name AgentEmailTrackingId';
80
+ const DRAFT_ORIGIN_PROPERTY = 'String {66f5a359-4659-4830-9070-00047ec6ac6e} Name AgentEmailDraftOrigin';
81
+ const DEFERRED_SEND_PROPERTY = 'SystemTime 0x3FEF';
71
82
  const WELL_KNOWN_FOLDER_ALIASES = {
72
83
  archive: 'archive',
73
84
  archived: 'archive',
@@ -83,6 +94,68 @@ const WELL_KNOWN_FOLDER_ALIASES = {
83
94
  spam: 'junkemail',
84
95
  trash: 'deleteditems',
85
96
  };
97
+ const SYSTEM_FOLDER_NAMES = [
98
+ 'archive',
99
+ 'clutter',
100
+ 'conflicts',
101
+ 'conversationhistory',
102
+ 'deleteditems',
103
+ 'drafts',
104
+ 'inbox',
105
+ 'junkemail',
106
+ 'localfailures',
107
+ 'msgfolderroot',
108
+ 'outbox',
109
+ 'recoverableitemsdeletions',
110
+ 'scheduled',
111
+ 'searchfolders',
112
+ 'sentitems',
113
+ 'serverfailures',
114
+ 'syncissues',
115
+ ];
116
+ const SYSTEM_FOLDER_NAME_SET = new Set([
117
+ ...SYSTEM_FOLDER_NAMES,
118
+ ...Object.keys(WELL_KNOWN_FOLDER_ALIASES),
119
+ ]);
120
+ const FOLDER_CACHE_TTL_MS = 60_000;
121
+ // Cap on Graph requests for a single folder-tree snapshot. Pagination is capped
122
+ // per collection, but recursion across a deep/wide mailbox would otherwise
123
+ // issue one request per folder — enough to blow the MCP request timeout or trip
124
+ // Graph throttling. Exceeding this TRUNCATES the listing rather than failing:
125
+ // a partial folder list is still useful, whereas a hard error would break
126
+ // list_folders outright on legitimately large mailboxes. Truncated snapshots
127
+ // are never cached, so the next call retries from scratch, and name resolution
128
+ // refuses to answer from a truncated tree (see resolveFolderId).
129
+ const MAX_FOLDER_REQUESTS_PER_SNAPSHOT = 400;
130
+ // Filing mail into these is equivalent to the blocked `delete` rule action.
131
+ const DESTRUCTIVE_RULE_DESTINATIONS = new Set([
132
+ 'deleteditems',
133
+ 'recoverableitemsdeletions',
134
+ 'scheduled',
135
+ 'serverfailures',
136
+ 'localfailures',
137
+ 'syncissues',
138
+ 'conflicts',
139
+ ]);
140
+ // Graph accepts rule action keys case-insensitively; compare normalized keys.
141
+ const BLOCKED_RULE_ACTIONS = new Set([
142
+ 'forwardto',
143
+ 'forwardasattachmentto',
144
+ 'redirectto',
145
+ 'delete',
146
+ ]);
147
+ // Normalized (lowercased) safe action key -> canonical Graph camelCase key.
148
+ // Doubles as the allowlist: a key absent here is rejected. Keys are normalized
149
+ // before lookup so `MoveToFolder`/`MOVETOFOLDER` all map to `moveToFolder`.
150
+ const CANONICAL_RULE_ACTIONS = {
151
+ assigncategories: 'assignCategories',
152
+ copytofolder: 'copyToFolder',
153
+ markasread: 'markAsRead',
154
+ markimportance: 'markImportance',
155
+ movetofolder: 'moveToFolder',
156
+ stopprocessingrules: 'stopProcessingRules',
157
+ };
158
+ const FOLDER_SELECT = '$select=id,displayName,parentFolderId,childFolderCount,unreadItemCount,totalItemCount,isHidden';
86
159
  /** Delta query select fields for efficiency */
87
160
  const DELTA_SELECT = '$select=subject,from,toRecipients,ccRecipients,receivedDateTime,hasAttachments,isRead,id';
88
161
  // Attachments are polymorphic: $select against the base type fails for derived-only props.
@@ -91,6 +164,32 @@ const DELTA_SELECT = '$select=subject,from,toRecipients,ccRecipients,receivedDat
91
164
  // base attachment: https://learn.microsoft.com/en-us/graph/api/resources/attachment?view=graph-rest-1.0
92
165
  // fileAttachment: https://learn.microsoft.com/en-us/graph/api/resources/fileattachment?view=graph-rest-1.0
93
166
  const ATTACHMENT_SELECT = 'id,name,contentType,size,isInline,microsoft.graph.fileAttachment/contentId';
167
+ // `uniqueBody` is returned only when explicitly selected. Because adding
168
+ // `$select=uniqueBody` would narrow Graph's response, list every message field
169
+ // consumed by mapGraphMessage and widen the existing getMessage projection.
170
+ const MESSAGE_SELECT = [
171
+ 'id',
172
+ 'subject',
173
+ 'from',
174
+ 'toRecipients',
175
+ 'ccRecipients',
176
+ 'bccRecipients',
177
+ 'receivedDateTime',
178
+ 'isRead',
179
+ 'hasAttachments',
180
+ 'body',
181
+ 'categories',
182
+ 'conversationId',
183
+ 'flag',
184
+ 'internetMessageId',
185
+ 'internetMessageHeaders',
186
+ 'uniqueBody',
187
+ // Without this, the explicit projection on getMessage/getThread narrows away
188
+ // the only signal that a message is an unsent draft, and a draft reply reads
189
+ // as though it had already been sent. list/search send no $select, so Graph's
190
+ // default projection already carries it there.
191
+ 'isDraft',
192
+ ].join(',');
94
193
  // Graph message and attachment IDs are base64url-flavored and routinely contain
95
194
  // `=`, `+`, `/`, `_`, `-`. Path segments must encode `+`, `/`, and `=` or Graph
96
195
  // returns 400/404. encodeURIComponent handles all three plus `?`, `#`, `&`.
@@ -191,6 +290,8 @@ export class GraphApiError extends Error {
191
290
  export class GraphEmailProvider {
192
291
  client;
193
292
  basePath;
293
+ folderCache;
294
+ systemFolderIdsCache;
194
295
  constructor(client, userId = 'me') {
195
296
  this.client = client;
196
297
  // For delegated auth, use /me/. For app-only, use /users/{id}/.
@@ -216,7 +317,7 @@ export class GraphEmailProvider {
216
317
  }
217
318
  async getMessage(id) {
218
319
  const encodedId = encodeGraphPathId(id);
219
- const expandedUrl = `${this.basePath}/messages/${encodedId}?$expand=attachments($select=${ATTACHMENT_SELECT})`;
320
+ const expandedUrl = `${this.basePath}/messages/${encodedId}?$select=${MESSAGE_SELECT}&$expand=attachments($select=${ATTACHMENT_SELECT})`;
220
321
  try {
221
322
  const response = await this.client.get(expandedUrl);
222
323
  return mapGraphMessage(response);
@@ -227,7 +328,7 @@ export class GraphEmailProvider {
227
328
  if (!(err instanceof GraphApiError) || err.status !== 400)
228
329
  throw err;
229
330
  }
230
- const message = await this.client.get(`${this.basePath}/messages/${encodedId}`);
331
+ const message = await this.client.get(`${this.basePath}/messages/${encodedId}?$select=${MESSAGE_SELECT}`);
231
332
  const attachments = await this.client.get(`${this.basePath}/messages/${encodedId}/attachments?$select=${ATTACHMENT_SELECT}`);
232
333
  return mapGraphMessage({
233
334
  ...message,
@@ -273,15 +374,47 @@ export class GraphEmailProvider {
273
374
  if (conversationId) {
274
375
  const params = new URLSearchParams();
275
376
  params.set('$filter', `conversationId eq '${conversationId}'`);
276
- const response = await this.client.get(`${this.basePath}/messages?${params}`);
277
- const messages = (response.value ?? [])
377
+ // No `$orderby`: Graph rejects (`InefficientFilter`) an `$orderby` on a
378
+ // property that isn't also the `$filter` property, and we fetch every
379
+ // page and sort locally anyway — so ordering server-side buys nothing.
380
+ params.set('$top', '50');
381
+ const graphMessages = [];
382
+ const visitedUrls = new Set();
383
+ const maxPages = 100;
384
+ let url = `${this.basePath}/messages?${params}`;
385
+ let truncated = false;
386
+ // Page through the whole conversation (follow @odata.nextLink). The
387
+ // maxPages / visitedUrls guards bound a pathological or looping nextLink;
388
+ // on hitting them we stop and return what we have (flagged truncated)
389
+ // rather than throwing away every message already fetched.
390
+ while (url) {
391
+ if (visitedUrls.size >= maxPages || visitedUrls.has(url)) {
392
+ console.warn(`[GraphEmailProvider] getThread hit pagination safety limit for conversation ${conversationId}; returning ${graphMessages.length} messages fetched so far`);
393
+ truncated = true;
394
+ break;
395
+ }
396
+ visitedUrls.add(url);
397
+ const response = await this.client.get(url);
398
+ graphMessages.push(...(response.value ?? []));
399
+ url = response['@odata.nextLink'];
400
+ }
401
+ let messages = graphMessages
278
402
  .map(mapGraphMessage)
279
403
  .sort((a, b) => a.receivedAt.localeCompare(b.receivedAt));
404
+ // Guarantee the queried message is present. The conversationId index can
405
+ // lag a just-arrived message (Graph eventual consistency), so if the
406
+ // paged results omit it, splice in the copy we already fetched above so
407
+ // get_thread(id) always anchors on and includes the passed id.
408
+ // receivedDateTime is ISO 8601 here, so localeCompare sorts chronologically.
409
+ if (!messages.some(m => m.id === message.id)) {
410
+ messages = [...messages, message].sort((a, b) => a.receivedAt.localeCompare(b.receivedAt));
411
+ }
280
412
  return {
281
413
  id: conversationId,
282
414
  subject: message.subject,
283
415
  messages,
284
416
  messageCount: messages.length,
417
+ ...(truncated ? { isTruncated: true } : {}),
285
418
  };
286
419
  }
287
420
  return { id: messageId, subject: message.subject, messages: [message], messageCount: 1 };
@@ -373,12 +506,132 @@ export class GraphEmailProvider {
373
506
  await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(messageId)}`, { isRead });
374
507
  }
375
508
  async moveToFolder(messageId, folder) {
376
- // Graph POST /move returns the moved message with a NEW id
509
+ // Graph POST /move returns the moved message with a NEW id.
510
+ // Resolve against the cache (not forWrite): a move does not alter the folder
511
+ // tree, and a triage loop can move dozens of messages per pass — forcing a
512
+ // fresh traversal per move would trip Graph throttling. The residual risk is
513
+ // the same 60s rename-race we accept for reads: at worst a message lands in
514
+ // a renamed-but-valid folder, which is recoverable, not lost.
515
+ const destinationId = await this.resolveFolderId(folder);
377
516
  const result = await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(messageId)}/move`, {
378
- destinationId: normalizeFolderId(folder),
517
+ destinationId,
379
518
  });
380
519
  return result.id ?? messageId;
381
520
  }
521
+ async listFolders() {
522
+ const { folders } = await this.getFolderSnapshot();
523
+ return folders.map(folder => ({ ...folder }));
524
+ }
525
+ async createFolder(displayName, parentFolder = 'inbox') {
526
+ const trimmedName = displayName.trim();
527
+ if (!trimmedName) {
528
+ throw new ProviderError('INVALID_FOLDER_NAME', 'Folder display name cannot be empty', 'microsoft', false);
529
+ }
530
+ const parentId = await this.resolveFolderId(parentFolder, true);
531
+ const parentPath = await this.folderPathFor(parentFolder, parentId);
532
+ const created = await this.client.post(`${this.basePath}/mailFolders/${encodeGraphPathId(parentId)}/childFolders`, { displayName: trimmedName });
533
+ this.invalidateFolderCaches();
534
+ return mapGraphFolder(created, parentPath ? `${parentPath}/${trimmedName}` : trimmedName);
535
+ }
536
+ async deleteFolder(folder) {
537
+ const normalizedInput = normalizeFolderLookup(folder);
538
+ if (SYSTEM_FOLDER_NAME_SET.has(normalizedInput)) {
539
+ throw systemFolderProtectedError(folder);
540
+ }
541
+ const folderId = await this.resolveFolderId(folder, true);
542
+ const systemFolderIds = await this.getSystemFolderIds();
543
+ if (systemFolderIds.has(folderId)) {
544
+ throw systemFolderProtectedError(folder);
545
+ }
546
+ await this.client.delete(`${this.basePath}/mailFolders/${encodeGraphPathId(folderId)}`);
547
+ this.invalidateFolderCaches();
548
+ }
549
+ async listInboxRules() {
550
+ const rules = [];
551
+ const visitedUrls = new Set();
552
+ let url = `${this.basePath}/mailFolders/inbox/messageRules`;
553
+ while (url) {
554
+ if (visitedUrls.has(url) || visitedUrls.size >= 100) {
555
+ throw new ProviderError('PAGINATION_LIMIT', 'Inbox rule pagination exceeded its safety limit', 'microsoft', false);
556
+ }
557
+ visitedUrls.add(url);
558
+ const response = await this.client.get(url);
559
+ rules.push(...(response.value ?? []));
560
+ url = response['@odata.nextLink'];
561
+ }
562
+ return rules;
563
+ }
564
+ async createInboxRule(rule) {
565
+ // Defense in depth: the create_inbox_rule action already enforces an
566
+ // allowlist, but this method is part of the public EmailRuleManager
567
+ // interface and must be safe when called directly. Graph treats JSON keys
568
+ // case-insensitively, so a case-sensitive blocklist alone would let
569
+ // `ForwardTo` through — match on the normalized key and allowlist rather
570
+ // than blocklist, so unknown future Graph actions fail closed.
571
+ // Rebuild the actions object with canonical camelCase keys. Graph accepts
572
+ // keys case-insensitively, so a caller passing `MoveToFolder` would pass
573
+ // the normalized allowlist check yet slip past a case-sensitive
574
+ // `actions['moveToFolder']` destructive-destination check below. Normalizing
575
+ // keys up front closes that bypass and guarantees the payload we POST uses
576
+ // exactly the safe keys we validated.
577
+ const actions = {};
578
+ for (const [key, value] of Object.entries(rule.actions)) {
579
+ const normalized = key.trim().toLowerCase();
580
+ if (BLOCKED_RULE_ACTIONS.has(normalized)) {
581
+ throw new ProviderError('UNSAFE_RULE_ACTION', `Inbox rule action '${key}' is blocked for security`, 'microsoft', false);
582
+ }
583
+ const canonical = CANONICAL_RULE_ACTIONS[normalized];
584
+ if (!canonical) {
585
+ throw new ProviderError('UNSUPPORTED_RULE_ACTION', `Inbox rule action '${key}' is not supported for creation`, 'microsoft', false);
586
+ }
587
+ // Validate value shapes locally instead of forwarding wrong-typed values
588
+ // to Graph. A non-string moveToFolder would otherwise skip the
589
+ // destructive-destination inspection entirely (it only fires on strings).
590
+ if (!isValidRuleActionValue(canonical, value)) {
591
+ throw new ProviderError('INVALID_RULE_ACTION_VALUE', `Inbox rule action '${key}' has an invalid value for its type`, 'microsoft', false);
592
+ }
593
+ actions[canonical] = value;
594
+ }
595
+ // Resolve folder destinations to opaque ids and reject mail-discarding ones.
596
+ // resolveRuleDestinationId does the destructive check on the canonical
597
+ // resolved folder, closing alias/slash/case bypasses like `/trash/`.
598
+ for (const folderAction of ['moveToFolder', 'copyToFolder']) {
599
+ const destination = actions[folderAction];
600
+ if (typeof destination === 'string') {
601
+ actions[folderAction] = await this.resolveRuleDestinationId(destination);
602
+ }
603
+ }
604
+ // Graph rejects sequence 0 (`MessageRuleValidationError` on Field 'Sequence'),
605
+ // which is exactly the value it assigns when a POST omits sequence. The tool
606
+ // exists so an agent can propose a rule without knowing Exchange internals,
607
+ // so when the caller doesn't specify one, append the rule after the existing
608
+ // rules (max existing sequence + 1, or 1 for an empty mailbox).
609
+ const GRAPH_MAX_SEQUENCE = 2_147_483_647; // Graph stores sequence as Int32.
610
+ let sequence = rule.sequence;
611
+ if (sequence === undefined || sequence === null) {
612
+ const existing = await this.listInboxRules();
613
+ const maxExisting = existing.reduce((max, r) => Math.max(max, r.sequence ?? 0), 0);
614
+ // Defensive: never exceed Int32 (a pathological existing sequence at the
615
+ // ceiling would otherwise overflow to an invalid value).
616
+ sequence = Math.min(maxExisting + 1, GRAPH_MAX_SEQUENCE);
617
+ }
618
+ else if (!Number.isInteger(sequence) || sequence < 1 || sequence > GRAPH_MAX_SEQUENCE) {
619
+ // The action schema already enforces this, but the provider is a public
620
+ // interface — reject an out-of-range explicit sequence rather than letting
621
+ // Graph fail it with an opaque 400.
622
+ throw new ProviderError('INVALID_RULE_SEQUENCE', `Inbox rule sequence must be an integer between 1 and ${GRAPH_MAX_SEQUENCE}; received ${sequence}`, 'microsoft', false);
623
+ }
624
+ // Spread `actions` last so the canonicalized/resolved actions replace the
625
+ // caller's original (possibly mis-cased) actions in the payload.
626
+ return await this.client.post(`${this.basePath}/mailFolders/inbox/messageRules`, {
627
+ ...rule,
628
+ sequence,
629
+ actions,
630
+ });
631
+ }
632
+ async deleteInboxRule(id) {
633
+ await this.client.delete(`${this.basePath}/mailFolders/inbox/messageRules/${encodeGraphPathId(id)}`);
634
+ }
382
635
  async deleteMessage(messageId, hard = false) {
383
636
  if (hard) {
384
637
  await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(messageId)}/permanentDelete`);
@@ -396,8 +649,9 @@ export class GraphEmailProvider {
396
649
  const graphMsg = {
397
650
  subject: msg.subject.slice(0, SUBJECT_MAX_LENGTH),
398
651
  body: buildGraphBody(msg.bodyHtml, msg.body),
399
- toRecipients: msg.to.map(r => ({ emailAddress: { address: r.email, name: r.name } })),
400
- ccRecipients: msg.cc?.map(r => ({ emailAddress: { address: r.email, name: r.name } })),
652
+ toRecipients: toGraphRecipients(msg.to),
653
+ ccRecipients: toGraphRecipients(msg.cc),
654
+ bccRecipients: toGraphRecipients(msg.bcc),
401
655
  singleValueExtendedProperties: [
402
656
  { id: TRACKING_PROPERTY, value: trackingId },
403
657
  ],
@@ -440,7 +694,12 @@ export class GraphEmailProvider {
440
694
  const graphMsg = {
441
695
  subject: msg.subject,
442
696
  body: buildGraphBody(msg.bodyHtml, msg.body),
443
- toRecipients: msg.to.map(r => ({ emailAddress: { address: r.email, name: r.name } })),
697
+ toRecipients: toGraphRecipients(msg.to),
698
+ ccRecipients: toGraphRecipients(msg.cc),
699
+ bccRecipients: toGraphRecipients(msg.bcc),
700
+ singleValueExtendedProperties: [
701
+ { id: DRAFT_ORIGIN_PROPERTY, value: 'non_reply' },
702
+ ],
444
703
  };
445
704
  if (msg.attachments && msg.attachments.length > 0) {
446
705
  graphMsg.attachments = msg.attachments.map(toGraphFileAttachment);
@@ -452,6 +711,124 @@ export class GraphEmailProvider {
452
711
  await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(draftId)}/send`, {});
453
712
  return { success: true, messageId: draftId };
454
713
  }
714
+ async scheduleMessage(msg, scheduledSendAt) {
715
+ const sizeError = checkGraphAttachmentLimits(msg.attachments, { checkTotal: true });
716
+ if (sizeError)
717
+ return { success: false, error: sizeError };
718
+ const trackingId = msg.trackingId ?? `ae-${Date.now()}`;
719
+ const graphMsg = {
720
+ subject: msg.subject.slice(0, SUBJECT_MAX_LENGTH),
721
+ body: buildGraphBody(msg.bodyHtml, msg.body),
722
+ toRecipients: toGraphRecipients(msg.to),
723
+ ccRecipients: toGraphRecipients(msg.cc),
724
+ bccRecipients: toGraphRecipients(msg.bcc),
725
+ singleValueExtendedProperties: [
726
+ { id: TRACKING_PROPERTY, value: trackingId },
727
+ { id: DEFERRED_SEND_PROPERTY, value: scheduledSendAt },
728
+ { id: DRAFT_ORIGIN_PROPERTY, value: 'non_reply' },
729
+ ],
730
+ };
731
+ if (msg.attachments && msg.attachments.length > 0) {
732
+ graphMsg.attachments = msg.attachments.map(toGraphFileAttachment);
733
+ }
734
+ const created = await this.client.post(`${this.basePath}/messages`, graphMsg);
735
+ if (!created.id) {
736
+ return {
737
+ success: false,
738
+ error: {
739
+ code: 'SCHEDULE_DRAFT_FAILED',
740
+ message: 'Microsoft Graph created no scheduled-send draft id',
741
+ provider: 'microsoft',
742
+ recoverable: false,
743
+ },
744
+ };
745
+ }
746
+ try {
747
+ await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(created.id)}/send`, {});
748
+ return { success: true, messageId: created.id, scheduledSendAt };
749
+ }
750
+ catch (err) {
751
+ return scheduledDraftSendFailure(created.id, scheduledSendAt, err);
752
+ }
753
+ }
754
+ async scheduleDraft(draftId, scheduledSendAt) {
755
+ const encodedId = encodeGraphPathId(draftId);
756
+ await this.client.patch(`${this.basePath}/messages/${encodedId}`, {
757
+ singleValueExtendedProperties: [
758
+ { id: DEFERRED_SEND_PROPERTY, value: scheduledSendAt },
759
+ ],
760
+ });
761
+ try {
762
+ await this.client.post(`${this.basePath}/messages/${encodedId}/send`, {});
763
+ return { success: true, messageId: draftId, scheduledSendAt };
764
+ }
765
+ catch (err) {
766
+ return scheduledDraftSendFailure(draftId, scheduledSendAt, err);
767
+ }
768
+ }
769
+ async listScheduledSends() {
770
+ const propertyFilter = `$filter=id eq '${DEFERRED_SEND_PROPERTY}'`;
771
+ let url = `${this.basePath}/mailFolders/drafts/messages`
772
+ + `?$select=id,subject,toRecipients,isDraft&$top=100`
773
+ + `&$expand=singleValueExtendedProperties(${propertyFilter})`;
774
+ const messages = [];
775
+ const visitedUrls = new Set();
776
+ while (url) {
777
+ if (visitedUrls.has(url) || visitedUrls.size >= 100) {
778
+ throw new ProviderError('PAGINATION_LIMIT', 'Scheduled-send pagination exceeded its safety limit', 'microsoft', false);
779
+ }
780
+ visitedUrls.add(url);
781
+ const response = await this.client.get(url);
782
+ messages.push(...(response.value ?? []));
783
+ url = response['@odata.nextLink'];
784
+ }
785
+ const scheduled = [];
786
+ for (const message of messages) {
787
+ const property = findDeferredSendProperty(message);
788
+ if (message.isDraft !== true || !property)
789
+ continue;
790
+ const timestamp = Date.parse(property.value);
791
+ if (!Number.isFinite(timestamp))
792
+ continue;
793
+ scheduled.push({
794
+ messageId: message.id,
795
+ subject: message.subject ?? '',
796
+ to: (message.toRecipients ?? []).map(recipient => ({
797
+ email: recipient.emailAddress.address,
798
+ name: recipient.emailAddress.name,
799
+ })),
800
+ scheduledSendAt: new Date(timestamp).toISOString(),
801
+ });
802
+ }
803
+ return scheduled;
804
+ }
805
+ async cancelScheduledSend(messageId) {
806
+ const encodedId = encodeGraphPathId(messageId);
807
+ const propertyFilter = `$filter=id eq '${DEFERRED_SEND_PROPERTY}'`;
808
+ let candidate;
809
+ try {
810
+ candidate = await this.client.get(`${this.basePath}/messages/${encodedId}`
811
+ + `?$select=id,isDraft&$expand=singleValueExtendedProperties(${propertyFilter})`);
812
+ }
813
+ catch (err) {
814
+ if (err instanceof GraphApiError && err.status === 404) {
815
+ throw scheduledSendNotFoundError();
816
+ }
817
+ throw err;
818
+ }
819
+ if (candidate.isDraft !== true || !findDeferredSendProperty(candidate)) {
820
+ throw scheduledSendNotFoundError();
821
+ }
822
+ try {
823
+ await this.client.delete(`${this.basePath}/messages/${encodedId}`);
824
+ }
825
+ catch (err) {
826
+ if (err instanceof GraphApiError && err.status === 404) {
827
+ throw scheduledSendNotFoundError();
828
+ }
829
+ throw err;
830
+ }
831
+ }
455
832
  async createReplyDraft(messageId, body, opts) {
456
833
  // Routes to createReply or createReplyAll based on opts.replyAll. Both Graph
457
834
  // endpoints preserve embedded images, CID references, and the auto-quoted thread.
@@ -498,6 +875,7 @@ export class GraphEmailProvider {
498
875
  if (!draft.id)
499
876
  throw new Error(`${endpoint} did not return a draft id`);
500
877
  let draftBody = draft.body;
878
+ let draftTo = draft.toRecipients ?? [];
501
879
  let draftCc = draft.ccRecipients ?? [];
502
880
  let draftBcc = draft.bccRecipients ?? [];
503
881
  // Fallback GET when the POST response lacks a usable HTML body. Graph defaults
@@ -505,6 +883,7 @@ export class GraphEmailProvider {
505
883
  if (typeof draftBody?.content !== 'string' || draftBody.contentType?.toLowerCase() !== 'html') {
506
884
  const fetched = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draft.id)}`);
507
885
  draftBody = fetched.body;
886
+ draftTo = fetched.toRecipients ?? [];
508
887
  draftCc = fetched.ccRecipients ?? [];
509
888
  draftBcc = fetched.bccRecipients ?? [];
510
889
  }
@@ -515,8 +894,38 @@ export class GraphEmailProvider {
515
894
  const merged = mergeQuotedReplyHtml(draftContent, callerFragment);
516
895
  const patch = {
517
896
  body: { contentType: 'HTML', content: truncateBody(merged) },
897
+ singleValueExtendedProperties: [
898
+ { id: DRAFT_ORIGIN_PROPERTY, value: 'reply' },
899
+ ],
518
900
  };
519
- const ccMerged = mergeRecipients(draftCc, opts?.cc ?? []);
901
+ // `to` REPLACES Graph's auto-populated recipients; `cc`/`bcc` below MERGE
902
+ // with the thread's. The asymmetry is deliberate (issue #164): merging a
903
+ // caller-supplied To would leave the parent's sender on the To line, which
904
+ // is exactly the failure being fixed — a reply to your own sent message
905
+ // stays addressed to yourself. Absent `to`, the patch omits toRecipients
906
+ // entirely and Graph's derived To stands, unchanged from before.
907
+ // mergeRecipients([], …) is reused only for its EmailAddress →
908
+ // GraphRecipient conversion and case-insensitive dedupe.
909
+ const hasExplicitTo = Boolean(opts?.to && opts.to.length > 0);
910
+ if (hasExplicitTo) {
911
+ patch.toRecipients = mergeRecipients([], opts.to);
912
+ }
913
+ // Replacing the To line must not silently drop anyone. On the reply-all
914
+ // endpoint Graph puts the parent's sender AND its other To participants on
915
+ // the draft's To; an explicit `to` displaces all of them, so demote the
916
+ // displaced ones to Cc — reply-all means the thread stays on the message,
917
+ // and `to` only decides who it is addressed to. This also brings Microsoft
918
+ // in line with Gmail, which already carries the thread's participants on Cc
919
+ // under reply-all. On the sender-only endpoint there is nothing to preserve:
920
+ // Graph's To is just the parent's sender, and replacing that is the point of
921
+ // a narrowed redirect.
922
+ const displacedTo = hasExplicitTo && opts?.replyAll !== false
923
+ ? draftTo.filter(r => {
924
+ const address = r.emailAddress?.address?.toLowerCase();
925
+ return address ? !opts.to.some(a => a.email.toLowerCase() === address) : false;
926
+ })
927
+ : [];
928
+ const ccMerged = mergeRecipients([...draftCc, ...displacedTo], opts?.cc ?? []);
520
929
  if (ccMerged.length > 0)
521
930
  patch.ccRecipients = ccMerged;
522
931
  const bccMerged = mergeRecipients(draftBcc, opts?.bcc ?? []);
@@ -540,39 +949,51 @@ export class GraphEmailProvider {
540
949
  }
541
950
  return draft.id;
542
951
  }
952
+ async getDraftReplyStatus(draftId) {
953
+ const propertyFilter = `$filter=id eq '${DRAFT_ORIGIN_PROPERTY}'`;
954
+ const metadata = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draftId)}`
955
+ + `?$select=isDraft,conversationIndex`
956
+ + `&$expand=singleValueExtendedProperties(${propertyFilter})`);
957
+ if (metadata.isDraft !== true)
958
+ return 'indeterminate';
959
+ // Duplicate stamps are ambiguous: taking the first match would make the
960
+ // answer depend on the order Graph returns the collection. Only a single,
961
+ // unanimous stamp is authoritative.
962
+ const originStamps = (metadata.singleValueExtendedProperties ?? []).filter(property => property.id.toLowerCase() === DRAFT_ORIGIN_PROPERTY.toLowerCase());
963
+ if (originStamps.length > 0) {
964
+ const values = originStamps.map(property => property.value);
965
+ const unanimous = values.every(value => value === values[0]);
966
+ if (!unanimous)
967
+ return 'indeterminate';
968
+ if (values[0] === 'reply')
969
+ return 'reply';
970
+ if (values[0] === 'non_reply')
971
+ return 'non_reply';
972
+ return 'indeterminate';
973
+ }
974
+ const conversationIndexBytes = decodeConversationIndex(metadata.conversationIndex);
975
+ if (conversationIndexBytes === undefined)
976
+ return 'indeterminate';
977
+ return conversationIndexBytes > 22 ? 'reply' : 'indeterminate';
978
+ }
543
979
  async updateDraft(draftId, msg) {
544
980
  const patch = {};
545
981
  if (msg.body !== undefined || msg.bodyHtml !== undefined) {
546
- // For reply drafts, GET the existing body so we can preserve Graph's auto-quoted
547
- // thread (divider + From/Sent/To/Subject + prior message). Replacing the body
548
- // wholesale via PATCH would drop the quoted history that prepareReplyDraft set up.
549
- // For non-reply drafts (no quoted-thread anatomy), this falls through to the
550
- // normal buildGraphBody path so behavior is unchanged.
551
- // $select=body narrows the response — we only need the body field here.
552
- const current = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draftId)}?$select=body`);
553
- const currentBody = current.body;
554
- const currentContent = typeof currentBody?.content === 'string' ? currentBody.content : '';
555
- const currentIsHtml = currentBody?.contentType?.toLowerCase() === 'html';
556
- const region = currentIsHtml ? findGraphQuotedReplyRegion(currentContent) : null;
557
- if (region) {
558
- const callerFragment = msg.bodyHtml !== undefined
559
- ? stripHtmlBodyWrappers(msg.bodyHtml)
560
- : wrapPlainTextAsHtml(msg.body ?? '');
561
- const merged = currentContent.slice(0, region.bodyOpenEnd)
562
- + callerFragment
563
- + currentContent.slice(region.dividerStart);
564
- patch.body = { contentType: 'HTML', content: truncateBody(merged) };
565
- }
566
- else {
567
- patch.body = buildGraphBody(msg.bodyHtml, msg.body ?? '');
568
- }
982
+ // update_draft admits body writes only for provider-confirmed non-reply
983
+ // drafts with explicit caller opt-in. Graph PATCH replaces that body
984
+ // wholesale; no quoted-history boundary inspection belongs here.
985
+ patch.body = buildGraphBody(msg.bodyHtml, msg.body ?? '');
569
986
  }
570
987
  if (msg.subject !== undefined)
571
988
  patch.subject = msg.subject.slice(0, SUBJECT_MAX_LENGTH);
989
+ // An omitted list leaves the draft's existing recipients untouched (Graph
990
+ // PATCH is a merge); a provided list replaces them.
572
991
  if (msg.to)
573
- patch.toRecipients = msg.to.map(r => ({ emailAddress: { address: r.email, name: r.name } }));
992
+ patch.toRecipients = toGraphRecipients(msg.to);
574
993
  if (msg.cc)
575
- patch.ccRecipients = msg.cc.map(r => ({ emailAddress: { address: r.email, name: r.name } }));
994
+ patch.ccRecipients = toGraphRecipients(msg.cc);
995
+ if (msg.bcc)
996
+ patch.bccRecipients = toGraphRecipients(msg.bcc);
576
997
  // Attachments: an omitted field preserves the draft's existing attachments
577
998
  // (Graph attachments are child resources untouched by this PATCH). A
578
999
  // provided array replaces them — delete the existing set, then add the new
@@ -669,6 +1090,260 @@ export class GraphEmailProvider {
669
1090
  ? response.categories.filter((value) => typeof value === 'string')
670
1091
  : [];
671
1092
  }
1093
+ async getFolderSnapshot() {
1094
+ const now = Date.now();
1095
+ if (this.folderCache && this.folderCache.expiresAt > now) {
1096
+ return { folders: this.folderCache.folders, truncated: false };
1097
+ }
1098
+ const budget = { remaining: MAX_FOLDER_REQUESTS_PER_SNAPSHOT, truncated: false };
1099
+ const folders = await this.fetchFolderCollection(`${this.basePath}/mailFolders?${FOLDER_SELECT}&$top=100&includeHiddenFolders=true`, '', new Set(), budget);
1100
+ // Never cache a partial tree — a truncated snapshot would otherwise make
1101
+ // "folder not found" sticky for 60s on a folder that does exist.
1102
+ if (!budget.truncated) {
1103
+ this.folderCache = { expiresAt: now + FOLDER_CACHE_TTL_MS, folders };
1104
+ }
1105
+ return { folders, truncated: budget.truncated };
1106
+ }
1107
+ async fetchFolderCollection(initialUrl, parentPath, visitedFolderIds,
1108
+ // Shared across the whole recursive traversal, not per collection, so a
1109
+ // wide/deep folder tree can't fan out into hundreds of Graph requests.
1110
+ budget) {
1111
+ const folders = [];
1112
+ const visitedUrls = new Set();
1113
+ let url = initialUrl;
1114
+ while (url) {
1115
+ if (visitedUrls.has(url) || visitedUrls.size >= 100) {
1116
+ throw new ProviderError('PAGINATION_LIMIT', 'Folder pagination exceeded its safety limit', 'microsoft', false);
1117
+ }
1118
+ if (budget.remaining <= 0) {
1119
+ // Truncate rather than throw — see MAX_FOLDER_REQUESTS_PER_SNAPSHOT.
1120
+ budget.truncated = true;
1121
+ return folders;
1122
+ }
1123
+ visitedUrls.add(url);
1124
+ budget.remaining -= 1;
1125
+ const response = await this.client.get(url);
1126
+ for (const graphFolder of response.value ?? []) {
1127
+ if (!graphFolder.id || visitedFolderIds.has(graphFolder.id))
1128
+ continue;
1129
+ visitedFolderIds.add(graphFolder.id);
1130
+ const path = parentPath ? `${parentPath}/${graphFolder.displayName}` : graphFolder.displayName;
1131
+ folders.push(mapGraphFolder(graphFolder, path));
1132
+ if ((graphFolder.childFolderCount ?? 0) > 0) {
1133
+ folders.push(...await this.fetchFolderCollection(`${this.basePath}/mailFolders/${encodeGraphPathId(graphFolder.id)}/childFolders?${FOLDER_SELECT}&$top=100&includeHiddenFolders=true`, path, visitedFolderIds, budget));
1134
+ }
1135
+ }
1136
+ url = response['@odata.nextLink'];
1137
+ }
1138
+ return folders;
1139
+ }
1140
+ /**
1141
+ * Resolve a folder name/path/id to a Graph folder id.
1142
+ *
1143
+ * `forWrite` is reserved for operations that MUTATE the folder tree
1144
+ * (createFolder's parent, deleteFolder's target): these are low-frequency and
1145
+ * high-harm — deleting or nesting under a stale-cached id is unrecoverable —
1146
+ * so they re-fetch to get a current path→id mapping. Message moves and rule
1147
+ * destinations deliberately do NOT pass forWrite: they don't change the tree,
1148
+ * they run in high-volume loops, and their worst-case staleness (the 60s
1149
+ * rename race) is the same recoverable risk we already accept for reads.
1150
+ */
1151
+ async resolveFolderId(folder, forWrite = false) {
1152
+ const trimmed = folder.trim();
1153
+ const normalized = normalizeFolderLookup(trimmed);
1154
+ const wellKnown = WELL_KNOWN_FOLDER_ALIASES[normalized]
1155
+ ?? (SYSTEM_FOLDER_NAME_SET.has(normalized) ? normalized : undefined);
1156
+ if (wellKnown)
1157
+ return wellKnown;
1158
+ if (forWrite)
1159
+ this.invalidateFolderCaches();
1160
+ const { folders, truncated } = await this.getFolderSnapshot();
1161
+ // Exact id match is safe even against a truncated tree — ids are globally
1162
+ // unique, so a visible match is THE match regardless of unseen folders.
1163
+ const idMatch = folders.find(candidate => candidate.id === trimmed);
1164
+ if (idMatch)
1165
+ return idMatch.id;
1166
+ // A truncated tree cannot prove a NAME or PATH is unique (a duplicate could
1167
+ // exist beyond the request budget), so refuse to guess — returning a
1168
+ // visible-but-maybe-not-unique match could misroute a write. Ids only.
1169
+ if (truncated) {
1170
+ // The exact id might simply lie beyond the truncated prefix. An id is
1171
+ // globally unique, so a direct GET is a safe, O(1) way to honor
1172
+ // "exact ids resolve without depending on a full traversal".
1173
+ const directId = await this.tryResolveFolderById(trimmed);
1174
+ if (directId)
1175
+ return directId;
1176
+ throw new ProviderError('FOLDER_TRAVERSAL_LIMIT', `Folder '${folder}' could not be uniquely resolved: this mailbox has more folders than a single traversal enumerates (${MAX_FOLDER_REQUESTS_PER_SNAPSHOT} requests). Specify the folder by id.`, 'microsoft', false);
1177
+ }
1178
+ const pathMatches = folders.filter(candidate => normalizeFolderLookup(candidate.path) === normalized);
1179
+ if (pathMatches.length === 1)
1180
+ return pathMatches[0].id;
1181
+ if (pathMatches.length > 1) {
1182
+ throw new ProviderError('AMBIGUOUS_FOLDER', `Folder path '${folder}' is ambiguous; use the folder id`, 'microsoft', false);
1183
+ }
1184
+ const nameMatches = folders.filter(candidate => normalizeFolderLookup(candidate.displayName) === normalized);
1185
+ if (nameMatches.length === 1)
1186
+ return nameMatches[0].id;
1187
+ if (nameMatches.length > 1) {
1188
+ throw new ProviderError('AMBIGUOUS_FOLDER', `Folder name '${folder}' is ambiguous; use a full folder path`, 'microsoft', false);
1189
+ }
1190
+ throw new ProviderError('FOLDER_NOT_FOUND', `Folder '${folder}' was not found`, 'microsoft', false);
1191
+ }
1192
+ /**
1193
+ * Verify a string is a real folder id via a direct GET. Returns the id on a
1194
+ * 200, undefined on 404 (not an id / no such folder). Used only as a fallback
1195
+ * when the tree was truncated, so a valid id past the budget still resolves.
1196
+ */
1197
+ async tryResolveFolderById(id) {
1198
+ try {
1199
+ const folder = await this.client.get(`${this.basePath}/mailFolders/${encodeGraphPathId(id)}?$select=id`);
1200
+ return folder.id ?? undefined;
1201
+ }
1202
+ catch (err) {
1203
+ if (err instanceof GraphApiError && (err.status === 404 || err.status === 400)) {
1204
+ return undefined;
1205
+ }
1206
+ throw err;
1207
+ }
1208
+ }
1209
+ /**
1210
+ * Resolve a rule-action destination to an OPAQUE Graph folder id.
1211
+ *
1212
+ * Unlike the /messages/{id}/move endpoint (which accepts well-known names),
1213
+ * Graph's messageRule action contract wants a folder id — so well-known names
1214
+ * are mapped through to their ids here. Resolution is `forWrite` (fresh): a
1215
+ * rule persists and acts 24/7, so a stale destination is worth one traversal
1216
+ * to avoid. The destructive check runs on the CANONICAL resolved value, so
1217
+ * alias/slash/case tricks (`/trash/`, `DeletedItems`) that reach the same
1218
+ * folder are all rejected.
1219
+ */
1220
+ async resolveRuleDestinationId(destination) {
1221
+ const normalized = normalizeFolderLookup(destination);
1222
+ const wellKnown = WELL_KNOWN_FOLDER_ALIASES[normalized]
1223
+ ?? (SYSTEM_FOLDER_NAME_SET.has(normalized) ? normalized : undefined);
1224
+ if (wellKnown) {
1225
+ if (DESTRUCTIVE_RULE_DESTINATIONS.has(wellKnown)) {
1226
+ throw new ProviderError('UNSAFE_RULE_DESTINATION', `Inbox rule destination '${destination}' discards mail and is blocked for security`, 'microsoft', false);
1227
+ }
1228
+ const id = (await this.getSystemFolderIdMap()).get(wellKnown);
1229
+ if (!id) {
1230
+ throw new ProviderError('FOLDER_NOT_FOUND', `Inbox rule destination '${destination}' is not provisioned on this mailbox`, 'microsoft', false);
1231
+ }
1232
+ return id;
1233
+ }
1234
+ const resolvedId = await this.resolveFolderId(destination, true);
1235
+ if ((await this.getDestructiveFolderIds()).has(resolvedId)) {
1236
+ throw new ProviderError('UNSAFE_RULE_DESTINATION', `Inbox rule destination '${destination}' resolves to a mail-discarding system folder and is blocked for security`, 'microsoft', false);
1237
+ }
1238
+ return resolvedId;
1239
+ }
1240
+ async folderPathFor(folder, folderId) {
1241
+ const normalized = normalizeFolderLookup(folder);
1242
+ const wellKnown = WELL_KNOWN_FOLDER_ALIASES[normalized]
1243
+ ?? (SYSTEM_FOLDER_NAME_SET.has(normalized) ? normalized : undefined);
1244
+ if (wellKnown)
1245
+ return displayNameForWellKnownFolder(wellKnown);
1246
+ const { folders } = await this.getFolderSnapshot();
1247
+ return folders.find(candidate => candidate.id === folderId)?.path ?? folder.trim();
1248
+ }
1249
+ /** Well-known-name -> resolved id for every provisioned system folder. */
1250
+ async getSystemFolderIdMap() {
1251
+ const now = Date.now();
1252
+ if (this.systemFolderIdsCache && this.systemFolderIdsCache.expiresAt > now) {
1253
+ return this.systemFolderIdsCache.idsByName;
1254
+ }
1255
+ const idsByName = new Map();
1256
+ for (const name of SYSTEM_FOLDER_NAMES) {
1257
+ try {
1258
+ const folder = await this.client.get(`${this.basePath}/mailFolders/${encodeGraphPathId(name)}?${FOLDER_SELECT}`);
1259
+ if (folder.id)
1260
+ idsByName.set(name, folder.id);
1261
+ }
1262
+ catch (err) {
1263
+ // Some tenants do not provision every optional system folder.
1264
+ if (err instanceof GraphApiError && err.status === 404)
1265
+ continue;
1266
+ throw err;
1267
+ }
1268
+ }
1269
+ this.systemFolderIdsCache = { expiresAt: now + FOLDER_CACHE_TTL_MS, idsByName };
1270
+ return idsByName;
1271
+ }
1272
+ /** Ids of ALL system folders — none may be deleted. */
1273
+ async getSystemFolderIds() {
1274
+ return new Set((await this.getSystemFolderIdMap()).values());
1275
+ }
1276
+ /**
1277
+ * Ids of only the mail-discarding system folders. Rule destinations are
1278
+ * checked against THIS set, not the full system set: filing into Archive or
1279
+ * Junk via a rule is legitimate, so blocking every system folder would reject
1280
+ * ordinary rules. Derived from the same cached sweep as getSystemFolderIds.
1281
+ */
1282
+ async getDestructiveFolderIds() {
1283
+ const idsByName = await this.getSystemFolderIdMap();
1284
+ const ids = new Set();
1285
+ for (const [name, id] of idsByName) {
1286
+ if (DESTRUCTIVE_RULE_DESTINATIONS.has(name))
1287
+ ids.add(id);
1288
+ }
1289
+ return ids;
1290
+ }
1291
+ invalidateFolderCaches() {
1292
+ this.folderCache = undefined;
1293
+ this.systemFolderIdsCache = undefined;
1294
+ }
1295
+ }
1296
+ function findDeferredSendProperty(message) {
1297
+ return message.singleValueExtendedProperties?.find(property => property.id.toLowerCase() === DEFERRED_SEND_PROPERTY.toLowerCase());
1298
+ }
1299
+ function decodeConversationIndex(value) {
1300
+ if (typeof value !== 'string' || value.length === 0 || value !== value.trim()) {
1301
+ return undefined;
1302
+ }
1303
+ if (!/^[A-Za-z0-9+/_-]+={0,2}$/.test(value))
1304
+ return undefined;
1305
+ const firstPadding = value.indexOf('=');
1306
+ if (firstPadding >= 0 && value.length % 4 !== 0)
1307
+ return undefined;
1308
+ const unpadded = value.replace(/=+$/, '');
1309
+ if (unpadded.length % 4 === 1)
1310
+ return undefined;
1311
+ const normalized = unpadded.replace(/-/g, '+').replace(/_/g, '/');
1312
+ const decoded = Buffer.from(normalized, 'base64');
1313
+ const canonical = decoded.toString('base64').replace(/=+$/, '');
1314
+ if (canonical !== normalized)
1315
+ return undefined;
1316
+ return decoded.length;
1317
+ }
1318
+ function scheduledDraftSendFailure(draftId, scheduledSendAt, err) {
1319
+ const detail = err instanceof Error ? err.message : String(err);
1320
+ if (err instanceof GraphApiError && err.status >= 400 && err.status < 500) {
1321
+ return {
1322
+ success: false,
1323
+ messageId: draftId,
1324
+ scheduledSendAt,
1325
+ error: {
1326
+ code: 'SCHEDULE_SEND_FAILED',
1327
+ message: `Microsoft Graph rejected scheduled-send submission; the tagged draft remains available at messageId ${draftId}. ${detail}`,
1328
+ provider: 'microsoft',
1329
+ recoverable: false,
1330
+ },
1331
+ };
1332
+ }
1333
+ return {
1334
+ success: false,
1335
+ messageId: draftId,
1336
+ scheduledSendAt,
1337
+ error: {
1338
+ code: 'SCHEDULE_SEND_STATUS_UNKNOWN',
1339
+ message: `Microsoft Graph may have accepted scheduled-send submission. Do not schedule a duplicate; inspect or cancel messageId ${draftId}. ${detail}`,
1340
+ provider: 'microsoft',
1341
+ recoverable: false,
1342
+ },
1343
+ };
1344
+ }
1345
+ function scheduledSendNotFoundError() {
1346
+ return new ProviderError('NOT_SCHEDULED', 'Message is not a pending scheduled send', 'microsoft', false);
672
1347
  }
673
1348
  function mapGraphMessage(msg) {
674
1349
  const attachments = (msg.attachments ?? []).map((attachment) => ({
@@ -679,6 +1354,19 @@ function mapGraphMessage(msg) {
679
1354
  isInline: attachment.isInline ?? false,
680
1355
  contentId: attachment.contentId,
681
1356
  }));
1357
+ const bodyHtml = msg.body?.contentType?.toLowerCase() === 'html'
1358
+ ? msg.body.content
1359
+ : undefined;
1360
+ let authoredBodyHtml;
1361
+ if (bodyHtml !== undefined) {
1362
+ const replyRegion = findGraphQuotedReplyRegion(bodyHtml);
1363
+ if (replyRegion) {
1364
+ authoredBodyHtml = msg.uniqueBody?.contentType?.toLowerCase() === 'html'
1365
+ && typeof msg.uniqueBody.content === 'string'
1366
+ ? msg.uniqueBody.content
1367
+ : bodyHtml.slice(replyRegion.bodyOpenEnd, replyRegion.dividerStart);
1368
+ }
1369
+ }
682
1370
  return {
683
1371
  id: msg.id,
684
1372
  subject: msg.subject ?? '',
@@ -694,12 +1382,21 @@ function mapGraphMessage(msg) {
694
1382
  email: r.emailAddress.address,
695
1383
  name: r.emailAddress.name,
696
1384
  })),
1385
+ // bccRecipients is only populated by Graph on the sender's own copy of a
1386
+ // message; recipients' copies omit it. Surface it when present so read_email
1387
+ // can report full recipient topology (issue #102).
1388
+ bcc: (msg.bccRecipients ?? []).map(r => ({
1389
+ email: r.emailAddress.address,
1390
+ name: r.emailAddress.name,
1391
+ })),
697
1392
  receivedAt: msg.receivedDateTime ?? new Date().toISOString(),
698
1393
  isRead: msg.isRead ?? false,
699
1394
  isFlagged: msg.flag?.flagStatus === 'flagged',
1395
+ isDraft: msg.isDraft === true,
700
1396
  hasAttachments: msg.hasAttachments ?? false,
701
1397
  body: msg.body?.contentType?.toLowerCase() === 'text' ? msg.body.content : undefined,
702
- bodyHtml: msg.body?.contentType?.toLowerCase() === 'html' ? msg.body.content : undefined,
1398
+ bodyHtml,
1399
+ authoredBodyHtml,
703
1400
  attachments,
704
1401
  labels: msg.categories,
705
1402
  conversationId: msg.conversationId,
@@ -709,6 +1406,47 @@ function mapGraphMessage(msg) {
709
1406
  function normalizeFolderId(folder) {
710
1407
  return WELL_KNOWN_FOLDER_ALIASES[folder.trim().toLowerCase()] ?? folder;
711
1408
  }
1409
+ // Graph's messageRuleActions value contract. Wrong-typed values (e.g. a boolean
1410
+ // moveToFolder, or a string markAsRead) are rejected locally rather than sent to
1411
+ // Graph — and a non-string folder value would otherwise dodge the destructive
1412
+ // destination check, which only inspects strings.
1413
+ function isValidRuleActionValue(canonicalKey, value) {
1414
+ switch (canonicalKey) {
1415
+ case 'moveToFolder':
1416
+ case 'copyToFolder':
1417
+ return typeof value === 'string' && value.trim().length > 0;
1418
+ case 'markAsRead':
1419
+ case 'stopProcessingRules':
1420
+ return typeof value === 'boolean';
1421
+ case 'markImportance':
1422
+ return value === 'low' || value === 'normal' || value === 'high';
1423
+ case 'assignCategories':
1424
+ return Array.isArray(value) && value.every(item => typeof item === 'string');
1425
+ default:
1426
+ return false;
1427
+ }
1428
+ }
1429
+ function normalizeFolderLookup(folder) {
1430
+ return folder.trim().replace(/^\/+|\/+$/g, '').toLowerCase();
1431
+ }
1432
+ function displayNameForWellKnownFolder(folder) {
1433
+ const names = {
1434
+ archive: 'Archive',
1435
+ deleteditems: 'Deleted Items',
1436
+ drafts: 'Drafts',
1437
+ inbox: 'Inbox',
1438
+ junkemail: 'Junk Email',
1439
+ outbox: 'Outbox',
1440
+ sentitems: 'Sent Items',
1441
+ };
1442
+ return names[folder] ?? folder;
1443
+ }
1444
+ function mapGraphFolder(folder, path) {
1445
+ return { ...folder, path };
1446
+ }
1447
+ function systemFolderProtectedError(folder) {
1448
+ return new ProviderError('SYSTEM_FOLDER_PROTECTED', `System folder '${folder}' cannot be deleted`, 'microsoft', false);
1449
+ }
712
1450
  /**
713
1451
  * Simplify a search query by stripping field prefixes, boolean operators, and quotes.
714
1452
  * Returns space-separated keywords suitable for a Graph API $search retry.
@@ -817,10 +1555,11 @@ function wrapPlainTextAsHtml(text) {
817
1555
  /**
818
1556
  * Locate the splice region in a Graph reply draft body.
819
1557
  *
820
- * Returns null when the content is not a recognizable Graph reply (no `<body>` tag,
821
- * or `<body>` without a following `<hr>` divider). Returns the anchors otherwise:
1558
+ * Returns null unless the content has Graph's unambiguous reply anatomy: a
1559
+ * `<body>`, the `divRplyFwdMsg` boundary, and the `<hr>` divider immediately
1560
+ * before that boundary. Returns the anchors otherwise:
822
1561
  * - `bodyOpenEnd`: index of the first character after the `<body ...>` opening tag
823
- * - `dividerStart`: index of the first `<hr ...>` that follows
1562
+ * - `dividerStart`: index of Graph's `<hr ...>` divider
824
1563
  *
825
1564
  * Both create-path (`mergeQuotedReplyHtml`, inserts at `bodyOpenEnd`) and update-path
826
1565
  * (`updateDraft`, replaces `bodyOpenEnd..dividerStart`) share this anatomy parser so
@@ -831,7 +1570,14 @@ function findGraphQuotedReplyRegion(content) {
831
1570
  if (!bodyMatch || bodyMatch.index === undefined)
832
1571
  return null;
833
1572
  const bodyOpenEnd = bodyMatch.index + bodyMatch[0].length;
834
- const dividerMatch = content.slice(bodyOpenEnd).match(/<hr\b[^>]*>/i);
1573
+ const boundaryMatch = content.slice(bodyOpenEnd).match(/<div\b[^>]*\bid\s*=\s*(["'])divRplyFwdMsg\1[^>]*>/i);
1574
+ if (!boundaryMatch || boundaryMatch.index === undefined)
1575
+ return null;
1576
+ const boundaryStart = bodyOpenEnd + boundaryMatch.index;
1577
+ // Match the divider adjacent to Graph's boundary, not the first <hr> in the
1578
+ // authored region. Markdown `---` legitimately renders to an authored <hr>.
1579
+ const beforeBoundary = content.slice(bodyOpenEnd, boundaryStart);
1580
+ const dividerMatch = beforeBoundary.match(/<hr\b[^>]*>\s*$/i);
835
1581
  if (!dividerMatch || dividerMatch.index === undefined)
836
1582
  return null;
837
1583
  return { bodyOpenEnd, dividerStart: bodyOpenEnd + dividerMatch.index };