@usejunior/provider-microsoft 0.4.0 → 0.5.1

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; });
246
+ }
247
+ return this.recovery;
248
+ }
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;
243
272
  }
244
- return resp;
245
273
  }
246
- async get(url) {
247
- const token = await this.getToken();
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}/.
@@ -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';
@@ -926,7 +1012,10 @@ export class GraphEmailProvider {
926
1012
  async scheduleMessage(msg, scheduledSendAt) {
927
1013
  const sizeError = checkGraphAttachmentLimits(msg.attachments);
928
1014
  if (sizeError)
929
- return { success: false, error: sizeError };
1015
+ return {
1016
+ success: false, error: sizeError,
1017
+ workflow: { phase: 'terminal', outcome: 'rejected', lastPhase: 'preparing' },
1018
+ };
930
1019
  const trackingId = msg.trackingId ?? `ae-${Date.now()}`;
931
1020
  const graphMsg = {
932
1021
  subject: msg.subject.slice(0, SUBJECT_MAX_LENGTH),
@@ -936,7 +1025,6 @@ export class GraphEmailProvider {
936
1025
  bccRecipients: toGraphRecipients(msg.bcc),
937
1026
  singleValueExtendedProperties: [
938
1027
  { id: TRACKING_PROPERTY, value: trackingId },
939
- { id: DEFERRED_SEND_PROPERTY, value: scheduledSendAt },
940
1028
  { id: DRAFT_ORIGIN_PROPERTY, value: 'non_reply' },
941
1029
  ],
942
1030
  };
@@ -944,56 +1032,41 @@ export class GraphEmailProvider {
944
1032
  if (!draftUpload && msg.attachments && msg.attachments.length > 0) {
945
1033
  graphMsg.attachments = msg.attachments.map(toGraphFileAttachment);
946
1034
  }
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
- }
1035
+ return this.runSchedule(scheduledSendAt, undefined, async () => {
1036
+ const created = await this.client.post(`${this.basePath}/messages`, graphMsg);
1037
+ if (!created.id)
1038
+ throw new Error('Microsoft Graph created no scheduled-send draft id');
1039
+ return created.id;
1040
+ }, async (id) => {
1041
+ if (draftUpload)
1042
+ await this.postDraftAttachments(id, msg.attachments);
1043
+ });
982
1044
  }
983
1045
  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
- ],
1046
+ return this.runSchedule(scheduledSendAt, draftId);
1047
+ }
1048
+ async runSchedule(scheduledSendAt, draftId, createDraft = async () => { throw new Error('Missing draft'); }, prepareAttachments = async () => { }) {
1049
+ // Attachments are complete before applying the marker. A failed PATCH may
1050
+ // still have applied remotely; retain the handle without cleanup or replay.
1051
+ return runScheduledWorkflow({
1052
+ scheduledSendAt, draftId, createDraft, prepareAttachments,
1053
+ setDeferredProperty: async (id) => {
1054
+ await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(id)}`, {
1055
+ singleValueExtendedProperties: [
1056
+ { id: DEFERRED_SEND_PROPERTY, value: scheduledSendAt },
1057
+ ],
1058
+ });
1059
+ },
1060
+ dispatch: async (id) => {
1061
+ await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(id)}/send`, {});
1062
+ },
1063
+ preparationError: (err, phase) => ({
1064
+ code: phase === 'draft_created' ? 'ATTACHMENT_UPLOAD_FAILED' : 'SCHEDULE_DRAFT_FAILED',
1065
+ 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)}`,
1066
+ provider: 'microsoft', recoverable: false,
1067
+ }),
1068
+ dispatchError: (err, id) => scheduledDispatchFailure(id, err),
989
1069
  });
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
1070
  }
998
1071
  /**
999
1072
  * Discovery is mailbox-wide, not Drafts-scoped: Outlook's own "Schedule send"
@@ -1029,9 +1102,10 @@ export class GraphEmailProvider {
1029
1102
  const property = findDeferredSendProperty(message);
1030
1103
  if (message.isDraft !== true || !property)
1031
1104
  continue;
1032
- const timestamp = Date.parse(property.value);
1033
- if (!Number.isFinite(timestamp))
1105
+ const validated = validateScheduledSendAt(property.value, now);
1106
+ if ('error' in validated)
1034
1107
  continue;
1108
+ const timestamp = Date.parse(validated.value);
1035
1109
  // Outlook leaves the tagged copy behind after delivery, so a past
1036
1110
  // deferred time marks residue rather than a pending send. Drafts-scoped
1037
1111
  // discovery rarely saw those; a mailbox-wide scan sees all of them.
@@ -1063,10 +1137,13 @@ export class GraphEmailProvider {
1063
1137
  }
1064
1138
  throw err;
1065
1139
  }
1066
- if (candidate.isDraft !== true || !findDeferredSendProperty(candidate)) {
1140
+ const marker = findDeferredSendProperty(candidate)?.value;
1141
+ if (candidate.isDraft !== true || marker === undefined || 'error' in validateScheduledSendAt(marker)) {
1067
1142
  throw scheduledSendNotFoundError();
1068
1143
  }
1069
1144
  try {
1145
+ // Graph offers no verified conditional DELETE for this flow. Delivery
1146
+ // can win after the observation; deletion cannot recall delivered mail.
1070
1147
  await this.client.delete(`${this.basePath}/messages/${encodedId}`);
1071
1148
  }
1072
1149
  catch (err) {
@@ -1143,98 +1220,150 @@ export class GraphEmailProvider {
1143
1220
  const draft = await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(messageId)}/${endpoint}`, {});
1144
1221
  if (!draft.id)
1145
1222
  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);
1223
+ try {
1224
+ let draftBody = draft.body;
1225
+ let draftTo = draft.toRecipients ?? [];
1226
+ let draftCc = draft.ccRecipients ?? [];
1227
+ let draftBcc = draft.bccRecipients ?? [];
1228
+ // Fallback GET when the POST response lacks a usable HTML body. Graph defaults
1229
+ // to HTML on `Get message` so no Prefer header is needed.
1230
+ if (typeof draftBody?.content !== 'string' || draftBody.contentType?.toLowerCase() !== 'html') {
1231
+ const fetched = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draft.id)}`);
1232
+ draftBody = fetched.body;
1233
+ draftTo = fetched.toRecipients ?? [];
1234
+ draftCc = fetched.ccRecipients ?? [];
1235
+ draftBcc = fetched.bccRecipients ?? [];
1220
1236
  }
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);
1237
+ const draftContent = typeof draftBody?.content === 'string' ? draftBody.content : '';
1238
+ const callerFragment = opts?.bodyHtml !== undefined
1239
+ ? stripHtmlBodyWrappers(opts.bodyHtml)
1240
+ : wrapPlainTextAsHtml(body);
1241
+ const merged = mergeQuotedReplyHtml(draftContent, callerFragment);
1242
+ const patch = {
1243
+ body: { contentType: 'HTML', content: truncateBody(merged) },
1244
+ singleValueExtendedProperties: [
1245
+ { id: DRAFT_ORIGIN_PROPERTY, value: 'reply' },
1246
+ ],
1247
+ };
1248
+ // `to` REPLACES Graph's auto-populated recipients; `cc`/`bcc` below MERGE
1249
+ // with the thread's. The asymmetry is deliberate (issue #164): merging a
1250
+ // caller-supplied To would leave the parent's sender on the To line, which
1251
+ // is exactly the failure being fixed — a reply to your own sent message
1252
+ // stays addressed to yourself. Absent `to`, the patch omits toRecipients
1253
+ // entirely and Graph's derived To stands, unchanged from before.
1254
+ // mergeRecipients([], …) is reused only for its EmailAddress →
1255
+ // GraphRecipient conversion and case-insensitive dedupe.
1256
+ const hasExplicitTo = Boolean(opts?.to && opts.to.length > 0);
1257
+ // Anyone on `bcc` comes off the visible lines Graph derived, so a thread
1258
+ // participant can be moved to Bcc without restating the audience (issue
1259
+ // #214). Bcc wins over a derived To/Cc.
1260
+ const hidden = new Set((opts?.bcc ?? []).map(a => a.email.toLowerCase()));
1261
+ const isVisible = (r) => !hidden.has(r.emailAddress?.address?.toLowerCase() ?? '');
1262
+ if (hasExplicitTo) {
1263
+ patch.toRecipients = mergeRecipients([], opts.to).filter(isVisible);
1264
+ }
1265
+ else if (draftTo.some(r => !isVisible(r))) {
1266
+ // Only touch toRecipients when something must come off it; otherwise
1267
+ // Graph's derived To stands untouched, as before.
1268
+ patch.toRecipients = draftTo.filter(isVisible);
1227
1269
  }
1270
+ // Replacing the To line must not silently drop anyone. On the reply-all
1271
+ // endpoint Graph puts the parent's sender AND its other To participants on
1272
+ // the draft's To; an explicit `to` displaces all of them, so demote the
1273
+ // displaced ones to Cc — reply-all means the thread stays on the message,
1274
+ // and `to` only decides who it is addressed to. This also brings Microsoft
1275
+ // in line with Gmail, which already carries the thread's participants on Cc
1276
+ // under reply-all. On the sender-only endpoint there is nothing to preserve:
1277
+ // Graph's To is just the parent's sender, and replacing that is the point of
1278
+ // a narrowed redirect.
1279
+ const displacedTo = hasExplicitTo && opts?.replyAll !== false
1280
+ ? draftTo.filter(r => {
1281
+ const address = r.emailAddress?.address?.toLowerCase();
1282
+ return address ? !opts.to.some(a => a.email.toLowerCase() === address) : false;
1283
+ })
1284
+ : [];
1285
+ const ccMerged = mergeRecipients([...draftCc, ...displacedTo], opts?.cc ?? []).filter(isVisible);
1286
+ if (ccMerged.length > 0 || draftCc.some(r => !isVisible(r)))
1287
+ patch.ccRecipients = ccMerged;
1288
+ const bccMerged = mergeRecipients(draftBcc, opts?.bcc ?? []);
1289
+ if (bccMerged.length > 0)
1290
+ patch.bccRecipients = bccMerged;
1291
+ await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(draft.id)}`, patch);
1292
+ // Two-step attachment upload: the draft now exists, so POST each file to
1293
+ // its /attachments collection. A failure here leaves a created-but-
1294
+ // incomplete draft — surface its id so the caller can inspect or retry.
1295
+ if (opts?.attachments && opts.attachments.length > 0) {
1296
+ try {
1297
+ await this.postDraftAttachments(draft.id, opts.attachments);
1298
+ }
1299
+ catch (err) {
1300
+ throw new GraphAttachmentError({
1301
+ code: 'ATTACHMENT_UPLOAD_FAILED',
1302
+ message: `Reply draft was created but attaching files failed: ${err instanceof Error ? err.message : String(err)}`,
1303
+ recoverable: false,
1304
+ }, draft.id);
1305
+ }
1306
+ }
1307
+ return draft.id;
1308
+ }
1309
+ catch (err) {
1310
+ if (err instanceof GraphAttachmentError)
1311
+ throw err;
1312
+ throw new GraphAttachmentError({
1313
+ code: 'DRAFT_PREPARATION_FAILED',
1314
+ message: `Reply draft was created but preparation failed: ${err instanceof Error ? err.message : String(err)}`,
1315
+ recoverable: false,
1316
+ }, draft.id);
1228
1317
  }
1229
- return draft.id;
1318
+ }
1319
+ async getDraft(draftId) {
1320
+ // Preserve the existing expanded attachment/unique-body preview reader.
1321
+ const message = await this.getMessage(draftId);
1322
+ if (message.isDraft !== true)
1323
+ throw new MessageNotFoundError(`Editable draft ${draftId} not found`);
1324
+ return message;
1325
+ }
1326
+ async getDraftSnapshot(draftId) {
1327
+ let metadata;
1328
+ try {
1329
+ metadata = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draftId)}`
1330
+ + `?$select=${MESSAGE_SELECT},conversationIndex,changeKey`
1331
+ + `&$expand=singleValueExtendedProperties($filter=id eq '${DRAFT_ORIGIN_PROPERTY}' or id eq '${DEFERRED_SEND_PROPERTY}')`);
1332
+ }
1333
+ catch (err) {
1334
+ if (err instanceof GraphApiError && err.status === 404)
1335
+ throw new MessageNotFoundError(`Draft ${draftId} not found`);
1336
+ throw err;
1337
+ }
1338
+ const scheduledSendAt = findDeferredSendProperty(metadata)?.value;
1339
+ const pending = scheduledSendAt !== undefined && !('error' in validateScheduledSendAt(scheduledSendAt));
1340
+ return {
1341
+ draftId: metadata.id,
1342
+ messageId: metadata.id,
1343
+ message: mapGraphMessage(metadata),
1344
+ revision: metadata.changeKey,
1345
+ lifecycle: metadata.isDraft === true ? (pending ? 'deferred' : 'editable') : 'indeterminate',
1346
+ origin: this.draftOrigin(metadata),
1347
+ scheduledSendAt,
1348
+ };
1230
1349
  }
1231
1350
  async getDraftReplyStatus(draftId) {
1232
1351
  const propertyFilter = `$filter=id eq '${DRAFT_ORIGIN_PROPERTY}'`;
1233
- const metadata = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draftId)}`
1234
- + `?$select=isDraft,conversationIndex`
1235
- + `&$expand=singleValueExtendedProperties(${propertyFilter})`);
1236
- if (metadata.isDraft !== true)
1237
- return 'indeterminate';
1352
+ let metadata;
1353
+ try {
1354
+ metadata = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draftId)}`
1355
+ + `?$select=isDraft,conversationIndex`
1356
+ + `&$expand=singleValueExtendedProperties(${propertyFilter})`);
1357
+ }
1358
+ catch (err) {
1359
+ if (err instanceof GraphApiError && err.status === 404) {
1360
+ throw new MessageNotFoundError(`Draft ${draftId} not found`);
1361
+ }
1362
+ throw err;
1363
+ }
1364
+ return metadata.isDraft === true ? this.draftOrigin(metadata) : 'indeterminate';
1365
+ }
1366
+ draftOrigin(metadata) {
1238
1367
  // Duplicate stamps are ambiguous: taking the first match would make the
1239
1368
  // answer depend on the order Graph returns the collection. Only a single,
1240
1369
  // unanimous stamp is authoritative.
@@ -1283,7 +1412,16 @@ export class GraphEmailProvider {
1283
1412
  return { success: false, draftId, error: sizeError };
1284
1413
  }
1285
1414
  }
1286
- await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(draftId)}`, patch);
1415
+ try {
1416
+ await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(draftId)}`, patch);
1417
+ }
1418
+ catch (err) {
1419
+ return { success: false, draftId, error: {
1420
+ code: 'UPDATE_DRAFT_FAILED',
1421
+ message: err instanceof Error ? err.message : String(err),
1422
+ recoverable: false,
1423
+ } };
1424
+ }
1287
1425
  if (msg.attachments !== undefined) {
1288
1426
  try {
1289
1427
  const existing = await this.client.get(`${this.basePath}/messages/${encodeGraphPathId(draftId)}/attachments?$select=id`);
@@ -1309,16 +1447,54 @@ export class GraphEmailProvider {
1309
1447
  return { success: true, draftId };
1310
1448
  }
1311
1449
  /**
1312
- * Get new inbox messages received after a given timestamp.
1313
- * Uses simple $filter=receivedDateTime gt {since} — instant, no full-inbox sync.
1450
+ * Retrieve a complete inclusive timestamp window; partial results never escape.
1451
+ * The optional end preserves existing callers while bounding every invocation.
1314
1452
  * This is the primary method for the watcher polling loop.
1315
1453
  */
1316
- async getNewMessages(since) {
1317
- const filter = `receivedDateTime ge ${since}`;
1454
+ async getNewMessages(since, end = new Date().toISOString(), signal) {
1455
+ if (!Number.isFinite(Date.parse(since)) || !Number.isFinite(Date.parse(end)) || Date.parse(since) > Date.parse(end)) {
1456
+ throw new Error('Invalid watcher timestamp window');
1457
+ }
1458
+ const filter = `receivedDateTime ge ${since} and receivedDateTime le ${end}`;
1318
1459
  const params = `$filter=${encodeURIComponent(filter)}&$orderby=receivedDateTime desc&$top=50&${DELTA_SELECT}`;
1319
- const url = `${this.basePath}/mailFolders/Inbox/messages?${params}`;
1320
- const response = await this.client.get(url);
1321
- return (response.value ?? []).map(mapGraphMessage);
1460
+ let url = `${this.basePath}/mailFolders/Inbox/messages?${params}`;
1461
+ const seen = new Set();
1462
+ const messages = [];
1463
+ while (url) {
1464
+ signal?.throwIfAborted();
1465
+ if (seen.has(url) || seen.size >= 1000)
1466
+ throw new Error('Watcher pagination repeated a link or exceeded 1000 pages');
1467
+ seen.add(url);
1468
+ const response = await this.client.get(url, signal);
1469
+ signal?.throwIfAborted();
1470
+ if (!Array.isArray(response.value))
1471
+ throw new Error('Invalid watcher message page');
1472
+ for (const raw of response.value) {
1473
+ // The general mapper supplies defaults for other actions. Watcher
1474
+ // windows must validate source identity/time before those defaults.
1475
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
1476
+ throw new Error('Invalid watcher message identity or timestamp');
1477
+ }
1478
+ const message = raw;
1479
+ if (typeof message.id !== 'string' || !message.id.trim()
1480
+ || !Object.hasOwn(message, 'receivedDateTime')
1481
+ || typeof message.receivedDateTime !== 'string' || !message.receivedDateTime.trim()
1482
+ || !Number.isFinite(Date.parse(message.receivedDateTime))) {
1483
+ throw new Error('Invalid watcher message identity or timestamp');
1484
+ }
1485
+ messages.push(mapGraphMessage(raw));
1486
+ }
1487
+ const next = response['@odata.nextLink'];
1488
+ if (next !== undefined && (typeof next !== 'string' || !next))
1489
+ throw new Error('Invalid watcher nextLink');
1490
+ url = next;
1491
+ }
1492
+ return messages.filter(message => {
1493
+ const received = Date.parse(message.receivedAt);
1494
+ if (!Number.isFinite(received))
1495
+ throw new Error('Invalid watcher message timestamp');
1496
+ return received >= Date.parse(since) && received <= Date.parse(end);
1497
+ });
1322
1498
  }
1323
1499
  /**
1324
1500
  * Delta Query polling — follows all pages.
@@ -1330,8 +1506,13 @@ export class GraphEmailProvider {
1330
1506
  let url = deltaLink;
1331
1507
  const allMessages = [];
1332
1508
  let finalDeltaLink = '';
1509
+ const visited = new Set();
1333
1510
  // Page through all results (follow @odata.nextLink until @odata.deltaLink)
1334
1511
  while (url) {
1512
+ if (visited.has(url) || visited.size >= 100) {
1513
+ throw new ProviderError('PAGINATION_LIMIT', 'Delta pagination exceeded its safety limit', 'microsoft', false);
1514
+ }
1515
+ visited.add(url);
1335
1516
  const response = await this.client.get(url);
1336
1517
  const items = response.value ?? [];
1337
1518
  // Filter out @removed tombstones and map the rest
@@ -1350,13 +1531,12 @@ export class GraphEmailProvider {
1350
1531
  url = response['@odata.nextLink'];
1351
1532
  }
1352
1533
  else {
1353
- // No nextLink and no deltaLink — shouldn't happen, but break to avoid infinite loop
1354
- break;
1534
+ throw new ProviderError('INVALID_DELTA_RESPONSE', 'Delta response omitted the terminal cursor', 'microsoft', false);
1355
1535
  }
1356
1536
  }
1357
1537
  return {
1358
1538
  messages: allMessages,
1359
- nextDeltaLink: finalDeltaLink || url,
1539
+ nextDeltaLink: finalDeltaLink,
1360
1540
  };
1361
1541
  }
1362
1542
  // NemoClaw egress domains
@@ -1369,19 +1549,13 @@ export class GraphEmailProvider {
1369
1549
  ? response.categories.filter((value) => typeof value === 'string')
1370
1550
  : [];
1371
1551
  }
1372
- async getFolderSnapshot() {
1373
- const now = Date.now();
1374
- if (this.folderCache && this.folderCache.expiresAt > now) {
1375
- return { folders: this.folderCache.folders, truncated: false };
1376
- }
1377
- const budget = { remaining: MAX_FOLDER_REQUESTS_PER_SNAPSHOT, truncated: false };
1378
- const folders = await this.fetchFolderCollection(`${this.basePath}/mailFolders?${FOLDER_SELECT}&$top=100&includeHiddenFolders=true`, '', new Set(), budget);
1379
- // Never cache a partial tree — a truncated snapshot would otherwise make
1380
- // "folder not found" sticky for 60s on a folder that does exist.
1381
- if (!budget.truncated) {
1382
- this.folderCache = { expiresAt: now + FOLDER_CACHE_TTL_MS, folders };
1383
- }
1384
- return { folders, truncated: budget.truncated };
1552
+ async getFolderSnapshot(fresh = false) {
1553
+ return this.folderCache.get(async () => {
1554
+ const budget = { remaining: MAX_FOLDER_REQUESTS_PER_SNAPSHOT, truncated: false };
1555
+ const folders = await this.fetchFolderCollection(`${this.basePath}/mailFolders?${FOLDER_SELECT}&$top=100&includeHiddenFolders=true`, '', new Set(), budget);
1556
+ // A partial tree cannot establish absence or uniqueness.
1557
+ return { folders, truncated: budget.truncated };
1558
+ }, snapshot => !snapshot.truncated, fresh);
1385
1559
  }
1386
1560
  async fetchFolderCollection(initialUrl, parentPath, visitedFolderIds,
1387
1561
  // Shared across the whole recursive traversal, not per collection, so a
@@ -1419,13 +1593,10 @@ export class GraphEmailProvider {
1419
1593
  /**
1420
1594
  * Resolve a folder name/path/id to a Graph folder id.
1421
1595
  *
1422
- * `forWrite` is reserved for operations that MUTATE the folder tree
1423
- * (createFolder's parent, deleteFolder's target): these are low-frequency and
1424
- * high-harm — deleting or nesting under a stale-cached id is unrecoverable —
1425
- * so they re-fetch to get a current path→id mapping. Message moves and rule
1426
- * destinations deliberately do NOT pass forWrite: they don't change the tree,
1427
- * they run in high-volume loops, and their worst-case staleness (the 60s
1428
- * rename race) is the same recoverable risk we already accept for reads.
1596
+ * Structural writes and persistent rule destinations bypass ready snapshots
1597
+ * for fresh path→id validation, sharing any active traversal. Message moves
1598
+ * retain the ordinary 60s cache. Validation does not invalidate system IDs or
1599
+ * advance generations; successful structural mutations invalidate both caches.
1429
1600
  */
1430
1601
  async resolveFolderId(folder, forWrite = false) {
1431
1602
  const trimmed = folder.trim();
@@ -1434,9 +1605,7 @@ export class GraphEmailProvider {
1434
1605
  ?? (SYSTEM_FOLDER_NAME_SET.has(normalized) ? normalized : undefined);
1435
1606
  if (wellKnown)
1436
1607
  return wellKnown;
1437
- if (forWrite)
1438
- this.invalidateFolderCaches();
1439
- const { folders, truncated } = await this.getFolderSnapshot();
1608
+ const { folders, truncated } = await this.getFolderSnapshot(forWrite);
1440
1609
  // Exact id match is safe even against a truncated tree — ids are globally
1441
1610
  // unique, so a visible match is THE match regardless of unseen folders.
1442
1611
  const idMatch = folders.find(candidate => candidate.id === trimmed);
@@ -1527,10 +1696,9 @@ export class GraphEmailProvider {
1527
1696
  }
1528
1697
  /** Well-known-name -> resolved id for every provisioned system folder. */
1529
1698
  async getSystemFolderIdMap() {
1530
- const now = Date.now();
1531
- if (this.systemFolderIdsCache && this.systemFolderIdsCache.expiresAt > now) {
1532
- return this.systemFolderIdsCache.idsByName;
1533
- }
1699
+ return this.systemFolderIdsCache.get(() => this.fetchSystemFolderIdMap(), () => true);
1700
+ }
1701
+ async fetchSystemFolderIdMap() {
1534
1702
  const idsByName = new Map();
1535
1703
  for (const name of SYSTEM_FOLDER_NAMES) {
1536
1704
  try {
@@ -1545,7 +1713,6 @@ export class GraphEmailProvider {
1545
1713
  throw err;
1546
1714
  }
1547
1715
  }
1548
- this.systemFolderIdsCache = { expiresAt: now + FOLDER_CACHE_TTL_MS, idsByName };
1549
1716
  return idsByName;
1550
1717
  }
1551
1718
  /** Ids of ALL system folders — none may be deleted. */
@@ -1568,8 +1735,8 @@ export class GraphEmailProvider {
1568
1735
  return ids;
1569
1736
  }
1570
1737
  invalidateFolderCaches() {
1571
- this.folderCache = undefined;
1572
- this.systemFolderIdsCache = undefined;
1738
+ this.folderCache.invalidate();
1739
+ this.systemFolderIdsCache.invalidate();
1573
1740
  }
1574
1741
  }
1575
1742
  function findDeferredSendProperty(message) {
@@ -1594,16 +1761,14 @@ function decodeConversationIndex(value) {
1594
1761
  return undefined;
1595
1762
  return decoded.length;
1596
1763
  }
1597
- function scheduledDraftSendFailure(draftId, scheduledSendAt, err) {
1764
+ function scheduledDispatchFailure(draftId, err) {
1598
1765
  // Shares classifyGraphDelivery with the immediate-send paths so the two
1599
1766
  // families cannot drift on what counts as ambiguous. The codes stay
1600
1767
  // scheduled-specific because they are spec'd and because the remedy differs:
1601
1768
  // here there is a tagged draft to inspect or cancel.
1602
1769
  const failure = classifyGraphDelivery(err);
1603
1770
  return {
1604
- success: false,
1605
- messageId: draftId,
1606
- scheduledSendAt,
1771
+ outcome: failure.ambiguous ? 'unknown' : 'rejected',
1607
1772
  error: {
1608
1773
  code: failure.ambiguous ? 'SCHEDULE_SEND_STATUS_UNKNOWN' : 'SCHEDULE_SEND_FAILED',
1609
1774
  message: failure.ambiguous