@usejunior/provider-microsoft 0.5.0 → 0.6.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.
@@ -1,4 +1,4 @@
1
- import { AttachmentNotSupportedError, AttachmentNotFoundError, MessageNotFoundError, ProviderError, classifyHttpStatus, classifyTransportError, parseRetryAfter, SEND_STATUS_UNKNOWN, } from '@usejunior/email-core';
1
+ import { AttachmentNotSupportedError, AttachmentNotFoundError, MessageNotFoundError, ProviderError, classifyHttpStatus, classifyTransportError, parseRetryAfter, SEND_STATUS_UNKNOWN, withAuthenticatedRetry, validateScheduledSendAt, runScheduledWorkflow, } 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 inline cap is on the *encoded write request* size, not the
@@ -205,6 +205,13 @@ const MESSAGE_SELECT = [
205
205
  function encodeGraphPathId(id) {
206
206
  return encodeURIComponent(id);
207
207
  }
208
+ class GraphAuthRejection extends Error {
209
+ response;
210
+ constructor(response) {
211
+ super('Graph rejected authentication');
212
+ this.response = response;
213
+ }
214
+ }
208
215
  /**
209
216
  * Real Graph API client using fetch + Bearer token.
210
217
  * Used when connected to a real mailbox via DelegatedAuthManager.
@@ -212,6 +219,7 @@ function encodeGraphPathId(id) {
212
219
  export class RealGraphApiClient {
213
220
  getToken;
214
221
  onAuthError;
222
+ recovery;
215
223
  constructor(getToken, onAuthError) {
216
224
  this.getToken = getToken;
217
225
  this.onAuthError = onAuthError;
@@ -230,54 +238,79 @@ export class RealGraphApiClient {
230
238
  const retryAfter = parseRetryAfter(resp.headers?.get('retry-after'));
231
239
  return new GraphApiError(resp.status, await resp.text(), retryAfter);
232
240
  }
233
- /** Fetch with automatic retry on 401 if onAuthError callback is provided. */
234
- async fetchWithAuthRetry(url, init) {
235
- const resp = await fetch(url, init);
236
- if (resp.status === 401 && this.onAuthError) {
237
- const ok = await this.onAuthError();
238
- if (ok) {
239
- const newToken = await this.getToken();
240
- const retryHeaders = { ...init.headers, Authorization: `Bearer ${newToken}` };
241
- return fetch(url, { ...init, headers: retryHeaders });
242
- }
241
+ recoverAuth() {
242
+ // Shared recovery belongs to the client; cancellation stops an individual
243
+ // waiter without cancelling another request's credential recovery.
244
+ if (!this.recovery) {
245
+ this.recovery = Promise.resolve().then(() => this.onAuthError()).finally(() => { this.recovery = undefined; });
243
246
  }
244
- return resp;
247
+ return this.recovery;
245
248
  }
246
- async get(url) {
247
- const token = await this.getToken();
249
+ /** Only a received 401 authorizes the single auth replay, including delivery. */
250
+ async fetchWithAuthRetry(url, init, operation) {
251
+ const signal = init.signal ?? undefined;
252
+ try {
253
+ return await withAuthenticatedRetry(async () => {
254
+ const token = await this.getToken(signal);
255
+ signal?.throwIfAborted();
256
+ const headers = { ...init.headers, Authorization: `Bearer ${token}` };
257
+ const response = await fetch(url, { ...init, headers });
258
+ if (response.status === 401)
259
+ throw new GraphAuthRejection(response);
260
+ return response;
261
+ }, {
262
+ operation,
263
+ signal,
264
+ classifyAuthError: error => error instanceof GraphAuthRejection && !!this.onAuthError ? 'rejected' : false,
265
+ refresh: () => this.recoverAuth(),
266
+ });
267
+ }
268
+ catch (error) {
269
+ if (error instanceof GraphAuthRejection)
270
+ return error.response;
271
+ throw error;
272
+ }
273
+ }
274
+ async get(url, signal) {
275
+ signal?.throwIfAborted();
248
276
  const fullUrl = url.startsWith('http') ? url : `https://graph.microsoft.com/v1.0${url}`;
249
277
  const resp = await this.fetchWithAuthRetry(fullUrl, {
250
- headers: { Authorization: `Bearer ${token}`, Prefer: IMMUTABLE_ID_PREFER },
251
- });
278
+ ...(signal ? { signal } : {}),
279
+ headers: { Prefer: IMMUTABLE_ID_PREFER },
280
+ }, 'idempotent-read');
252
281
  if (!resp.ok) {
253
282
  throw await this.errorFrom(resp);
254
283
  }
255
284
  return resp.json();
256
285
  }
257
- async getBytes(url) {
258
- const token = await this.getToken();
286
+ async getBytes(url, signal) {
259
287
  const fullUrl = url.startsWith('http') ? url : `https://graph.microsoft.com/v1.0${url}`;
260
288
  const resp = await this.fetchWithAuthRetry(fullUrl, {
261
- headers: { Authorization: `Bearer ${token}`, Prefer: IMMUTABLE_ID_PREFER },
262
- });
289
+ signal,
290
+ headers: { Prefer: IMMUTABLE_ID_PREFER },
291
+ }, 'idempotent-read');
263
292
  if (!resp.ok) {
264
293
  throw await this.errorFrom(resp);
265
294
  }
266
295
  return Buffer.from(await resp.arrayBuffer());
267
296
  }
268
- async post(url, body) {
269
- const token = await this.getToken();
297
+ async post(url, body, signal) {
270
298
  const fullUrl = url.startsWith('http') ? url : `https://graph.microsoft.com/v1.0${url}`;
271
299
  const headers = {
272
- Authorization: `Bearer ${token}`,
273
300
  Prefer: IMMUTABLE_ID_PREFER,
274
301
  };
275
- const init = { method: 'POST', headers };
302
+ const init = { method: 'POST', headers, signal };
276
303
  if (body !== undefined) {
277
304
  headers['Content-Type'] = 'application/json';
278
305
  init.body = JSON.stringify(body);
279
306
  }
280
- const resp = await this.fetchWithAuthRetry(fullUrl, init);
307
+ // These action endpoints dispatch mail. Other POSTs create/move resources.
308
+ // Unknown POSTs are conservatively delivery; only known resource actions
309
+ // are labelled writes. Neither classification enables a non-401 retry.
310
+ const path = new URL(fullUrl).pathname;
311
+ const operation = /\/(messages|attachments|mailFolders|messageRules|createReply|createReplyAll|createForward|move|copy|createUploadSession)\/?$/i.test(path)
312
+ ? 'idempotent-write' : 'delivery';
313
+ const resp = await this.fetchWithAuthRetry(fullUrl, init, operation);
281
314
  // sendMail returns 202 with no body
282
315
  if (resp.status === 202)
283
316
  return {};
@@ -287,29 +320,28 @@ export class RealGraphApiClient {
287
320
  const text = await resp.text();
288
321
  return text ? JSON.parse(text) : {};
289
322
  }
290
- async patch(url, body) {
291
- const token = await this.getToken();
323
+ async patch(url, body, signal) {
292
324
  const fullUrl = url.startsWith('http') ? url : `https://graph.microsoft.com/v1.0${url}`;
293
325
  const resp = await this.fetchWithAuthRetry(fullUrl, {
294
326
  method: 'PATCH',
327
+ signal,
295
328
  headers: {
296
- Authorization: `Bearer ${token}`,
297
329
  Prefer: IMMUTABLE_ID_PREFER,
298
330
  'Content-Type': 'application/json',
299
331
  },
300
332
  body: JSON.stringify(body),
301
- });
333
+ }, 'idempotent-write');
302
334
  if (!resp.ok) {
303
335
  throw await this.errorFrom(resp);
304
336
  }
305
337
  }
306
- async delete(url) {
307
- const token = await this.getToken();
338
+ async delete(url, signal) {
308
339
  const fullUrl = url.startsWith('http') ? url : `https://graph.microsoft.com/v1.0${url}`;
309
340
  const resp = await this.fetchWithAuthRetry(fullUrl, {
310
341
  method: 'DELETE',
311
- headers: { Authorization: `Bearer ${token}`, Prefer: IMMUTABLE_ID_PREFER },
312
- });
342
+ signal,
343
+ headers: { Prefer: IMMUTABLE_ID_PREFER },
344
+ }, 'idempotent-write');
313
345
  if (!resp.ok) {
314
346
  throw await this.errorFrom(resp);
315
347
  }
@@ -390,11 +422,61 @@ function graphDeliveryError(err, guidance) {
390
422
  ...(failure.retryAfter !== undefined ? { retryAfter: failure.retryAfter } : {}),
391
423
  };
392
424
  }
425
+ /** Process-local single-flight cache; invalidated completions must retry. */
426
+ class FolderCache {
427
+ generation = 0;
428
+ state = { kind: 'empty' };
429
+ invalidate() {
430
+ this.generation += 1;
431
+ this.state = { kind: 'empty' };
432
+ }
433
+ async get(load, complete, fresh = false) {
434
+ // Fresh validation bypasses a completed snapshot, but joins an active load.
435
+ // Only a completed structural mutation advances the generation.
436
+ if (fresh && this.state.kind === 'ready')
437
+ this.state = { kind: 'empty' };
438
+ for (;;) {
439
+ if (this.state.kind === 'ready' && this.state.expiresAt > Date.now()) {
440
+ return this.state.data;
441
+ }
442
+ if (this.state.kind !== 'loading') {
443
+ // Defer the loader until the shared state is installed, including when
444
+ // a loader throws synchronously before making its first request.
445
+ this.state = {
446
+ kind: 'loading', generation: this.generation,
447
+ promise: Promise.resolve().then(load),
448
+ };
449
+ }
450
+ const loading = this.state;
451
+ let data;
452
+ try {
453
+ data = await loading.promise;
454
+ }
455
+ catch (err) {
456
+ if (this.state === loading)
457
+ this.state = { kind: 'empty' };
458
+ if (loading.generation !== this.generation)
459
+ continue;
460
+ throw err;
461
+ }
462
+ // A structural mutation can finish while Graph is still traversing.
463
+ // Neither publish nor return that generation as the current snapshot.
464
+ if (loading.generation !== this.generation)
465
+ continue;
466
+ if (this.state === loading) {
467
+ this.state = complete(data)
468
+ ? { kind: 'ready', expiresAt: Date.now() + FOLDER_CACHE_TTL_MS, data }
469
+ : { kind: 'empty' };
470
+ }
471
+ return data;
472
+ }
473
+ }
474
+ }
393
475
  export class GraphEmailProvider {
394
476
  client;
395
477
  basePath;
396
- folderCache;
397
- systemFolderIdsCache;
478
+ folderCache = new FolderCache();
479
+ systemFolderIdsCache = new FolderCache();
398
480
  constructor(client, userId = 'me') {
399
481
  this.client = client;
400
482
  // For delegated auth, use /me/. For app-only, use /users/{id}/.
@@ -533,7 +615,7 @@ export class GraphEmailProvider {
533
615
  mimeType: a.contentType ?? 'application/octet-stream',
534
616
  size: a.size ?? 0,
535
617
  isInline: a.isInline ?? false,
536
- contentId: a.contentId,
618
+ contentId: a.contentId ?? undefined,
537
619
  }));
538
620
  }
539
621
  // Returns bytes + fresh metadata for fileAttachment only. itemAttachment and
@@ -714,12 +796,13 @@ export class GraphEmailProvider {
714
796
  // Resolve folder destinations to opaque ids and reject mail-discarding ones.
715
797
  // resolveRuleDestinationId does the destructive check on the canonical
716
798
  // resolved folder, closing alias/slash/case bypasses like `/trash/`.
717
- for (const folderAction of ['moveToFolder', 'copyToFolder']) {
799
+ // Start both validations together so move/copy share a fresh traversal.
800
+ await Promise.all(['moveToFolder', 'copyToFolder'].map(async (folderAction) => {
718
801
  const destination = actions[folderAction];
719
802
  if (typeof destination === 'string') {
720
803
  actions[folderAction] = await this.resolveRuleDestinationId(destination);
721
804
  }
722
- }
805
+ }));
723
806
  // Graph rejects sequence 0 (`MessageRuleValidationError` on Field 'Sequence'),
724
807
  // which is exactly the value it assigns when a POST omits sequence. The tool
725
808
  // exists so an agent can propose a rule without knowing Exchange internals,
@@ -847,7 +930,10 @@ export class GraphEmailProvider {
847
930
  : '';
848
931
  return {
849
932
  success: false,
850
- error: { ...err.emailError, message: err.emailError.message + detail },
933
+ messageId: err.draftId,
934
+ error: { ...err.emailError,
935
+ code: err.emailError.code === 'DRAFT_PREPARATION_FAILED' ? 'REPLY_FAILED' : err.emailError.code,
936
+ message: err.emailError.message + detail },
851
937
  };
852
938
  }
853
939
  const message = err instanceof Error ? err.message : 'Failed to prepare reply';
@@ -867,12 +953,33 @@ export class GraphEmailProvider {
867
953
  }
868
954
  return { success: true, messageId: draftId };
869
955
  }
956
+ async validateDraftFrom(from) {
957
+ if (!from)
958
+ return;
959
+ // Only this mailbox's primary SMTP address and proxy aliases are admitted.
960
+ // Delegated send-as of unrelated mailboxes needs a separate permission model.
961
+ let profile;
962
+ try {
963
+ profile = await this.client.get(`${this.basePath}?$select=mail,proxyAddresses`);
964
+ }
965
+ catch {
966
+ throw new ProviderError('FROM_NOT_ALLOWED', 'Cannot verify this mailbox\'s send-as addresses', 'microsoft', false);
967
+ }
968
+ const aliases = [profile.mail, ...(Array.isArray(profile.proxyAddresses) ? profile.proxyAddresses : [])
969
+ .filter((a) => typeof a === 'string' && /^smtp:/i.test(a))
970
+ .map(a => a.slice(5))];
971
+ if (!aliases.some(a => typeof a === 'string' && a.toLowerCase() === from.email.toLowerCase())) {
972
+ throw new ProviderError('FROM_NOT_ALLOWED', 'From must be this mailbox\'s primary SMTP address or proxy alias', 'microsoft', false);
973
+ }
974
+ }
870
975
  async createDraft(msg) {
976
+ await this.validateDraftFrom(msg.from);
871
977
  const sizeError = checkGraphAttachmentLimits(msg.attachments);
872
978
  if (sizeError) {
873
979
  return { success: false, error: sizeError };
874
980
  }
875
981
  const graphMsg = {
982
+ ...(msg.from ? { from: { emailAddress: { address: msg.from.email, name: msg.from.name } } } : {}),
876
983
  subject: msg.subject,
877
984
  body: buildGraphBody(msg.bodyHtml, msg.body),
878
985
  toRecipients: toGraphRecipients(msg.to),
@@ -926,7 +1033,10 @@ export class GraphEmailProvider {
926
1033
  async scheduleMessage(msg, scheduledSendAt) {
927
1034
  const sizeError = checkGraphAttachmentLimits(msg.attachments);
928
1035
  if (sizeError)
929
- return { success: false, error: sizeError };
1036
+ return {
1037
+ success: false, error: sizeError,
1038
+ workflow: { phase: 'terminal', outcome: 'rejected', lastPhase: 'preparing' },
1039
+ };
930
1040
  const trackingId = msg.trackingId ?? `ae-${Date.now()}`;
931
1041
  const graphMsg = {
932
1042
  subject: msg.subject.slice(0, SUBJECT_MAX_LENGTH),
@@ -936,7 +1046,6 @@ export class GraphEmailProvider {
936
1046
  bccRecipients: toGraphRecipients(msg.bcc),
937
1047
  singleValueExtendedProperties: [
938
1048
  { id: TRACKING_PROPERTY, value: trackingId },
939
- { id: DEFERRED_SEND_PROPERTY, value: scheduledSendAt },
940
1049
  { id: DRAFT_ORIGIN_PROPERTY, value: 'non_reply' },
941
1050
  ],
942
1051
  };
@@ -944,56 +1053,41 @@ export class GraphEmailProvider {
944
1053
  if (!draftUpload && msg.attachments && msg.attachments.length > 0) {
945
1054
  graphMsg.attachments = msg.attachments.map(toGraphFileAttachment);
946
1055
  }
947
- const created = await this.client.post(`${this.basePath}/messages`, graphMsg);
948
- if (!created.id) {
949
- return {
950
- success: false,
951
- error: {
952
- code: 'SCHEDULE_DRAFT_FAILED',
953
- message: 'Microsoft Graph created no scheduled-send draft id',
954
- provider: 'microsoft',
955
- recoverable: false,
956
- },
957
- };
958
- }
959
- if (draftUpload) {
960
- try {
961
- await this.postDraftAttachments(created.id, msg.attachments);
962
- }
963
- catch (err) {
964
- return {
965
- success: false,
966
- messageId: created.id,
967
- error: {
968
- code: 'ATTACHMENT_UPLOAD_FAILED',
969
- message: `Scheduled draft ${created.id} was created but attaching files failed: ${err instanceof Error ? err.message : String(err)}`,
970
- recoverable: false,
971
- },
972
- };
973
- }
974
- }
975
- try {
976
- await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(created.id)}/send`, {});
977
- return { success: true, messageId: created.id, scheduledSendAt };
978
- }
979
- catch (err) {
980
- return scheduledDraftSendFailure(created.id, scheduledSendAt, err);
981
- }
1056
+ return this.runSchedule(scheduledSendAt, undefined, async () => {
1057
+ const created = await this.client.post(`${this.basePath}/messages`, graphMsg);
1058
+ if (!created.id)
1059
+ throw new Error('Microsoft Graph created no scheduled-send draft id');
1060
+ return created.id;
1061
+ }, async (id) => {
1062
+ if (draftUpload)
1063
+ await this.postDraftAttachments(id, msg.attachments);
1064
+ });
982
1065
  }
983
1066
  async scheduleDraft(draftId, scheduledSendAt) {
984
- const encodedId = encodeGraphPathId(draftId);
985
- await this.client.patch(`${this.basePath}/messages/${encodedId}`, {
986
- singleValueExtendedProperties: [
987
- { id: DEFERRED_SEND_PROPERTY, value: scheduledSendAt },
988
- ],
1067
+ return this.runSchedule(scheduledSendAt, draftId);
1068
+ }
1069
+ async runSchedule(scheduledSendAt, draftId, createDraft = async () => { throw new Error('Missing draft'); }, prepareAttachments = async () => { }) {
1070
+ // Attachments are complete before applying the marker. A failed PATCH may
1071
+ // still have applied remotely; retain the handle without cleanup or replay.
1072
+ return runScheduledWorkflow({
1073
+ scheduledSendAt, draftId, createDraft, prepareAttachments,
1074
+ setDeferredProperty: async (id) => {
1075
+ await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(id)}`, {
1076
+ singleValueExtendedProperties: [
1077
+ { id: DEFERRED_SEND_PROPERTY, value: scheduledSendAt },
1078
+ ],
1079
+ });
1080
+ },
1081
+ dispatch: async (id) => {
1082
+ await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(id)}/send`, {});
1083
+ },
1084
+ preparationError: (err, phase) => ({
1085
+ code: phase === 'draft_created' ? 'ATTACHMENT_UPLOAD_FAILED' : 'SCHEDULE_DRAFT_FAILED',
1086
+ message: `Scheduled-send preparation failed at ${phase}; no dispatch attempted. Any retained draft may include partial changes. Inspect it before further action. ${err instanceof Error ? err.message : String(err)}`,
1087
+ provider: 'microsoft', recoverable: false,
1088
+ }),
1089
+ dispatchError: (err, id) => scheduledDispatchFailure(id, err),
989
1090
  });
990
- try {
991
- await this.client.post(`${this.basePath}/messages/${encodedId}/send`, {});
992
- return { success: true, messageId: draftId, scheduledSendAt };
993
- }
994
- catch (err) {
995
- return scheduledDraftSendFailure(draftId, scheduledSendAt, err);
996
- }
997
1091
  }
998
1092
  /**
999
1093
  * Discovery is mailbox-wide, not Drafts-scoped: Outlook's own "Schedule send"
@@ -1029,9 +1123,10 @@ export class GraphEmailProvider {
1029
1123
  const property = findDeferredSendProperty(message);
1030
1124
  if (message.isDraft !== true || !property)
1031
1125
  continue;
1032
- const timestamp = Date.parse(property.value);
1033
- if (!Number.isFinite(timestamp))
1126
+ const validated = validateScheduledSendAt(property.value, now);
1127
+ if ('error' in validated)
1034
1128
  continue;
1129
+ const timestamp = Date.parse(validated.value);
1035
1130
  // Outlook leaves the tagged copy behind after delivery, so a past
1036
1131
  // deferred time marks residue rather than a pending send. Drafts-scoped
1037
1132
  // discovery rarely saw those; a mailbox-wide scan sees all of them.
@@ -1063,10 +1158,13 @@ export class GraphEmailProvider {
1063
1158
  }
1064
1159
  throw err;
1065
1160
  }
1066
- if (candidate.isDraft !== true || !findDeferredSendProperty(candidate)) {
1161
+ const marker = findDeferredSendProperty(candidate)?.value;
1162
+ if (candidate.isDraft !== true || marker === undefined || 'error' in validateScheduledSendAt(marker)) {
1067
1163
  throw scheduledSendNotFoundError();
1068
1164
  }
1069
1165
  try {
1166
+ // Graph offers no verified conditional DELETE for this flow. Delivery
1167
+ // can win after the observation; deletion cannot recall delivered mail.
1070
1168
  await this.client.delete(`${this.basePath}/messages/${encodedId}`);
1071
1169
  }
1072
1170
  catch (err) {
@@ -1076,6 +1174,17 @@ export class GraphEmailProvider {
1076
1174
  throw err;
1077
1175
  }
1078
1176
  }
1177
+ async createForwardDraft(messageId, body, opts) {
1178
+ try {
1179
+ const draftId = await this.prepareReplyDraft(messageId, body, opts, true);
1180
+ return { success: true, draftId };
1181
+ }
1182
+ catch (err) {
1183
+ if (err instanceof GraphAttachmentError)
1184
+ return { success: false, draftId: err.draftId, error: err.emailError };
1185
+ return { success: false, error: { code: err instanceof ProviderError ? err.code : 'DRAFT_FAILED', message: err instanceof Error ? err.message : 'Forward draft failed', recoverable: false } };
1186
+ }
1187
+ }
1079
1188
  async createReplyDraft(messageId, body, opts) {
1080
1189
  // Routes to createReply or createReplyAll based on opts.replyAll. Both Graph
1081
1190
  // endpoints preserve embedded images, CID references, and the auto-quoted thread.
@@ -1088,7 +1197,7 @@ export class GraphEmailProvider {
1088
1197
  return { success: false, draftId: err.draftId, error: err.emailError };
1089
1198
  }
1090
1199
  const message = err instanceof Error ? err.message : 'Failed to create reply draft';
1091
- return { success: false, error: { code: 'DRAFT_FAILED', message, recoverable: false } };
1200
+ return { success: false, error: { code: err instanceof ProviderError ? err.code : 'DRAFT_FAILED', message, recoverable: false } };
1092
1201
  }
1093
1202
  }
1094
1203
  /**
@@ -1132,101 +1241,153 @@ export class GraphEmailProvider {
1132
1241
  }
1133
1242
  }
1134
1243
  }
1135
- async prepareReplyDraft(messageId, body, opts) {
1244
+ async prepareReplyDraft(messageId, body, opts, forward = false) {
1136
1245
  // Size preflight before creating the draft, so an oversize attachment
1137
1246
  // never leaves an orphan draft behind.
1138
1247
  const sizeError = checkGraphAttachmentLimits(opts?.attachments);
1139
1248
  if (sizeError) {
1140
1249
  throw new GraphAttachmentError(sizeError);
1141
1250
  }
1142
- const endpoint = opts?.replyAll === false ? 'createReply' : 'createReplyAll';
1251
+ await this.validateDraftFrom(opts?.from);
1252
+ const endpoint = forward ? 'createForward' : opts?.replyAll === false ? 'createReply' : 'createReplyAll';
1143
1253
  const draft = await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(messageId)}/${endpoint}`, {});
1144
1254
  if (!draft.id)
1145
1255
  throw new Error(`${endpoint} did not return a draft id`);
1146
- let draftBody = draft.body;
1147
- let draftTo = draft.toRecipients ?? [];
1148
- let draftCc = draft.ccRecipients ?? [];
1149
- let draftBcc = draft.bccRecipients ?? [];
1150
- // Fallback GET when the POST response lacks a usable HTML body. Graph defaults
1151
- // to HTML on `Get message` so no Prefer header is needed.
1152
- if (typeof draftBody?.content !== 'string' || draftBody.contentType?.toLowerCase() !== 'html') {
1153
- const fetched = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draft.id)}`);
1154
- draftBody = fetched.body;
1155
- draftTo = fetched.toRecipients ?? [];
1156
- draftCc = fetched.ccRecipients ?? [];
1157
- draftBcc = fetched.bccRecipients ?? [];
1158
- }
1159
- const draftContent = typeof draftBody?.content === 'string' ? draftBody.content : '';
1160
- const callerFragment = opts?.bodyHtml !== undefined
1161
- ? stripHtmlBodyWrappers(opts.bodyHtml)
1162
- : wrapPlainTextAsHtml(body);
1163
- const merged = mergeQuotedReplyHtml(draftContent, callerFragment);
1164
- const patch = {
1165
- body: { contentType: 'HTML', content: truncateBody(merged) },
1166
- singleValueExtendedProperties: [
1167
- { id: DRAFT_ORIGIN_PROPERTY, value: 'reply' },
1168
- ],
1169
- };
1170
- // `to` REPLACES Graph's auto-populated recipients; `cc`/`bcc` below MERGE
1171
- // with the thread's. The asymmetry is deliberate (issue #164): merging a
1172
- // caller-supplied To would leave the parent's sender on the To line, which
1173
- // is exactly the failure being fixed — a reply to your own sent message
1174
- // stays addressed to yourself. Absent `to`, the patch omits toRecipients
1175
- // entirely and Graph's derived To stands, unchanged from before.
1176
- // mergeRecipients([], …) is reused only for its EmailAddress →
1177
- // GraphRecipient conversion and case-insensitive dedupe.
1178
- const hasExplicitTo = Boolean(opts?.to && opts.to.length > 0);
1179
- // Anyone on `bcc` comes off the visible lines Graph derived, so a thread
1180
- // participant can be moved to Bcc without restating the audience (issue
1181
- // #214). Bcc wins over a derived To/Cc.
1182
- const hidden = new Set((opts?.bcc ?? []).map(a => a.email.toLowerCase()));
1183
- const isVisible = (r) => !hidden.has(r.emailAddress?.address?.toLowerCase() ?? '');
1184
- if (hasExplicitTo) {
1185
- patch.toRecipients = mergeRecipients([], opts.to).filter(isVisible);
1186
- }
1187
- else if (draftTo.some(r => !isVisible(r))) {
1188
- // Only touch toRecipients when something must come off it; otherwise
1189
- // Graph's derived To stands untouched, as before.
1190
- patch.toRecipients = draftTo.filter(isVisible);
1191
- }
1192
- // Replacing the To line must not silently drop anyone. On the reply-all
1193
- // endpoint Graph puts the parent's sender AND its other To participants on
1194
- // the draft's To; an explicit `to` displaces all of them, so demote the
1195
- // displaced ones to Cc — reply-all means the thread stays on the message,
1196
- // and `to` only decides who it is addressed to. This also brings Microsoft
1197
- // in line with Gmail, which already carries the thread's participants on Cc
1198
- // under reply-all. On the sender-only endpoint there is nothing to preserve:
1199
- // Graph's To is just the parent's sender, and replacing that is the point of
1200
- // a narrowed redirect.
1201
- const displacedTo = hasExplicitTo && opts?.replyAll !== false
1202
- ? draftTo.filter(r => {
1203
- const address = r.emailAddress?.address?.toLowerCase();
1204
- return address ? !opts.to.some(a => a.email.toLowerCase() === address) : false;
1205
- })
1206
- : [];
1207
- const ccMerged = mergeRecipients([...draftCc, ...displacedTo], opts?.cc ?? []).filter(isVisible);
1208
- if (ccMerged.length > 0 || draftCc.some(r => !isVisible(r)))
1209
- patch.ccRecipients = ccMerged;
1210
- const bccMerged = mergeRecipients(draftBcc, opts?.bcc ?? []);
1211
- if (bccMerged.length > 0)
1212
- patch.bccRecipients = bccMerged;
1213
- await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(draft.id)}`, patch);
1214
- // Two-step attachment upload: the draft now exists, so POST each file to
1215
- // its /attachments collection. A failure here leaves a created-but-
1216
- // incomplete draft — surface its id so the caller can inspect or retry.
1217
- if (opts?.attachments && opts.attachments.length > 0) {
1218
- try {
1219
- await this.postDraftAttachments(draft.id, opts.attachments);
1256
+ try {
1257
+ let draftBody = draft.body;
1258
+ let draftTo = draft.toRecipients ?? [];
1259
+ let draftCc = draft.ccRecipients ?? [];
1260
+ let draftBcc = draft.bccRecipients ?? [];
1261
+ // Fallback GET when the POST response lacks a usable HTML body. Graph defaults
1262
+ // to HTML on `Get message` so no Prefer header is needed.
1263
+ if (typeof draftBody?.content !== 'string' || draftBody.contentType?.toLowerCase() !== 'html') {
1264
+ const fetched = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draft.id)}`);
1265
+ draftBody = fetched.body;
1266
+ draftTo = fetched.toRecipients ?? [];
1267
+ draftCc = fetched.ccRecipients ?? [];
1268
+ draftBcc = fetched.bccRecipients ?? [];
1220
1269
  }
1221
- catch (err) {
1222
- throw new GraphAttachmentError({
1223
- code: 'ATTACHMENT_UPLOAD_FAILED',
1224
- message: `Reply draft was created but attaching files failed: ${err instanceof Error ? err.message : String(err)}`,
1225
- recoverable: false,
1226
- }, draft.id);
1270
+ const draftContent = typeof draftBody?.content === 'string' ? draftBody.content : '';
1271
+ const callerFragment = opts?.bodyHtml !== undefined
1272
+ ? stripHtmlBodyWrappers(opts.bodyHtml)
1273
+ : wrapPlainTextAsHtml(body);
1274
+ const merged = mergeQuotedReplyHtml(draftContent, callerFragment);
1275
+ const patch = {
1276
+ body: { contentType: 'HTML', content: truncateBody(merged) },
1277
+ singleValueExtendedProperties: [
1278
+ { id: DRAFT_ORIGIN_PROPERTY, value: 'reply' },
1279
+ ],
1280
+ };
1281
+ if (opts?.subject !== undefined)
1282
+ patch.subject = opts.subject.slice(0, SUBJECT_MAX_LENGTH);
1283
+ if (opts?.from)
1284
+ patch.from = { emailAddress: { address: opts.from.email, name: opts.from.name } };
1285
+ // `to` REPLACES Graph's auto-populated recipients; `cc`/`bcc` below MERGE
1286
+ // with the thread's. The asymmetry is deliberate (issue #164): merging a
1287
+ // caller-supplied To would leave the parent's sender on the To line, which
1288
+ // is exactly the failure being fixed — a reply to your own sent message
1289
+ // stays addressed to yourself. Absent `to`, the patch omits toRecipients
1290
+ // entirely and Graph's derived To stands, unchanged from before.
1291
+ // mergeRecipients([], …) is reused only for its EmailAddress →
1292
+ // GraphRecipient conversion and case-insensitive dedupe.
1293
+ const hasExplicitTo = Boolean(opts?.to && opts.to.length > 0);
1294
+ // Anyone on `bcc` comes off the visible lines Graph derived, so a thread
1295
+ // participant can be moved to Bcc without restating the audience (issue
1296
+ // #214). Bcc wins over a derived To/Cc.
1297
+ const hidden = new Set((opts?.bcc ?? []).map(a => a.email.toLowerCase()));
1298
+ const isVisible = (r) => !hidden.has(r.emailAddress?.address?.toLowerCase() ?? '');
1299
+ if (hasExplicitTo) {
1300
+ patch.toRecipients = mergeRecipients([], opts.to).filter(isVisible);
1301
+ }
1302
+ else if (draftTo.some(r => !isVisible(r))) {
1303
+ // Only touch toRecipients when something must come off it; otherwise
1304
+ // Graph's derived To stands untouched, as before.
1305
+ patch.toRecipients = draftTo.filter(isVisible);
1306
+ }
1307
+ // Replacing the To line must not silently drop anyone. On the reply-all
1308
+ // endpoint Graph puts the parent's sender AND its other To participants on
1309
+ // the draft's To; an explicit `to` displaces all of them, so demote the
1310
+ // displaced ones to Cc — reply-all means the thread stays on the message,
1311
+ // and `to` only decides who it is addressed to. This also brings Microsoft
1312
+ // in line with Gmail, which already carries the thread's participants on Cc
1313
+ // under reply-all. On the sender-only endpoint there is nothing to preserve:
1314
+ // Graph's To is just the parent's sender, and replacing that is the point of
1315
+ // a narrowed redirect.
1316
+ const displacedTo = hasExplicitTo && opts?.replyAll !== false
1317
+ ? draftTo.filter(r => {
1318
+ const address = r.emailAddress?.address?.toLowerCase();
1319
+ return address ? !opts.to.some(a => a.email.toLowerCase() === address) : false;
1320
+ })
1321
+ : [];
1322
+ const ccMerged = mergeRecipients([...draftCc, ...displacedTo], opts?.cc ?? []).filter(isVisible);
1323
+ if (ccMerged.length > 0 || draftCc.some(r => !isVisible(r)))
1324
+ patch.ccRecipients = ccMerged;
1325
+ const bccMerged = mergeRecipients(draftBcc, opts?.bcc ?? []);
1326
+ if (bccMerged.length > 0)
1327
+ patch.bccRecipients = bccMerged;
1328
+ if (forward) {
1329
+ patch.toRecipients = toGraphRecipients(opts?.to ?? []);
1330
+ patch.ccRecipients = toGraphRecipients(opts?.cc ?? []);
1331
+ patch.bccRecipients = toGraphRecipients(opts?.bcc ?? []);
1332
+ }
1333
+ await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(draft.id)}`, patch);
1334
+ // Two-step attachment upload: the draft now exists, so POST each file to
1335
+ // its /attachments collection. A failure here leaves a created-but-
1336
+ // incomplete draft — surface its id so the caller can inspect or retry.
1337
+ if (opts?.attachments && opts.attachments.length > 0) {
1338
+ try {
1339
+ await this.postDraftAttachments(draft.id, opts.attachments);
1340
+ }
1341
+ catch (err) {
1342
+ throw new GraphAttachmentError({
1343
+ code: 'ATTACHMENT_UPLOAD_FAILED',
1344
+ message: `Reply draft was created but attaching files failed: ${err instanceof Error ? err.message : String(err)}`,
1345
+ recoverable: false,
1346
+ }, draft.id);
1347
+ }
1227
1348
  }
1349
+ return draft.id;
1350
+ }
1351
+ catch (err) {
1352
+ if (err instanceof GraphAttachmentError)
1353
+ throw err;
1354
+ throw new GraphAttachmentError({
1355
+ code: 'DRAFT_PREPARATION_FAILED',
1356
+ message: `Reply draft was created but preparation failed: ${err instanceof Error ? err.message : String(err)}`,
1357
+ recoverable: false,
1358
+ }, draft.id);
1359
+ }
1360
+ }
1361
+ async getDraft(draftId) {
1362
+ // Preserve the existing expanded attachment/unique-body preview reader.
1363
+ const message = await this.getMessage(draftId);
1364
+ if (message.isDraft !== true)
1365
+ throw new MessageNotFoundError(`Editable draft ${draftId} not found`);
1366
+ return message;
1367
+ }
1368
+ async getDraftSnapshot(draftId) {
1369
+ let metadata;
1370
+ try {
1371
+ metadata = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draftId)}`
1372
+ + `?$select=${MESSAGE_SELECT},conversationIndex,changeKey`
1373
+ + `&$expand=singleValueExtendedProperties($filter=id eq '${DRAFT_ORIGIN_PROPERTY}' or id eq '${DEFERRED_SEND_PROPERTY}')`);
1228
1374
  }
1229
- return draft.id;
1375
+ catch (err) {
1376
+ if (err instanceof GraphApiError && err.status === 404)
1377
+ throw new MessageNotFoundError(`Draft ${draftId} not found`);
1378
+ throw err;
1379
+ }
1380
+ const scheduledSendAt = findDeferredSendProperty(metadata)?.value;
1381
+ const pending = scheduledSendAt !== undefined && !('error' in validateScheduledSendAt(scheduledSendAt));
1382
+ return {
1383
+ draftId: metadata.id,
1384
+ messageId: metadata.id,
1385
+ message: mapGraphMessage(metadata),
1386
+ revision: metadata.changeKey,
1387
+ lifecycle: metadata.isDraft === true ? (pending ? 'deferred' : 'editable') : 'indeterminate',
1388
+ origin: this.draftOrigin(metadata),
1389
+ scheduledSendAt,
1390
+ };
1230
1391
  }
1231
1392
  async getDraftReplyStatus(draftId) {
1232
1393
  const propertyFilter = `$filter=id eq '${DRAFT_ORIGIN_PROPERTY}'`;
@@ -1242,8 +1403,9 @@ export class GraphEmailProvider {
1242
1403
  }
1243
1404
  throw err;
1244
1405
  }
1245
- if (metadata.isDraft !== true)
1246
- return 'indeterminate';
1406
+ return metadata.isDraft === true ? this.draftOrigin(metadata) : 'indeterminate';
1407
+ }
1408
+ draftOrigin(metadata) {
1247
1409
  // Duplicate stamps are ambiguous: taking the first match would make the
1248
1410
  // answer depend on the order Graph returns the collection. Only a single,
1249
1411
  // unanimous stamp is authoritative.
@@ -1265,6 +1427,7 @@ export class GraphEmailProvider {
1265
1427
  return conversationIndexBytes > 22 ? 'reply' : 'indeterminate';
1266
1428
  }
1267
1429
  async updateDraft(draftId, msg) {
1430
+ await this.validateDraftFrom(msg.from);
1268
1431
  const patch = {};
1269
1432
  if (msg.body !== undefined || msg.bodyHtml !== undefined) {
1270
1433
  // update_draft admits body writes only for provider-confirmed non-reply
@@ -1272,6 +1435,8 @@ export class GraphEmailProvider {
1272
1435
  // wholesale; no quoted-history boundary inspection belongs here.
1273
1436
  patch.body = buildGraphBody(msg.bodyHtml, msg.body ?? '');
1274
1437
  }
1438
+ if (msg.from)
1439
+ patch.from = { emailAddress: { address: msg.from.email, name: msg.from.name } };
1275
1440
  if (msg.subject !== undefined)
1276
1441
  patch.subject = msg.subject.slice(0, SUBJECT_MAX_LENGTH);
1277
1442
  // An omitted list leaves the draft's existing recipients untouched (Graph
@@ -1292,7 +1457,16 @@ export class GraphEmailProvider {
1292
1457
  return { success: false, draftId, error: sizeError };
1293
1458
  }
1294
1459
  }
1295
- await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(draftId)}`, patch);
1460
+ try {
1461
+ await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(draftId)}`, patch);
1462
+ }
1463
+ catch (err) {
1464
+ return { success: false, draftId, error: {
1465
+ code: 'UPDATE_DRAFT_FAILED',
1466
+ message: err instanceof Error ? err.message : String(err),
1467
+ recoverable: false,
1468
+ } };
1469
+ }
1296
1470
  if (msg.attachments !== undefined) {
1297
1471
  try {
1298
1472
  const existing = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draftId)}/attachments?$select=id`);
@@ -1318,16 +1492,54 @@ export class GraphEmailProvider {
1318
1492
  return { success: true, draftId };
1319
1493
  }
1320
1494
  /**
1321
- * Get new inbox messages received after a given timestamp.
1322
- * Uses simple $filter=receivedDateTime gt {since} — instant, no full-inbox sync.
1495
+ * Retrieve a complete inclusive timestamp window; partial results never escape.
1496
+ * The optional end preserves existing callers while bounding every invocation.
1323
1497
  * This is the primary method for the watcher polling loop.
1324
1498
  */
1325
- async getNewMessages(since) {
1326
- const filter = `receivedDateTime ge ${since}`;
1499
+ async getNewMessages(since, end = new Date().toISOString(), signal) {
1500
+ if (!Number.isFinite(Date.parse(since)) || !Number.isFinite(Date.parse(end)) || Date.parse(since) > Date.parse(end)) {
1501
+ throw new Error('Invalid watcher timestamp window');
1502
+ }
1503
+ const filter = `receivedDateTime ge ${since} and receivedDateTime le ${end}`;
1327
1504
  const params = `$filter=${encodeURIComponent(filter)}&$orderby=receivedDateTime desc&$top=50&${DELTA_SELECT}`;
1328
- const url = `${this.basePath}/mailFolders/Inbox/messages?${params}`;
1329
- const response = await this.client.get(url);
1330
- return (response.value ?? []).map(mapGraphMessage);
1505
+ let url = `${this.basePath}/mailFolders/Inbox/messages?${params}`;
1506
+ const seen = new Set();
1507
+ const messages = [];
1508
+ while (url) {
1509
+ signal?.throwIfAborted();
1510
+ if (seen.has(url) || seen.size >= 1000)
1511
+ throw new Error('Watcher pagination repeated a link or exceeded 1000 pages');
1512
+ seen.add(url);
1513
+ const response = await this.client.get(url, signal);
1514
+ signal?.throwIfAborted();
1515
+ if (!Array.isArray(response.value))
1516
+ throw new Error('Invalid watcher message page');
1517
+ for (const raw of response.value) {
1518
+ // The general mapper supplies defaults for other actions. Watcher
1519
+ // windows must validate source identity/time before those defaults.
1520
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
1521
+ throw new Error('Invalid watcher message identity or timestamp');
1522
+ }
1523
+ const message = raw;
1524
+ if (typeof message.id !== 'string' || !message.id.trim()
1525
+ || !Object.hasOwn(message, 'receivedDateTime')
1526
+ || typeof message.receivedDateTime !== 'string' || !message.receivedDateTime.trim()
1527
+ || !Number.isFinite(Date.parse(message.receivedDateTime))) {
1528
+ throw new Error('Invalid watcher message identity or timestamp');
1529
+ }
1530
+ messages.push(mapGraphMessage(raw));
1531
+ }
1532
+ const next = response['@odata.nextLink'];
1533
+ if (next !== undefined && (typeof next !== 'string' || !next))
1534
+ throw new Error('Invalid watcher nextLink');
1535
+ url = next;
1536
+ }
1537
+ return messages.filter(message => {
1538
+ const received = Date.parse(message.receivedAt);
1539
+ if (!Number.isFinite(received))
1540
+ throw new Error('Invalid watcher message timestamp');
1541
+ return received >= Date.parse(since) && received <= Date.parse(end);
1542
+ });
1331
1543
  }
1332
1544
  /**
1333
1545
  * Delta Query polling — follows all pages.
@@ -1339,8 +1551,13 @@ export class GraphEmailProvider {
1339
1551
  let url = deltaLink;
1340
1552
  const allMessages = [];
1341
1553
  let finalDeltaLink = '';
1554
+ const visited = new Set();
1342
1555
  // Page through all results (follow @odata.nextLink until @odata.deltaLink)
1343
1556
  while (url) {
1557
+ if (visited.has(url) || visited.size >= 100) {
1558
+ throw new ProviderError('PAGINATION_LIMIT', 'Delta pagination exceeded its safety limit', 'microsoft', false);
1559
+ }
1560
+ visited.add(url);
1344
1561
  const response = await this.client.get(url);
1345
1562
  const items = response.value ?? [];
1346
1563
  // Filter out @removed tombstones and map the rest
@@ -1359,13 +1576,12 @@ export class GraphEmailProvider {
1359
1576
  url = response['@odata.nextLink'];
1360
1577
  }
1361
1578
  else {
1362
- // No nextLink and no deltaLink — shouldn't happen, but break to avoid infinite loop
1363
- break;
1579
+ throw new ProviderError('INVALID_DELTA_RESPONSE', 'Delta response omitted the terminal cursor', 'microsoft', false);
1364
1580
  }
1365
1581
  }
1366
1582
  return {
1367
1583
  messages: allMessages,
1368
- nextDeltaLink: finalDeltaLink || url,
1584
+ nextDeltaLink: finalDeltaLink,
1369
1585
  };
1370
1586
  }
1371
1587
  // NemoClaw egress domains
@@ -1378,19 +1594,13 @@ export class GraphEmailProvider {
1378
1594
  ? response.categories.filter((value) => typeof value === 'string')
1379
1595
  : [];
1380
1596
  }
1381
- async getFolderSnapshot() {
1382
- const now = Date.now();
1383
- if (this.folderCache && this.folderCache.expiresAt > now) {
1384
- return { folders: this.folderCache.folders, truncated: false };
1385
- }
1386
- const budget = { remaining: MAX_FOLDER_REQUESTS_PER_SNAPSHOT, truncated: false };
1387
- const folders = await this.fetchFolderCollection(`${this.basePath}/mailFolders?${FOLDER_SELECT}&$top=100&includeHiddenFolders=true`, '', new Set(), budget);
1388
- // Never cache a partial tree — a truncated snapshot would otherwise make
1389
- // "folder not found" sticky for 60s on a folder that does exist.
1390
- if (!budget.truncated) {
1391
- this.folderCache = { expiresAt: now + FOLDER_CACHE_TTL_MS, folders };
1392
- }
1393
- return { folders, truncated: budget.truncated };
1597
+ async getFolderSnapshot(fresh = false) {
1598
+ return this.folderCache.get(async () => {
1599
+ const budget = { remaining: MAX_FOLDER_REQUESTS_PER_SNAPSHOT, truncated: false };
1600
+ const folders = await this.fetchFolderCollection(`${this.basePath}/mailFolders?${FOLDER_SELECT}&$top=100&includeHiddenFolders=true`, '', new Set(), budget);
1601
+ // A partial tree cannot establish absence or uniqueness.
1602
+ return { folders, truncated: budget.truncated };
1603
+ }, snapshot => !snapshot.truncated, fresh);
1394
1604
  }
1395
1605
  async fetchFolderCollection(initialUrl, parentPath, visitedFolderIds,
1396
1606
  // Shared across the whole recursive traversal, not per collection, so a
@@ -1428,13 +1638,10 @@ export class GraphEmailProvider {
1428
1638
  /**
1429
1639
  * Resolve a folder name/path/id to a Graph folder id.
1430
1640
  *
1431
- * `forWrite` is reserved for operations that MUTATE the folder tree
1432
- * (createFolder's parent, deleteFolder's target): these are low-frequency and
1433
- * high-harm — deleting or nesting under a stale-cached id is unrecoverable —
1434
- * so they re-fetch to get a current path→id mapping. Message moves and rule
1435
- * destinations deliberately do NOT pass forWrite: they don't change the tree,
1436
- * they run in high-volume loops, and their worst-case staleness (the 60s
1437
- * rename race) is the same recoverable risk we already accept for reads.
1641
+ * Structural writes and persistent rule destinations bypass ready snapshots
1642
+ * for fresh path→id validation, sharing any active traversal. Message moves
1643
+ * retain the ordinary 60s cache. Validation does not invalidate system IDs or
1644
+ * advance generations; successful structural mutations invalidate both caches.
1438
1645
  */
1439
1646
  async resolveFolderId(folder, forWrite = false) {
1440
1647
  const trimmed = folder.trim();
@@ -1443,9 +1650,7 @@ export class GraphEmailProvider {
1443
1650
  ?? (SYSTEM_FOLDER_NAME_SET.has(normalized) ? normalized : undefined);
1444
1651
  if (wellKnown)
1445
1652
  return wellKnown;
1446
- if (forWrite)
1447
- this.invalidateFolderCaches();
1448
- const { folders, truncated } = await this.getFolderSnapshot();
1653
+ const { folders, truncated } = await this.getFolderSnapshot(forWrite);
1449
1654
  // Exact id match is safe even against a truncated tree — ids are globally
1450
1655
  // unique, so a visible match is THE match regardless of unseen folders.
1451
1656
  const idMatch = folders.find(candidate => candidate.id === trimmed);
@@ -1536,10 +1741,9 @@ export class GraphEmailProvider {
1536
1741
  }
1537
1742
  /** Well-known-name -> resolved id for every provisioned system folder. */
1538
1743
  async getSystemFolderIdMap() {
1539
- const now = Date.now();
1540
- if (this.systemFolderIdsCache && this.systemFolderIdsCache.expiresAt > now) {
1541
- return this.systemFolderIdsCache.idsByName;
1542
- }
1744
+ return this.systemFolderIdsCache.get(() => this.fetchSystemFolderIdMap(), () => true);
1745
+ }
1746
+ async fetchSystemFolderIdMap() {
1543
1747
  const idsByName = new Map();
1544
1748
  for (const name of SYSTEM_FOLDER_NAMES) {
1545
1749
  try {
@@ -1554,7 +1758,6 @@ export class GraphEmailProvider {
1554
1758
  throw err;
1555
1759
  }
1556
1760
  }
1557
- this.systemFolderIdsCache = { expiresAt: now + FOLDER_CACHE_TTL_MS, idsByName };
1558
1761
  return idsByName;
1559
1762
  }
1560
1763
  /** Ids of ALL system folders — none may be deleted. */
@@ -1577,8 +1780,8 @@ export class GraphEmailProvider {
1577
1780
  return ids;
1578
1781
  }
1579
1782
  invalidateFolderCaches() {
1580
- this.folderCache = undefined;
1581
- this.systemFolderIdsCache = undefined;
1783
+ this.folderCache.invalidate();
1784
+ this.systemFolderIdsCache.invalidate();
1582
1785
  }
1583
1786
  }
1584
1787
  function findDeferredSendProperty(message) {
@@ -1603,16 +1806,14 @@ function decodeConversationIndex(value) {
1603
1806
  return undefined;
1604
1807
  return decoded.length;
1605
1808
  }
1606
- function scheduledDraftSendFailure(draftId, scheduledSendAt, err) {
1809
+ function scheduledDispatchFailure(draftId, err) {
1607
1810
  // Shares classifyGraphDelivery with the immediate-send paths so the two
1608
1811
  // families cannot drift on what counts as ambiguous. The codes stay
1609
1812
  // scheduled-specific because they are spec'd and because the remedy differs:
1610
1813
  // here there is a tagged draft to inspect or cancel.
1611
1814
  const failure = classifyGraphDelivery(err);
1612
1815
  return {
1613
- success: false,
1614
- messageId: draftId,
1615
- scheduledSendAt,
1816
+ outcome: failure.ambiguous ? 'unknown' : 'rejected',
1616
1817
  error: {
1617
1818
  code: failure.ambiguous ? 'SCHEDULE_SEND_STATUS_UNKNOWN' : 'SCHEDULE_SEND_FAILED',
1618
1819
  message: failure.ambiguous
@@ -1634,7 +1835,7 @@ function mapGraphMessage(msg) {
1634
1835
  mimeType: attachment.contentType ?? 'application/octet-stream',
1635
1836
  size: attachment.size ?? 0,
1636
1837
  isInline: attachment.isInline ?? false,
1637
- contentId: attachment.contentId,
1838
+ contentId: attachment.contentId ?? undefined,
1638
1839
  }));
1639
1840
  const bodyHtml = msg.body?.contentType?.toLowerCase() === 'html'
1640
1841
  ? msg.body.content