imap-mcp 1.3.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +109 -6
- package/dist/access.js +6 -1
- package/dist/index.js +28 -1
- package/dist/index.test.js +62 -0
- package/dist/instructions.js +10 -2
- package/dist/instructions.test.js +10 -0
- package/dist/tools/archive-emails.js +55 -0
- package/dist/tools/archive-emails.test.js +154 -0
- package/dist/tools/batch.js +219 -0
- package/dist/tools/fake-imap.js +104 -10
- package/dist/tools/imap.js +32 -3
- package/dist/tools/list-unsubscribe.js +162 -0
- package/dist/tools/list-unsubscribe.test.js +129 -0
- package/dist/tools/mark-emails.js +131 -0
- package/dist/tools/mark-emails.test.js +124 -0
- package/dist/tools/move-emails.js +55 -0
- package/dist/tools/move-emails.test.js +169 -0
- package/dist/tools/one-click-post.js +276 -0
- package/dist/tools/one-click-post.test.js +219 -0
- package/dist/tools/trash-emails.js +37 -0
- package/dist/tools/trash-emails.test.js +73 -0
- package/dist/tools/unsubscribe-from-list.js +249 -0
- package/dist/tools/unsubscribe-from-list.test.js +251 -0
- package/package.json +1 -1
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// Shared plumbing for the tools that change mail (mark_emails,
|
|
2
|
+
// archive_emails, move_emails, trash_emails): the ids argument, finding where
|
|
3
|
+
// each id's message is, moving messages between folders, and the per-id
|
|
4
|
+
// result line. Shaped like langmail-mcp's file-emails-common.
|
|
5
|
+
import { z } from "zod/v4";
|
|
6
|
+
import { decodeMessageId, errorMessage, errorResult, examine, placeOf, searchUids, selectableFolders, textResult, uidRanges, } from "./imap.js";
|
|
7
|
+
const MAX_IDS = 50;
|
|
8
|
+
export const idsShape = {
|
|
9
|
+
ids: z
|
|
10
|
+
.array(z.string().min(1))
|
|
11
|
+
.min(1)
|
|
12
|
+
.max(MAX_IDS)
|
|
13
|
+
.describe(`Message ids to act on (1–${MAX_IDS}), as returned by search_emails or get_thread. ` +
|
|
14
|
+
"To act on a whole conversation, pass every id get_thread lists."),
|
|
15
|
+
};
|
|
16
|
+
/** Duplicates collapse, so one message never counts twice. */
|
|
17
|
+
export const uniqueIds = (ids) => [...new Set(ids)];
|
|
18
|
+
export const NOT_FOUND = "not found";
|
|
19
|
+
const NOT_AN_ID = "not a message id";
|
|
20
|
+
/**
|
|
21
|
+
* Finds every copy of each id's message: for a stable id one SEARCH per
|
|
22
|
+
* folder for all of them, for a UID id its folder, UIDVALIDITY and UID.
|
|
23
|
+
*/
|
|
24
|
+
export async function locateMessages(client, ids) {
|
|
25
|
+
const folders = await selectableFolders(client);
|
|
26
|
+
const locations = new Map();
|
|
27
|
+
const failed = [];
|
|
28
|
+
const add = (id, loc) => locations.set(id, [...(locations.get(id) ?? []), loc]);
|
|
29
|
+
const stable = new Map();
|
|
30
|
+
const byPath = new Map();
|
|
31
|
+
for (const id of ids) {
|
|
32
|
+
const ref = decodeMessageId(id);
|
|
33
|
+
if (!ref) {
|
|
34
|
+
failed.push({ id, status: "failed", reason: NOT_AN_ID });
|
|
35
|
+
}
|
|
36
|
+
else if (ref.kind === "stable") {
|
|
37
|
+
stable.set(ref.emailId, id);
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
byPath.set(ref.path, [...(byPath.get(ref.path) ?? []), { id, ...ref }]);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
for (const folder of folders) {
|
|
44
|
+
const wanted = byPath.get(folder.path) ?? [];
|
|
45
|
+
if (stable.size === 0 && wanted.length === 0)
|
|
46
|
+
continue;
|
|
47
|
+
const opened = await examine(client, folder.path);
|
|
48
|
+
if (!opened || opened.exists === 0)
|
|
49
|
+
continue;
|
|
50
|
+
if (stable.size > 0) {
|
|
51
|
+
const emailIds = [...stable.keys()];
|
|
52
|
+
const uids = await searchUids(client, emailIds.length === 1
|
|
53
|
+
? { emailId: emailIds[0] }
|
|
54
|
+
: { or: emailIds.map((emailId) => ({ emailId })) }, folder.path);
|
|
55
|
+
if (uids.length > 0) {
|
|
56
|
+
for await (const msg of client.fetch(uidRanges(uids), { uid: true, emailId: true }, { uid: true })) {
|
|
57
|
+
const id = msg.emailId ? stable.get(msg.emailId) : undefined;
|
|
58
|
+
if (id)
|
|
59
|
+
add(id, { folder, uid: msg.uid });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const current = wanted.filter((w) => w.uidValidity === opened.uidValidity.toString());
|
|
64
|
+
if (current.length > 0) {
|
|
65
|
+
const present = new Set(await searchUids(client, { uid: uidRanges(current.map((w) => w.uid)) }, folder.path));
|
|
66
|
+
for (const w of current) {
|
|
67
|
+
if (present.has(w.uid))
|
|
68
|
+
add(w.id, { folder, uid: w.uid });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const id of ids) {
|
|
73
|
+
if (!locations.has(id) && !failed.some((f) => f.id === id)) {
|
|
74
|
+
failed.push({ id, status: "failed", reason: NOT_FOUND });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { folders, locations, failed };
|
|
78
|
+
}
|
|
79
|
+
/** The ids whose copies are listed, grouped by folder path. */
|
|
80
|
+
export function byFolder(copies) {
|
|
81
|
+
const out = new Map();
|
|
82
|
+
for (const { id, loc } of copies) {
|
|
83
|
+
out.set(loc.folder.path, [
|
|
84
|
+
...(out.get(loc.folder.path) ?? []),
|
|
85
|
+
{ id, uid: loc.uid },
|
|
86
|
+
]);
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/** Gmail's All Mail: every message that is not in Spam or Trash. */
|
|
91
|
+
export const isAllMail = (folder) => folder.specialUse?.toLowerCase() === "\\all";
|
|
92
|
+
/**
|
|
93
|
+
* A folder that shows messages by a flag (Gmail's Starred and Important):
|
|
94
|
+
* moving a message out of it clears the flag, so it is never a source.
|
|
95
|
+
*/
|
|
96
|
+
const isFlagView = (folder) => ["\\flagged", "\\important"].includes(folder.specialUse?.toLowerCase() ?? "");
|
|
97
|
+
/**
|
|
98
|
+
* Moves each listed copy into `destination`, folder by folder, with UID
|
|
99
|
+
* MOVE. Without MOVE (RFC 6851), imapflow copies, flags `\Deleted` and
|
|
100
|
+
* expunges: by UID with UIDPLUS (RFC 4315), else with a plain EXPUNGE that
|
|
101
|
+
* would take every `\Deleted` message, so then a folder holding others is
|
|
102
|
+
* left alone. Returns the ids moved and the reason for each that failed.
|
|
103
|
+
*/
|
|
104
|
+
export async function moveCopies(client, copies, destination) {
|
|
105
|
+
// Gmail's All Mail holds every message that is not in Spam or Trash, and
|
|
106
|
+
// taking one out of it deletes it. COPY adds the destination label and
|
|
107
|
+
// leaves it there; only into Trash does it leave All Mail.
|
|
108
|
+
const copyFrom = new Set(copies.filter((c) => isAllMail(c.loc.folder)).map((c) => c.loc.folder.path));
|
|
109
|
+
const toTrash = placeOf(destination)?.name === "Trash";
|
|
110
|
+
const moved = new Set();
|
|
111
|
+
const failed = new Map();
|
|
112
|
+
const caps = client.capabilities;
|
|
113
|
+
const plainExpunge = !caps.has("MOVE") && !caps.has("UIDPLUS");
|
|
114
|
+
for (const [path, entries] of byFolder(copies)) {
|
|
115
|
+
const uids = entries.map((e) => e.uid);
|
|
116
|
+
const fail = (reason) => entries.forEach((e) => failed.set(e.id, reason));
|
|
117
|
+
try {
|
|
118
|
+
await client.mailboxOpen(path);
|
|
119
|
+
if (copyFrom.has(path) && !toTrash) {
|
|
120
|
+
if (!(await client.messageCopy(uidRanges(uids), destination.path, {
|
|
121
|
+
uid: true,
|
|
122
|
+
}))) {
|
|
123
|
+
fail(`the server refused the copy out of ${path}`);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
entries.forEach((e) => moved.add(e.id));
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (plainExpunge) {
|
|
130
|
+
const deleted = await searchUids(client, { deleted: true }, path);
|
|
131
|
+
if (deleted.some((uid) => !uids.includes(uid))) {
|
|
132
|
+
fail(`the server cannot move without expunging the other deleted messages in ${path}`);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const result = await client.messageMove(uidRanges(uids), destination.path, {
|
|
137
|
+
uid: true,
|
|
138
|
+
});
|
|
139
|
+
if (!result) {
|
|
140
|
+
fail(`the server refused the move out of ${path}`);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
entries.forEach((e) => moved.add(e.id));
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
fail(errorMessage(err));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return { moved, failed };
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Turns per-copy results into one outcome per id: changed when any copy
|
|
153
|
+
* changed, failed when none did and one failed, otherwise already in place.
|
|
154
|
+
*/
|
|
155
|
+
export function outcomesOf(ids, changed, failed) {
|
|
156
|
+
return ids.map((id) => {
|
|
157
|
+
if (changed.has(id))
|
|
158
|
+
return { id, status: "changed" };
|
|
159
|
+
const reason = failed.get(id);
|
|
160
|
+
if (reason !== undefined)
|
|
161
|
+
return { id, status: "failed", reason };
|
|
162
|
+
return { id, status: "already" };
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* langmail-mcp's result line, "Archived 2 message(s).", plus how many were
|
|
167
|
+
* already in place and each id not updated with the reason. An error only
|
|
168
|
+
* when nothing changed and an id was refused: an id whose message is gone or
|
|
169
|
+
* has moved is listed, not an error for the whole call.
|
|
170
|
+
*/
|
|
171
|
+
export function formatBatchResult(verb, outcomes, opts) {
|
|
172
|
+
const changed = outcomes.filter((o) => o.status === "changed").length;
|
|
173
|
+
const already = outcomes.filter((o) => o.status === "already").length;
|
|
174
|
+
const failed = outcomes.flatMap((o) => (o.status === "failed" ? [o] : []));
|
|
175
|
+
let text = `${verb} ${changed} message(s)${opts.suffix ?? ""}.`;
|
|
176
|
+
if (already > 0)
|
|
177
|
+
text += ` ${already} message(s) ${opts.already}.`;
|
|
178
|
+
if (failed.length === 0)
|
|
179
|
+
return textResult(text);
|
|
180
|
+
text += ` Not updated (${failed.length}): ${failed.map((f) => `${f.id} (${f.reason})`).join(", ")}.`;
|
|
181
|
+
if (failed.some((f) => f.reason === NOT_FOUND || f.reason === NOT_AN_ID)) {
|
|
182
|
+
text += " Re-run search_emails or get_thread for current ids.";
|
|
183
|
+
}
|
|
184
|
+
const refused = failed.some((f) => f.reason !== NOT_FOUND);
|
|
185
|
+
return changed === 0 && already === 0 && refused
|
|
186
|
+
? errorResult(text)
|
|
187
|
+
: textResult(text);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Moves every id's message into `destination` from the copies `sourcesOf`
|
|
191
|
+
* picks; an id with no copy to move is already in place. Outcomes come back
|
|
192
|
+
* in the order of `ids`.
|
|
193
|
+
*/
|
|
194
|
+
export async function fileMessages(client, ids, located, destination, sourcesOf) {
|
|
195
|
+
const copies = [...located.locations].flatMap(([id, locs]) => sourcesOf(locs).map((loc) => ({ id, loc })));
|
|
196
|
+
const { moved, failed } = await moveCopies(client, copies, destination);
|
|
197
|
+
const outcomes = new Map([
|
|
198
|
+
...outcomesOf([...located.locations.keys()], moved, failed).map((o) => [o.id, o]),
|
|
199
|
+
...located.failed.map((o) => [o.id, o]),
|
|
200
|
+
]);
|
|
201
|
+
return ids.flatMap((id) => outcomes.get(id) ?? []);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Every copy outside `destination`, flag views left out. On Gmail, All Mail follows the other
|
|
205
|
+
* folders (labels), so it is a source only when the message is in no other
|
|
206
|
+
* folder, the destination included.
|
|
207
|
+
*/
|
|
208
|
+
export function copiesOutside(destination) {
|
|
209
|
+
return (locations) => {
|
|
210
|
+
const others = locations.filter((l) => l.folder.path !== destination.path && !isFlagView(l.folder));
|
|
211
|
+
const labelled = others.filter((l) => !isAllMail(l.folder));
|
|
212
|
+
if (labelled.length > 0)
|
|
213
|
+
return labelled;
|
|
214
|
+
// Already in the destination, and in All Mail only because of it.
|
|
215
|
+
if (locations.some((l) => l.folder.path === destination.path))
|
|
216
|
+
return [];
|
|
217
|
+
return others;
|
|
218
|
+
};
|
|
219
|
+
}
|
package/dist/tools/fake-imap.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
// An in-memory stand-in for ImapFlow, for the
|
|
2
|
-
//
|
|
3
|
-
// A message with `
|
|
1
|
+
// An in-memory stand-in for ImapFlow, for the tools' tests: folders holding
|
|
2
|
+
// messages, and the SEARCH, FETCH, STORE and MOVE subset the tools use.
|
|
3
|
+
// A message with `emailId` behaves as on a server with OBJECTID or Gmail.
|
|
4
|
+
// Without MOVE in `capabilities`, a move is imapflow's fallback: COPY,
|
|
5
|
+
// \Deleted, then UID EXPUNGE with UIDPLUS or else a plain EXPUNGE.
|
|
4
6
|
import { vi } from "vitest";
|
|
5
7
|
const DAY = (d) => new Date(d).toISOString().slice(0, 10);
|
|
6
8
|
function header(m, name) {
|
|
@@ -24,7 +26,11 @@ function matches(m, q) {
|
|
|
24
26
|
}
|
|
25
27
|
if (q.threadId && m.threadId !== q.threadId)
|
|
26
28
|
return false;
|
|
29
|
+
if (q.uid && !parseRanges(String(q.uid)).includes(m.uid))
|
|
30
|
+
return false;
|
|
27
31
|
const flags = new Set(m.flags ?? []);
|
|
32
|
+
if (q.deleted !== undefined && flags.has("\\Deleted") !== q.deleted)
|
|
33
|
+
return false;
|
|
28
34
|
if (q.seen !== undefined && flags.has("\\Seen") !== q.seen)
|
|
29
35
|
return false;
|
|
30
36
|
if (q.flagged !== undefined && flags.has("\\Flagged") !== q.flagged)
|
|
@@ -55,17 +61,36 @@ function parseRanges(range) {
|
|
|
55
61
|
return Array.from({ length: b - a + 1 }, (_, i) => a + i);
|
|
56
62
|
});
|
|
57
63
|
}
|
|
58
|
-
export function fakeClient(folders) {
|
|
64
|
+
export function fakeClient(folders, capabilities = ["MOVE", "UIDPLUS", "OBJECTID"]) {
|
|
59
65
|
let open;
|
|
66
|
+
const commands = [];
|
|
67
|
+
const setFlags = (range, change) => {
|
|
68
|
+
for (const uid of parseRanges(range)) {
|
|
69
|
+
const m = find(uid);
|
|
70
|
+
if (!m)
|
|
71
|
+
continue;
|
|
72
|
+
const flags = new Set(m.flags ?? []);
|
|
73
|
+
change(flags);
|
|
74
|
+
m.flags = [...flags];
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const expunge = (uids) => {
|
|
78
|
+
if (!open)
|
|
79
|
+
return;
|
|
80
|
+
open.messages = open.messages.filter((m) => !(m.flags ?? []).includes("\\Deleted") ||
|
|
81
|
+
(uids !== undefined && !uids.includes(m.uid)));
|
|
82
|
+
};
|
|
60
83
|
const find = (uid) => open?.messages.find((m) => m.uid === uid);
|
|
61
84
|
const toFetched = (m) => ({
|
|
62
85
|
seq: m.uid,
|
|
63
86
|
uid: m.uid,
|
|
64
87
|
emailId: m.emailId,
|
|
65
88
|
threadId: m.threadId,
|
|
66
|
-
headers: m.
|
|
67
|
-
? Buffer.from(
|
|
68
|
-
:
|
|
89
|
+
headers: m.headers !== undefined
|
|
90
|
+
? Buffer.from(m.headers)
|
|
91
|
+
: m.references === undefined
|
|
92
|
+
? Buffer.from("\r\n")
|
|
93
|
+
: Buffer.from(`References: ${m.references}\r\n\r\n`),
|
|
69
94
|
internalDate: new Date(m.date),
|
|
70
95
|
flags: new Set(m.flags ?? []),
|
|
71
96
|
size: m.size ?? (m.source ?? "").length,
|
|
@@ -80,6 +105,8 @@ export function fakeClient(folders) {
|
|
|
80
105
|
source: m.source === undefined ? undefined : Buffer.from(m.source),
|
|
81
106
|
});
|
|
82
107
|
const client = {
|
|
108
|
+
capabilities: new Map(capabilities.map((c) => [c, true])),
|
|
109
|
+
commands,
|
|
83
110
|
on: vi.fn(),
|
|
84
111
|
connect: vi.fn(async () => { }),
|
|
85
112
|
logout: vi.fn(async () => { }),
|
|
@@ -108,9 +135,73 @@ export function fakeClient(folders) {
|
|
|
108
135
|
readOnly: opts?.readOnly,
|
|
109
136
|
uidValidity: BigInt(open.uidValidity ?? 1),
|
|
110
137
|
exists: open.messages.length,
|
|
138
|
+
permanentFlags: opts?.readOnly || !open.permanentFlags
|
|
139
|
+
? undefined
|
|
140
|
+
: new Set(open.permanentFlags),
|
|
111
141
|
};
|
|
112
142
|
}),
|
|
113
|
-
|
|
143
|
+
messageFlagsAdd: vi.fn(async (range, flags) => {
|
|
144
|
+
if (open?.refuseWrites)
|
|
145
|
+
return false;
|
|
146
|
+
commands.push(`STORE ${open?.path} ${range} +${flags.join(" ")}`);
|
|
147
|
+
setFlags(range, (set) => flags.forEach((f) => set.add(f)));
|
|
148
|
+
return true;
|
|
149
|
+
}),
|
|
150
|
+
messageFlagsRemove: vi.fn(async (range, flags) => {
|
|
151
|
+
if (open?.refuseWrites)
|
|
152
|
+
return false;
|
|
153
|
+
commands.push(`STORE ${open?.path} ${range} -${flags.join(" ")}`);
|
|
154
|
+
setFlags(range, (set) => flags.forEach((f) => set.delete(f)));
|
|
155
|
+
return true;
|
|
156
|
+
}),
|
|
157
|
+
messageCopy: vi.fn(async (range, destination) => {
|
|
158
|
+
const dest = folders.find((f) => f.path === destination);
|
|
159
|
+
if (!open || !dest || open.refuseWrites)
|
|
160
|
+
return false;
|
|
161
|
+
commands.push(`COPY ${open.path} ${range} ${destination}`);
|
|
162
|
+
const uids = parseRanges(range);
|
|
163
|
+
let next = Math.max(0, ...dest.messages.map((m) => m.uid)) + 1;
|
|
164
|
+
dest.messages.push(...open.messages
|
|
165
|
+
.filter((m) => uids.includes(m.uid))
|
|
166
|
+
.map((m) => ({ ...m, flags: [...(m.flags ?? [])], uid: next++ })));
|
|
167
|
+
return { path: open.path, destination };
|
|
168
|
+
}),
|
|
169
|
+
messageMove: vi.fn(async (range, destination) => {
|
|
170
|
+
const source = open;
|
|
171
|
+
const dest = folders.find((f) => f.path === destination);
|
|
172
|
+
if (!source || !dest || source.refuseWrites)
|
|
173
|
+
return false;
|
|
174
|
+
const uids = parseRanges(range);
|
|
175
|
+
const moving = source.messages.filter((m) => uids.includes(m.uid));
|
|
176
|
+
let next = Math.max(0, ...dest.messages.map((m) => m.uid)) + 1;
|
|
177
|
+
dest.messages.push(...moving.map((m) => ({
|
|
178
|
+
...m,
|
|
179
|
+
flags: [...(m.flags ?? [])],
|
|
180
|
+
uid: next++,
|
|
181
|
+
})));
|
|
182
|
+
if (capabilities.includes("MOVE")) {
|
|
183
|
+
commands.push(`MOVE ${source.path} ${range} ${destination}`);
|
|
184
|
+
source.messages = source.messages.filter((m) => !uids.includes(m.uid));
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
commands.push(`COPY ${source.path} ${range} ${destination}`);
|
|
188
|
+
setFlags(range, (set) => set.add("\\Deleted"));
|
|
189
|
+
const byUid = capabilities.includes("UIDPLUS");
|
|
190
|
+
commands.push(`${byUid ? "UID EXPUNGE" : "EXPUNGE"} ${source.path}`);
|
|
191
|
+
expunge(byUid ? uids : undefined);
|
|
192
|
+
}
|
|
193
|
+
return { path: source.path, destination };
|
|
194
|
+
}),
|
|
195
|
+
search: vi.fn(async (q) => {
|
|
196
|
+
// imapflow refuses EMAILID without OBJECTID or Gmail's extension.
|
|
197
|
+
const stable = ["OBJECTID", "X-GM-EXT-1"].some((c) => capabilities.includes(c));
|
|
198
|
+
if (JSON.stringify(q).includes('"emailId"') && !stable) {
|
|
199
|
+
throw new Error("Missing server extension");
|
|
200
|
+
}
|
|
201
|
+
return (open?.messages ?? [])
|
|
202
|
+
.filter((m) => matches(m, q))
|
|
203
|
+
.map((m) => m.uid);
|
|
204
|
+
}),
|
|
114
205
|
fetch: vi.fn(async function* (range) {
|
|
115
206
|
for (const uid of parseRanges(range)) {
|
|
116
207
|
const m = find(uid);
|
|
@@ -123,14 +214,17 @@ export function fakeClient(folders) {
|
|
|
123
214
|
const m = find(Number(uid));
|
|
124
215
|
return m ? toFetched(m) : false;
|
|
125
216
|
}),
|
|
126
|
-
download: vi.fn(async (uid) => {
|
|
217
|
+
download: vi.fn(async (uid, part, opts) => {
|
|
218
|
+
// Without uid: true imapflow reads the range as a sequence number.
|
|
219
|
+
if (!opts?.uid)
|
|
220
|
+
throw new Error("download without uid: true");
|
|
127
221
|
const m = find(Number(uid));
|
|
128
222
|
if (!m)
|
|
129
223
|
return {};
|
|
130
224
|
return {
|
|
131
225
|
meta: {},
|
|
132
226
|
content: (async function* () {
|
|
133
|
-
yield Buffer.from(m.text ?? "");
|
|
227
|
+
yield Buffer.from((part && m.parts?.[part]) ?? m.text ?? "");
|
|
134
228
|
})(),
|
|
135
229
|
};
|
|
136
230
|
}),
|
package/dist/tools/imap.js
CHANGED
|
@@ -9,6 +9,31 @@ export const READ_ONLY = {
|
|
|
9
9
|
openWorldHint: false,
|
|
10
10
|
readOnlyHint: true,
|
|
11
11
|
};
|
|
12
|
+
/** Writes inside the user's own mailbox that the user can undo: langmail-mcp's ACCOUNT_WRITE. */
|
|
13
|
+
export const ACCOUNT_WRITE = {
|
|
14
|
+
destructiveHint: false,
|
|
15
|
+
idempotentHint: false,
|
|
16
|
+
openWorldHint: false,
|
|
17
|
+
readOnlyHint: false,
|
|
18
|
+
};
|
|
19
|
+
/** Removes something from the user's mailbox: langmail-mcp's ACCOUNT_DESTRUCTIVE. */
|
|
20
|
+
export const ACCOUNT_DESTRUCTIVE = {
|
|
21
|
+
destructiveHint: true,
|
|
22
|
+
idempotentHint: false,
|
|
23
|
+
openWorldHint: false,
|
|
24
|
+
readOnlyHint: false,
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Annotations of a tool that reaches someone outside the mailbox and cannot
|
|
28
|
+
* be taken back, such as an unsubscribe request (langmail-mcp's
|
|
29
|
+
* OUTWARD_DESTRUCTIVE).
|
|
30
|
+
*/
|
|
31
|
+
export const OUTWARD_DESTRUCTIVE = {
|
|
32
|
+
destructiveHint: true,
|
|
33
|
+
idempotentHint: false,
|
|
34
|
+
openWorldHint: true,
|
|
35
|
+
readOnlyHint: false,
|
|
36
|
+
};
|
|
12
37
|
export const textResult = (text) => ({
|
|
13
38
|
content: [{ type: "text", text }],
|
|
14
39
|
});
|
|
@@ -63,7 +88,7 @@ export async function selectableFolders(client) {
|
|
|
63
88
|
const folders = await client.list();
|
|
64
89
|
return folders.filter((f) => ![...f.flags].some((flag) => ["\\noselect", "\\nonexistent"].includes(flag.toLowerCase())));
|
|
65
90
|
}
|
|
66
|
-
function placeOf(folder) {
|
|
91
|
+
export function placeOf(folder) {
|
|
67
92
|
const specialUse = folder.path.toUpperCase() === "INBOX"
|
|
68
93
|
? "\\Inbox"
|
|
69
94
|
: folder.specialUse?.toLowerCase();
|
|
@@ -87,7 +112,7 @@ export function sortFolderLabels(labels) {
|
|
|
87
112
|
* special-use attribute (RFC 6154), anything else to the folder with exactly
|
|
88
113
|
* that path or name. Never creates a folder.
|
|
89
114
|
*/
|
|
90
|
-
export function resolveMailbox(folders, name) {
|
|
115
|
+
export function resolveMailbox(folders, name, nothing = "Nothing was searched.") {
|
|
91
116
|
const place = PLACES.find((p) => p.name.toLowerCase() === name.toLowerCase());
|
|
92
117
|
const found = (place && folders.find((f) => placeOf(f) === place)) ||
|
|
93
118
|
folders.find((f) => f.path === name) ||
|
|
@@ -95,7 +120,11 @@ export function resolveMailbox(folders, name) {
|
|
|
95
120
|
if (found)
|
|
96
121
|
return found;
|
|
97
122
|
const available = sortFolderLabels(folders.map(folderLabel));
|
|
98
|
-
return errorResult(`Mailbox not found: ${name}.
|
|
123
|
+
return errorResult(`Mailbox not found: ${name}. ${nothing} Available folders: ${available.join(", ")}.`);
|
|
124
|
+
}
|
|
125
|
+
/** The folder holding a standard place, such as Archive or Trash, if any. */
|
|
126
|
+
export function findPlace(folders, name) {
|
|
127
|
+
return folders.find((f) => placeOf(f)?.name === name);
|
|
99
128
|
}
|
|
100
129
|
/**
|
|
101
130
|
* A UID set as IMAP ranges ("1:3,7"), so a FETCH for thousands of hits stays
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// RFC 5322 §2.2.3: a folded header is a CRLF followed by whitespace; unfolding
|
|
2
|
+
// removes the CRLF. Bare LF is tolerated because not every store normalises.
|
|
3
|
+
const FOLD_RE = /\r?\n(?=[ \t])/gu;
|
|
4
|
+
const ANGLE_ENTRY_RE = /<([^>]*)>/gu;
|
|
5
|
+
const WHITESPACE_RE = /\s+/gu;
|
|
6
|
+
export const unfoldHeader = (raw) => raw.replaceAll(FOLD_RE, "");
|
|
7
|
+
// The header block imapflow returns for a `headers` fetch: every field's
|
|
8
|
+
// value (unfolded, still raw), by lower-cased name, in the message's order.
|
|
9
|
+
export const parseHeaderBlock = (block) => {
|
|
10
|
+
const fields = new Map();
|
|
11
|
+
for (const line of unfoldHeader(block).split(/\r?\n/u)) {
|
|
12
|
+
const colon = line.indexOf(":");
|
|
13
|
+
if (colon <= 0) {
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
const name = line.slice(0, colon).trim().toLowerCase();
|
|
17
|
+
fields.set(name, [...(fields.get(name) ?? []), line.slice(colon + 1)]);
|
|
18
|
+
}
|
|
19
|
+
return fields;
|
|
20
|
+
};
|
|
21
|
+
// Sender text that ends up in the tool result: one line, so a `%0A` in a
|
|
22
|
+
// mailto subject cannot forge a line of the result.
|
|
23
|
+
const oneLine = (text) => text.replaceAll(WHITESPACE_RE, " ").trim();
|
|
24
|
+
// RFC 6068: `+` in a mailto query is a literal plus, not a space, so the
|
|
25
|
+
// pairs are percent-decoded by hand rather than through URLSearchParams.
|
|
26
|
+
const mailtoField = (query, name) => {
|
|
27
|
+
for (const pair of query.split("&")) {
|
|
28
|
+
const eq = pair.indexOf("=");
|
|
29
|
+
if (eq > 0 && pair.slice(0, eq).toLowerCase() === name) {
|
|
30
|
+
const value = oneLine(decodeURIComponent(pair.slice(eq + 1)));
|
|
31
|
+
return value || undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return undefined;
|
|
35
|
+
};
|
|
36
|
+
const parseMailto = (uri) => {
|
|
37
|
+
try {
|
|
38
|
+
const rest = uri.slice("mailto:".length);
|
|
39
|
+
const q = rest.indexOf("?");
|
|
40
|
+
const address = oneLine(decodeURIComponent(q === -1 ? rest : rest.slice(0, q)));
|
|
41
|
+
if (!address) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
const query = q === -1 ? "" : rest.slice(q + 1);
|
|
45
|
+
const subject = mailtoField(query, "subject");
|
|
46
|
+
const body = mailtoField(query, "body");
|
|
47
|
+
return {
|
|
48
|
+
address,
|
|
49
|
+
...(subject ? { subject } : {}),
|
|
50
|
+
...(body ? { body } : {}),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// A malformed percent-escape: skip this entry, keep the others.
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
// RFC 2369 §2: the value is a comma-separated list of `<uri>` entries; a
|
|
59
|
+
// folded line may split it anywhere, and whitespace inside the angle brackets
|
|
60
|
+
// is to be ignored.
|
|
61
|
+
export const parseListUnsubscribe = (raw, post) => {
|
|
62
|
+
const result = {
|
|
63
|
+
http: [],
|
|
64
|
+
https: [],
|
|
65
|
+
mailto: [],
|
|
66
|
+
oneClick: false,
|
|
67
|
+
};
|
|
68
|
+
if (!raw) {
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
for (const match of unfoldHeader(raw).matchAll(ANGLE_ENTRY_RE)) {
|
|
72
|
+
const uri = (match[1] ?? "").replaceAll(WHITESPACE_RE, "");
|
|
73
|
+
const scheme = uri.slice(0, uri.indexOf(":") + 1).toLowerCase();
|
|
74
|
+
if (scheme === "https:") {
|
|
75
|
+
result.https.push(uri);
|
|
76
|
+
}
|
|
77
|
+
else if (scheme === "http:") {
|
|
78
|
+
result.http.push(uri);
|
|
79
|
+
}
|
|
80
|
+
else if (scheme === "mailto:") {
|
|
81
|
+
const target = parseMailto(uri);
|
|
82
|
+
if (target) {
|
|
83
|
+
result.mailto.push(target);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
result.oneClick = result.https.length > 0 && isOneClickPost(post);
|
|
88
|
+
return result;
|
|
89
|
+
};
|
|
90
|
+
// RFC 8058 §3.1: the Post header must contain exactly the key/value pair
|
|
91
|
+
// `List-Unsubscribe=One-Click`.
|
|
92
|
+
const POST_PAIR_SEPARATOR_RE = /[;&,]/u;
|
|
93
|
+
const isOneClickPost = (post) => (post ?? "")
|
|
94
|
+
.split(POST_PAIR_SEPARATOR_RE)
|
|
95
|
+
.some((pair) => pair.replaceAll(WHITESPACE_RE, "").toLowerCase() ===
|
|
96
|
+
"list-unsubscribe=one-click");
|
|
97
|
+
// What the URL says about how much it covers. Only the strong signal is named:
|
|
98
|
+
// the field test's publisher footer said "this mailing list" while the header
|
|
99
|
+
// link was `unsubscribe-all`.
|
|
100
|
+
const ALL_SCOPE_RE = /(?:unsub(?:scribe)?|opt-?out)[-_]?all|all[-_]?(?:unsub(?:scribe)?|opt-?out)/iu;
|
|
101
|
+
export const scopeNote = (url) => {
|
|
102
|
+
let parsed;
|
|
103
|
+
try {
|
|
104
|
+
parsed = new URL(url);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
if (ALL_SCOPE_RE.test(`${parsed.pathname}${parsed.search}`)) {
|
|
110
|
+
return 'The link looks like "unsubscribe from all": it may stop all marketing mail from this sender, not just this list.';
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
};
|
|
114
|
+
// The host and path only: the query string carries the sender's tracking
|
|
115
|
+
// token and tells the user nothing.
|
|
116
|
+
export const describeUrl = (url) => {
|
|
117
|
+
try {
|
|
118
|
+
const parsed = new URL(url);
|
|
119
|
+
return `${parsed.host}${parsed.pathname}`;
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return url;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
// A URL in the message's text that names itself an unsubscribe or opt-out
|
|
126
|
+
// link. The texts are the decoded text/plain and text/html parts, so both
|
|
127
|
+
// plain URLs and href targets are found. A tracking redirect whose URL does
|
|
128
|
+
// not say "unsubscribe" is missed, which reports "no link found" rather than
|
|
129
|
+
// guessing.
|
|
130
|
+
const URL_RE = /https?:\/\/[^\s"'<>()]+/giu;
|
|
131
|
+
const FOOTER_HINT_RE = /unsub|opt-?out|optout/iu;
|
|
132
|
+
const HTML_AMP_RE = /&/gu;
|
|
133
|
+
export const footerLink = (texts) => {
|
|
134
|
+
for (const text of texts) {
|
|
135
|
+
for (const match of text.matchAll(URL_RE)) {
|
|
136
|
+
if (FOOTER_HINT_RE.test(match[0])) {
|
|
137
|
+
return match[0].replaceAll(HTML_AMP_RE, "&");
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
};
|
|
143
|
+
const ADDRESS_RE = /^[^\s@<>]+@[^\s@<>]+$/u;
|
|
144
|
+
// Delivered-To headers are prepended at each delivery hop, so the first one
|
|
145
|
+
// is the user's own mailbox; forwarded mail carries older hops below it.
|
|
146
|
+
export const deliveredTo = (deliveredToValues, to) => {
|
|
147
|
+
// The receiving server writes it, but a server that doesn't leaves the
|
|
148
|
+
// sender's own value first: name it only when it looks like an address.
|
|
149
|
+
const first = deliveredToValues.find((v) => v.trim())?.trim();
|
|
150
|
+
if (first) {
|
|
151
|
+
return ADDRESS_RE.test(first) ? first : null;
|
|
152
|
+
}
|
|
153
|
+
// Without the header, a single To recipient is the best guess; a list of
|
|
154
|
+
// them would name other people's addresses as the user's.
|
|
155
|
+
const recipients = to.filter(Boolean);
|
|
156
|
+
return recipients.length === 1 ? (recipients[0] ?? null) : null;
|
|
157
|
+
};
|
|
158
|
+
export const formatMailto = (m) => [
|
|
159
|
+
` To: ${m.address}`,
|
|
160
|
+
...(m.subject ? [` Subject: ${m.subject}`] : []),
|
|
161
|
+
...(m.body ? [` Body: ${m.body}`] : []),
|
|
162
|
+
].join("\n");
|