@miguelarios/email-mcp 0.18.0 → 1.1.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0 (2026-11-02)
4
+
5
+ - **New tool: `update_draft`** (#137, #157). It changes an existing draft's recipients, subject, body or attachments in place. Before, an agent revising a draft had to save a new one and then permanently delete the old one; when that confirmation-gated delete was skipped or declined, duplicate drafts piled up. Only the fields given change. The draft keeps its From, Reply-To and threading headers (a reply draft stays a reply), its attachments (inline images keep their Content-ID, text attachments their charset), a calendar invitation, read-receipt and priority headers, and its flags. A new `text` or `html` replaces the whole body. It asks for no confirmation, and returns the new UID, `previousUid`, and `previousRemoved`.
6
+ - The swap is a single atomic `UID REPLACE` where the server supports RFC 8508. Elsewhere the new version is appended before the old one is expunged, so a failure never leaves zero copies. On a server without UIDPLUS, the old version is left in place (`previousRemoved: false`) when other messages in the folder are already marked `\Deleted`, because a plain `EXPUNGE` would purge those too.
7
+ - A message outside the Drafts folder without the `\Draft` flag is refused, so a received email is never rewritten.
8
+
9
+ ## 1.0.0 (2026-10-18)
10
+
11
+ First stable release. The public contract, and what a minor or patch may change from here, is in [`docs/versioning.md`](../../docs/versioning.md).
12
+
13
+ - **Breaking: requires Node.js 22.12.0 or newer** (was 20.19.0). Node 20 reached end of life in April 2026, and raising the floor after 1.0 would need a major release (#150).
14
+ - **A folder that does not exist is `FOLDER_NOT_FOUND`**, naming the folder and quoting the server, on every tool that takes one. It was `INTERNAL_ERROR`, usually with the message "Command failed". `copy_email` to a missing destination was `OPERATION_FAILED`.
15
+ - **`move_email` fails when the server refuses the move**, instead of reporting success with nothing moved, and on a server without the IMAP MOVE extension does the copy-then-delete itself, deleting the originals only after the copy succeeded: imapflow's own fallback deleted them even when the copy was refused (a missing folder, a full quota, no permission). `delete_email`'s move to Trash and `mark_email` likewise fail on a refusal, and `get_folder_status` on a folder that cannot be opened (a parent-only folder) fails rather than reporting zeros.
16
+ - `send_draft` reports a sent message as sent even if deleting the draft afterwards fails, so a caller is not invited to send it twice. `mark_email` rejects an empty `flags` with `INVALID_INPUT`.
17
+ - Other IMAP refusals are `OPERATION_FAILED` with the server's reason, a wrong password is `AUTH_FAILED`, an SMTP rejection is `SEND_FAILED` (retryable only for a 4xx reply), and a `from` address outside `SMTP_ALLOWED_FROM` is `INVALID_INPUT` (pim-core).
18
+ - Bumped `@miguelarios/pim-core` to `^1.0.0`.
19
+
3
20
  ## 0.18.0 (2026-10-18)
4
21
 
5
22
  - **`send_email`, `forward_email` and `send_draft` return the `Message-ID` the sent message carries** (#130). They returned an ID nodemailer invented and never sent, so it matched neither the delivered copy nor the Sent copy. A draft from another client that has no `Message-ID` gets one before it is sent and filed.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Miguel Rios
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -9,7 +9,7 @@ Every tool declares a `title`, all four behaviour annotations, and an `outputSch
9
9
 
10
10
  `send_email` and `forward_email` (when sending, not when saving a draft), `send_draft`, `delete_email` with `permanent: true`, and `delete_folder` ask the user to confirm first. Set `PIM_MCP_CONFIRM=off` to skip confirmation in headless use.
11
11
 
12
- Requires Node.js **20.19.0 or newer**.
12
+ Requires Node.js **22.12.0 or newer**.
13
13
 
14
14
  ## Usage
15
15
 
@@ -88,12 +88,12 @@ docker run -d --name email-mcp --restart unless-stopped --user node \
88
88
  --env-file email.env \
89
89
  -e PIM_MCP_TRANSPORT=http -e PIM_MCP_HTTP_HOST=0.0.0.0 \
90
90
  -p 127.0.0.1:3001:3000 -v email-mcp-home:/home/node \
91
- node:22-alpine npx -y @miguelarios/email-mcp@0.17.0
91
+ node:22-alpine npx -y @miguelarios/email-mcp@1.1.0
92
92
  ```
93
93
 
94
94
  See the [Docker guide](https://github.com/miguelarios/pim-agents/blob/main/docs/docker.md) for the env file, stdio use from a desktop client, Docker Compose, and exposing a server safely, and the [README](https://github.com/miguelarios/pim-agents/blob/main/README.md#over-streamable-http) for every HTTP setting.
95
95
 
96
- ## Tools (17)
96
+ ## Tools (18)
97
97
 
98
98
  See [docs/tools/email-mcp.md](../../docs/tools/email-mcp.md) for full parameter and output details.
99
99
 
@@ -103,6 +103,7 @@ See [docs/tools/email-mcp.md](../../docs/tools/email-mcp.md) for full parameter
103
103
  | `get_email` | Fetch full email by UID — headers, body, attachment metadata, calendar invitation parts |
104
104
  | `get_thread` | Fetch the whole conversation a message belongs to, oldest first |
105
105
  | `send_email` | Compose and send via SMTP, reply or reply-all with threading, save as draft, or use an allowed visible From address |
106
+ | `update_draft` | Change a draft's recipients, subject, body or attachments in place, keeping the rest |
106
107
  | `send_draft` | Send an existing draft from the Drafts folder |
107
108
  | `forward_email` | Forward a message with its attachments and an optional note |
108
109
  | `move_email` | Move emails between folders |
@@ -123,6 +123,20 @@ export interface RawEmailTooLarge {
123
123
  source?: undefined;
124
124
  }
125
125
  export type RawEmailResult = RawEmailSource | RawEmailTooLarge;
126
+ /** A message's source and flags, as update_draft reads a draft. */
127
+ export interface DraftSource {
128
+ source: Buffer;
129
+ flags: string[];
130
+ }
131
+ /** How a draft was swapped for its new version. */
132
+ export interface DraftReplacement {
133
+ /** The new version's UID; null when the server gave no way to learn it. */
134
+ uid: number | null;
135
+ /** False when the old version could not be removed and is still there. */
136
+ previousRemoved: boolean;
137
+ /** True when the server swapped them in one command (RFC 8508 REPLACE). */
138
+ atomic: boolean;
139
+ }
126
140
  export interface SearchOptions {
127
141
  limit?: number;
128
142
  offset?: number;
@@ -170,6 +184,20 @@ export declare class ImapService {
170
184
  fetchEmail(folder: string, uid: number): Promise<EmailFull>;
171
185
  fetchRawEmail(folder: string, uid: number): Promise<string>;
172
186
  fetchRawEmail(folder: string, uid: number, maxBytes: number): Promise<RawEmailResult>;
187
+ /**
188
+ * The error for a COPY or MOVE the server refused. imapflow resolves `false`
189
+ * and keeps the reason (usually `NO [TRYCREATE]`, a missing destination) to
190
+ * itself, so ask STATUS whether the destination exists.
191
+ */
192
+ private refusedTransfer;
193
+ /**
194
+ * MOVE, failing loudly. On a server without the MOVE extension imapflow
195
+ * falls back to COPY then delete, and deletes even when the COPY was
196
+ * refused (a missing folder, a full quota, no permission), so that fallback
197
+ * is done here instead: the originals are deleted only after the copy
198
+ * succeeded.
199
+ */
200
+ private moveOrThrow;
173
201
  /**
174
202
  * Copies messages, leaving the originals in place.
175
203
  *
@@ -213,6 +241,26 @@ export declare class ImapService {
213
241
  uid: number;
214
242
  }>;
215
243
  fetchRawSource(folder: string, uid: number): Promise<Buffer>;
244
+ /** One message's raw source and flags, for update_draft. */
245
+ fetchDraft(folder: string, uid: number): Promise<DraftSource>;
246
+ /**
247
+ * Swaps the message at `uid` for `raw`, in the same folder.
248
+ *
249
+ * With RFC 8508 REPLACE the server does it atomically. Otherwise the new
250
+ * version is appended first and the old one expunged only after that
251
+ * succeeded, so a failure at any point leaves at least one copy: never zero.
252
+ * A failure after the APPEND leaves two, which `previousRemoved: false`
253
+ * reports rather than hides. So does a server without UIDPLUS when another
254
+ * message in the folder is already flagged \Deleted: its plain EXPUNGE
255
+ * would purge that message too, so the old version is left in place.
256
+ *
257
+ * The new UID comes from the server's APPENDUID (UIDPLUS); imapflow already
258
+ * falls back to the EXISTS sequence number when appending to the selected
259
+ * folder, and failing both, the new version is found by its Message-ID.
260
+ * `null` means none of these identified it, which is reported rather than
261
+ * guessed.
262
+ */
263
+ replaceDraft(folder: string, uid: number, raw: Buffer, flags: string[], messageId: string): Promise<DraftReplacement>;
216
264
  getFolderStatus(folder: string): Promise<{
217
265
  total: number;
218
266
  unseen: number;
@@ -1 +1 @@
1
- {"version":3,"file":"ImapService.d.ts","sourceRoot":"","sources":["../../src/services/ImapService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAMjB,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EAAE,KAAK,YAAY,EAAuB,MAAM,cAAc,CAAC;AAEtE,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IACzC,EAAE,EAAE,KAAK,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC9C,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,cAAc,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,SAAU,SAAQ,YAAY;IAC7C,EAAE,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,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;IAwBlE,4DAA4D;IACtD,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAiCnE;;;;;;;;;;;;;;;;OAgBG;IACG,YAAY,CAChB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,EAAE,EACf,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,gBAAgB,CAAC;IAwEtB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CAoBlF"}
@@ -1,8 +1,9 @@
1
- import { EmailError, ErrorCode, formatInTimezone, getTimezone, toPimError, } from "@miguelarios/pim-core";
1
+ import { EmailError, ErrorCode, formatInTimezone, getTimezone, } from "@miguelarios/pim-core";
2
2
  import { ImapFlow } from "imapflow";
3
3
  import { simpleParser } from "mailparser";
4
4
  import { uidSort } from "../imapSort.js";
5
5
  import { buildSearchCriteria } from "../search.js";
6
+ import { toImapError } from "./imapErrors.js";
6
7
  /**
7
8
  * A lower bound on a base64 part's decoded size, from its encoded
8
9
  * BODYSTRUCTURE size, or undefined when there is no safe bound. 64-character
@@ -61,7 +62,7 @@ export class ImapService {
61
62
  }));
62
63
  }
63
64
  catch (error) {
64
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
65
+ throw toImapError(error);
65
66
  }
66
67
  finally {
67
68
  await client.logout().catch(() => { });
@@ -133,7 +134,7 @@ export class ImapService {
133
134
  }
134
135
  }
135
136
  catch (error) {
136
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
137
+ throw toImapError(error, folder);
137
138
  }
138
139
  finally {
139
140
  await client.logout().catch(() => { });
@@ -296,7 +297,7 @@ export class ImapService {
296
297
  catch (error) {
297
298
  if (error instanceof EmailError)
298
299
  throw error;
299
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
300
+ throw toImapError(error, anchorFolder);
300
301
  }
301
302
  finally {
302
303
  await client.logout().catch(() => { });
@@ -360,7 +361,7 @@ export class ImapService {
360
361
  catch (error) {
361
362
  if (error instanceof EmailError)
362
363
  throw error;
363
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
364
+ throw toImapError(error, folder);
364
365
  }
365
366
  finally {
366
367
  await client.logout().catch(() => { });
@@ -403,12 +404,47 @@ export class ImapService {
403
404
  catch (error) {
404
405
  if (error instanceof EmailError)
405
406
  throw error;
406
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
407
+ throw toImapError(error, folder);
407
408
  }
408
409
  finally {
409
410
  await client.logout().catch(() => { });
410
411
  }
411
412
  }
413
+ /**
414
+ * The error for a COPY or MOVE the server refused. imapflow resolves `false`
415
+ * and keeps the reason (usually `NO [TRYCREATE]`, a missing destination) to
416
+ * itself, so ask STATUS whether the destination exists.
417
+ */
418
+ async refusedTransfer(client, verb, destination) {
419
+ try {
420
+ await client.status(destination, { messages: true });
421
+ }
422
+ catch (error) {
423
+ const classified = toImapError(error, destination);
424
+ if (classified.code === ErrorCode.FOLDER_NOT_FOUND)
425
+ return classified;
426
+ }
427
+ return new EmailError(`${verb} to ${destination} failed — the server refused it. Check list_folders for the exact path.`, ErrorCode.OPERATION_FAILED);
428
+ }
429
+ /**
430
+ * MOVE, failing loudly. On a server without the MOVE extension imapflow
431
+ * falls back to COPY then delete, and deletes even when the COPY was
432
+ * refused (a missing folder, a full quota, no permission), so that fallback
433
+ * is done here instead: the originals are deleted only after the copy
434
+ * succeeded.
435
+ */
436
+ async moveOrThrow(client, uidRange, destination) {
437
+ if (!client.capabilities.has("MOVE")) {
438
+ const copied = await client.messageCopy(uidRange, destination, { uid: true });
439
+ if (!copied)
440
+ throw await this.refusedTransfer(client, "Move", destination);
441
+ await client.messageDelete(uidRange, { uid: true });
442
+ return;
443
+ }
444
+ const moved = await client.messageMove(uidRange, destination, { uid: true });
445
+ if (!moved)
446
+ throw await this.refusedTransfer(client, "Move", destination);
447
+ }
412
448
  /**
413
449
  * Copies messages, leaving the originals in place.
414
450
  *
@@ -431,9 +467,8 @@ export class ImapService {
431
467
  const lock = await client.getMailboxLock(folder);
432
468
  try {
433
469
  const result = await client.messageCopy(uids.join(","), destination, { uid: true });
434
- if (!result) {
435
- throw new EmailError(`Copy to ${destination} failed — the server refused it. The folder may not exist; create_folder first, or check list_folders for the exact path.`, ErrorCode.OPERATION_FAILED);
436
- }
470
+ if (!result)
471
+ throw await this.refusedTransfer(client, "Copy", destination);
437
472
  if (!result.uidMap)
438
473
  return undefined;
439
474
  return [...result.uidMap].map(([uid, destinationUid]) => ({ uid, destinationUid }));
@@ -445,7 +480,7 @@ export class ImapService {
445
480
  catch (error) {
446
481
  if (error instanceof EmailError)
447
482
  throw error;
448
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
483
+ throw toImapError(error, folder);
449
484
  }
450
485
  finally {
451
486
  await client.logout().catch(() => { });
@@ -457,16 +492,14 @@ export class ImapService {
457
492
  await client.connect();
458
493
  const lock = await client.getMailboxLock(folder);
459
494
  try {
460
- await client.messageMove(uids.join(","), destination, {
461
- uid: true,
462
- });
495
+ await this.moveOrThrow(client, uids.join(","), destination);
463
496
  }
464
497
  finally {
465
498
  lock.release();
466
499
  }
467
500
  }
468
501
  catch (error) {
469
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
502
+ throw toImapError(error, folder);
470
503
  }
471
504
  finally {
472
505
  await client.logout().catch(() => { });
@@ -479,13 +512,11 @@ export class ImapService {
479
512
  const lock = await client.getMailboxLock(folder);
480
513
  try {
481
514
  const uidRange = uids.join(",");
482
- if (action === "add") {
483
- await client.messageFlagsAdd(uidRange, flags, { uid: true });
484
- }
485
- else {
486
- await client.messageFlagsRemove(uidRange, flags, {
487
- uid: true,
488
- });
515
+ const stored = action === "add"
516
+ ? await client.messageFlagsAdd(uidRange, flags, { uid: true })
517
+ : await client.messageFlagsRemove(uidRange, flags, { uid: true });
518
+ if (!stored) {
519
+ throw new EmailError(`Could not ${action === "add" ? "set" : "clear"} ${flags.join(", ")} in ${folder}: the server refused, or the folder does not allow these flags (see its PERMANENTFLAGS)`, ErrorCode.OPERATION_FAILED);
489
520
  }
490
521
  }
491
522
  finally {
@@ -493,7 +524,7 @@ export class ImapService {
493
524
  }
494
525
  }
495
526
  catch (error) {
496
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
527
+ throw toImapError(error, folder);
497
528
  }
498
529
  finally {
499
530
  await client.logout().catch(() => { });
@@ -511,7 +542,7 @@ export class ImapService {
511
542
  await client.messageDelete(uidRange, { uid: true });
512
543
  }
513
544
  else {
514
- await client.messageMove(uidRange, trashFolder, { uid: true });
545
+ await this.moveOrThrow(client, uidRange, trashFolder);
515
546
  }
516
547
  }
517
548
  finally {
@@ -519,7 +550,7 @@ export class ImapService {
519
550
  }
520
551
  }
521
552
  catch (error) {
522
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
553
+ throw toImapError(error, folder);
523
554
  }
524
555
  finally {
525
556
  await client.logout().catch(() => { });
@@ -532,7 +563,7 @@ export class ImapService {
532
563
  await client.mailboxCreate(path);
533
564
  }
534
565
  catch (error) {
535
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
566
+ throw toImapError(error, path);
536
567
  }
537
568
  finally {
538
569
  await client.logout().catch(() => { });
@@ -560,7 +591,7 @@ export class ImapService {
560
591
  };
561
592
  }
562
593
  catch (error) {
563
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
594
+ throw toImapError(error, path);
564
595
  }
565
596
  finally {
566
597
  await client.logout().catch(() => { });
@@ -579,7 +610,7 @@ export class ImapService {
579
610
  this.specialUseCache.clear();
580
611
  }
581
612
  catch (error) {
582
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
613
+ throw toImapError(error, path);
583
614
  }
584
615
  finally {
585
616
  await client.logout().catch(() => { });
@@ -640,7 +671,7 @@ export class ImapService {
640
671
  catch (error) {
641
672
  if (error instanceof EmailError)
642
673
  throw error;
643
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
674
+ throw toImapError(error, folder);
644
675
  }
645
676
  finally {
646
677
  await client.logout().catch(() => { });
@@ -680,7 +711,7 @@ export class ImapService {
680
711
  catch (error) {
681
712
  if (error instanceof EmailError)
682
713
  throw error;
683
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
714
+ throw toImapError(error);
684
715
  }
685
716
  finally {
686
717
  await client.logout().catch(() => { });
@@ -695,7 +726,7 @@ export class ImapService {
695
726
  return { uid: result && typeof result === "object" && "uid" in result ? result.uid : 0 };
696
727
  }
697
728
  catch (error) {
698
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
729
+ throw toImapError(error, folder);
699
730
  }
700
731
  finally {
701
732
  await client.logout().catch(() => { });
@@ -722,7 +753,112 @@ export class ImapService {
722
753
  catch (error) {
723
754
  if (error instanceof EmailError)
724
755
  throw error;
725
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
756
+ throw toImapError(error, folder);
757
+ }
758
+ finally {
759
+ await client.logout().catch(() => { });
760
+ }
761
+ }
762
+ /** One message's raw source and flags, for update_draft. */
763
+ async fetchDraft(folder, uid) {
764
+ const client = this.createClient();
765
+ try {
766
+ await client.connect();
767
+ const lock = await client.getMailboxLock(folder);
768
+ try {
769
+ const fetched = await client.fetchOne(String(uid), { source: true, flags: true }, { uid: true });
770
+ if (!fetched || !fetched.source) {
771
+ throw new EmailError(`Draft UID ${uid} not found in ${folder}`, ErrorCode.EMAIL_NOT_FOUND, uid);
772
+ }
773
+ return {
774
+ source: Buffer.isBuffer(fetched.source) ? fetched.source : Buffer.from(fetched.source),
775
+ flags: [...(fetched.flags ?? [])],
776
+ };
777
+ }
778
+ finally {
779
+ lock.release();
780
+ }
781
+ }
782
+ catch (error) {
783
+ if (error instanceof EmailError)
784
+ throw error;
785
+ throw toImapError(error, folder);
786
+ }
787
+ finally {
788
+ await client.logout().catch(() => { });
789
+ }
790
+ }
791
+ /**
792
+ * Swaps the message at `uid` for `raw`, in the same folder.
793
+ *
794
+ * With RFC 8508 REPLACE the server does it atomically. Otherwise the new
795
+ * version is appended first and the old one expunged only after that
796
+ * succeeded, so a failure at any point leaves at least one copy: never zero.
797
+ * A failure after the APPEND leaves two, which `previousRemoved: false`
798
+ * reports rather than hides. So does a server without UIDPLUS when another
799
+ * message in the folder is already flagged \Deleted: its plain EXPUNGE
800
+ * would purge that message too, so the old version is left in place.
801
+ *
802
+ * The new UID comes from the server's APPENDUID (UIDPLUS); imapflow already
803
+ * falls back to the EXISTS sequence number when appending to the selected
804
+ * folder, and failing both, the new version is found by its Message-ID.
805
+ * `null` means none of these identified it, which is reported rather than
806
+ * guessed.
807
+ */
808
+ async replaceDraft(folder, uid, raw, flags, messageId) {
809
+ const client = this.createClient();
810
+ try {
811
+ await client.connect();
812
+ const lock = await client.getMailboxLock(folder);
813
+ try {
814
+ // The folder as selected, after imapflow's normalisation (namespace
815
+ // prefix, INBOX case), so REPLACE targets the mailbox the lock opened.
816
+ const selected = (client.mailbox || undefined)?.path || folder;
817
+ // It goes out as an atom. A name that needs modified UTF-7 (non-ASCII,
818
+ // or an `&`) would need imapflow's encodePath, an internal module, so
819
+ // it takes the non-atomic path instead, which is still correct.
820
+ if (client.capabilities.has("REPLACE") && /^[\x20-\x25\x27-\x7e]+$/.test(selected)) {
821
+ const replacedUid = await uidReplace(client, uid, selected, raw, storableFlags(client, flags));
822
+ return {
823
+ uid: replacedUid ?? (await findByMessageId(client, messageId, uid)),
824
+ previousRemoved: true,
825
+ atomic: true,
826
+ };
827
+ }
828
+ const appended = await client.append(folder, raw, flags);
829
+ if (!appended) {
830
+ throw new EmailError(`Could not save the new version of draft ${uid} to ${folder}: the server refused the APPEND. The draft is unchanged.`, ErrorCode.OPERATION_FAILED);
831
+ }
832
+ // From here the new version is safe on the server. Nothing below may
833
+ // throw: an error would read as "nothing was saved" and invite a
834
+ // retry, adding a third copy. What goes wrong is reported instead.
835
+ const newUid = appended.uid ?? (await findByMessageId(client, messageId, uid).catch(() => null));
836
+ let previousRemoved = false;
837
+ try {
838
+ if (await canExpungeOnly(client, uid)) {
839
+ await client.messageDelete(String(uid), { uid: true });
840
+ // imapflow's delete resolves true even when the \Deleted STORE
841
+ // before the EXPUNGE was refused, so look rather than trust it.
842
+ const remaining = await client.search({ uid: String(uid) }, { uid: true });
843
+ previousRemoved = Array.isArray(remaining) && !remaining.includes(uid);
844
+ }
845
+ else {
846
+ console.error(`[email-mcp] Saved the new draft, but left UID ${uid} in ${folder}: without UIDPLUS the expunge would also remove other messages already marked \\Deleted there`);
847
+ }
848
+ }
849
+ catch (deleteError) {
850
+ console.error(`[email-mcp] Saved the new draft, but could not remove UID ${uid}:`, deleteError);
851
+ }
852
+ return { uid: newUid, previousRemoved, atomic: false };
853
+ }
854
+ finally {
855
+ lock.release();
856
+ }
857
+ }
858
+ catch (error) {
859
+ if (error instanceof EmailError)
860
+ throw error;
861
+ throw toImapError(error, folder);
726
862
  }
727
863
  finally {
728
864
  await client.logout().catch(() => { });
@@ -733,10 +869,15 @@ export class ImapService {
733
869
  try {
734
870
  await client.connect();
735
871
  const status = await client.status(folder, { messages: true, unseen: true });
872
+ // imapflow resolves `false` when STATUS is refused on a folder that does
873
+ // exist, such as a \Noselect parent; zeros would claim it is empty.
874
+ if (!status) {
875
+ throw new EmailError(`The server refused STATUS on ${folder}; it may not hold messages (a parent-only folder).`, ErrorCode.OPERATION_FAILED);
876
+ }
736
877
  return { total: status.messages ?? 0, unseen: status.unseen ?? 0 };
737
878
  }
738
879
  catch (error) {
739
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
880
+ throw toImapError(error, folder);
740
881
  }
741
882
  finally {
742
883
  await client.logout().catch(() => { });
@@ -888,4 +1029,82 @@ function decodeText(buffer, charset) {
888
1029
  }
889
1030
  return buffer.toString("utf-8");
890
1031
  }
1032
+ /**
1033
+ * `UID REPLACE` (RFC 8508 §3.4), returning the new UID from the APPENDUID
1034
+ * response code when the server sends one.
1035
+ *
1036
+ * imapflow has no REPLACE command, so this drives `exec` directly, as
1037
+ * `imapSort` does for SORT. Unlike SORT it does not fail soft: a refusal
1038
+ * leaves the old message untouched (the command is atomic), and the caller
1039
+ * needs to hear about it rather than fall through to a non-atomic swap that
1040
+ * would most likely be refused for the same reason.
1041
+ */
1042
+ async function uidReplace(client, uid, folder, raw, flags) {
1043
+ // RFC 8508 §3.4 sends APPENDUID in an untagged OK, ahead of the EXPUNGE,
1044
+ // and the tagged OK carries no code. imapflow drops untagged OK after
1045
+ // login, so it is caught here; the tagged reply is read too, for a server
1046
+ // that puts it there instead.
1047
+ let appendUid;
1048
+ const response = await client.exec("UID REPLACE", [
1049
+ { type: "SEQUENCE", value: String(uid) },
1050
+ { type: "ATOM", value: folder },
1051
+ flags.map((flag) => ({ type: "ATOM", value: flag })),
1052
+ { type: "LITERAL", value: raw },
1053
+ ], {
1054
+ untagged: {
1055
+ OK: async (untagged) => {
1056
+ appendUid ??= appendUidOf(untagged);
1057
+ },
1058
+ },
1059
+ });
1060
+ // imapflow's own commands call this to release the response; skipping it
1061
+ // would leave the connection waiting on a reader that never runs.
1062
+ response?.next?.();
1063
+ return appendUid ?? appendUidOf(response?.response);
1064
+ }
1065
+ /** The UID in an `[APPENDUID <validity> <uid>]` response code, if there is one. */
1066
+ function appendUidOf(response) {
1067
+ const section = response?.attributes?.[0]?.section;
1068
+ const code = section?.[0]?.value;
1069
+ if (typeof code !== "string" || code.toUpperCase() !== "APPENDUID")
1070
+ return undefined;
1071
+ const value = section?.[2]?.value;
1072
+ return typeof value === "string" && /^\d+$/.test(value) ? Number(value) : undefined;
1073
+ }
1074
+ /**
1075
+ * Whether expunging `uid` removes only `uid`. With UIDPLUS imapflow sends
1076
+ * `UID EXPUNGE <uid>`; without it, a plain `EXPUNGE`, which also removes
1077
+ * every other message in the folder already flagged \Deleted — mail the user
1078
+ * marked for deletion but has not purged, which update_draft must not purge
1079
+ * for them. Without UIDPLUS, then, it is safe only when no other message
1080
+ * carries the flag.
1081
+ */
1082
+ async function canExpungeOnly(client, uid) {
1083
+ if (client.capabilities.has("UIDPLUS"))
1084
+ return true;
1085
+ const deleted = await client.search({ deleted: true }, { uid: true });
1086
+ return Array.isArray(deleted) && deleted.every((u) => u === uid);
1087
+ }
1088
+ /**
1089
+ * The flags the selected folder can store. imapflow's APPEND drops the rest
1090
+ * against PERMANENTFLAGS itself; REPLACE goes through `exec`, so it is done
1091
+ * here, or a keyword the folder does not allow could get the command refused.
1092
+ */
1093
+ function storableFlags(client, flags) {
1094
+ const permanent = client.mailbox ? client.mailbox.permanentFlags : undefined;
1095
+ if (!permanent || permanent.size === 0 || permanent.has("\\*"))
1096
+ return flags;
1097
+ const allowed = new Set([...permanent].map((flag) => flag.toLowerCase()));
1098
+ return flags.filter((flag) => allowed.has(flag.toLowerCase()));
1099
+ }
1100
+ /**
1101
+ * The UID of the message carrying `messageId` in the selected folder, or null.
1102
+ * `exclude` is the version being replaced; the highest remaining UID wins,
1103
+ * since a newer APPEND always takes a higher one.
1104
+ */
1105
+ async function findByMessageId(client, messageId, exclude) {
1106
+ const found = await client.search({ header: { "message-id": messageId } }, { uid: true });
1107
+ const candidates = (Array.isArray(found) ? found : []).filter((u) => u !== exclude);
1108
+ return candidates.length > 0 ? Math.max(...candidates) : null;
1109
+ }
891
1110
  //# sourceMappingURL=ImapService.js.map