mcp-google-multi 5.4.1-alpha.2 → 6.0.0-alpha.2

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.
Files changed (116) hide show
  1. package/README.md +21 -16
  2. package/dist/accounts.d.ts +44 -5
  3. package/dist/accounts.js +267 -25
  4. package/dist/auth.d.ts +11 -4
  5. package/dist/auth.js +85 -78
  6. package/dist/client-config.d.ts +90 -0
  7. package/dist/client-config.js +282 -0
  8. package/dist/client.js +10 -4
  9. package/dist/config-file.d.ts +38 -0
  10. package/dist/config-file.js +117 -0
  11. package/dist/discover.js +57 -3
  12. package/dist/doctor.d.ts +86 -0
  13. package/dist/doctor.js +384 -0
  14. package/dist/env-load.d.ts +11 -0
  15. package/dist/env-load.js +52 -0
  16. package/dist/executor.d.ts +2 -0
  17. package/dist/executor.js +2 -1
  18. package/dist/fanout.js +8 -5
  19. package/dist/fs-atomic.d.ts +3 -0
  20. package/dist/fs-atomic.js +123 -0
  21. package/dist/http-config.d.ts +35 -0
  22. package/dist/http-config.js +113 -0
  23. package/dist/http-transport.d.ts +59 -0
  24. package/dist/http-transport.js +269 -0
  25. package/dist/identity.d.ts +24 -0
  26. package/dist/identity.js +19 -0
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +199 -18
  29. package/dist/master-key.d.ts +53 -0
  30. package/dist/master-key.js +242 -0
  31. package/dist/mcp-token.d.ts +81 -0
  32. package/dist/mcp-token.js +176 -0
  33. package/dist/migrate-config.d.ts +7 -0
  34. package/dist/migrate-config.js +103 -0
  35. package/dist/migrate-tokens.js +4 -3
  36. package/dist/net-tuning.d.ts +8 -0
  37. package/dist/net-tuning.js +25 -0
  38. package/dist/oauth-as.d.ts +52 -0
  39. package/dist/oauth-as.js +457 -0
  40. package/dist/oauth-consent.d.ts +28 -0
  41. package/dist/oauth-consent.js +109 -0
  42. package/dist/open-url.d.ts +1 -0
  43. package/dist/open-url.js +30 -0
  44. package/dist/reauth-hint.d.ts +2 -0
  45. package/dist/reauth-hint.js +15 -0
  46. package/dist/registry-transfer.d.ts +41 -0
  47. package/dist/registry-transfer.js +219 -0
  48. package/dist/registry.d.ts +27 -1
  49. package/dist/registry.js +117 -6
  50. package/dist/scope-catalog.d.ts +19 -0
  51. package/dist/scope-catalog.js +182 -0
  52. package/dist/scope-observability.d.ts +78 -0
  53. package/dist/scope-observability.js +192 -0
  54. package/dist/services.js +1 -1
  55. package/dist/setup-prompt.d.ts +9 -0
  56. package/dist/setup-prompt.js +59 -0
  57. package/dist/ssrf-guard.d.ts +48 -0
  58. package/dist/ssrf-guard.js +242 -0
  59. package/dist/token-store.js +23 -125
  60. package/dist/tools/_errors.d.ts +8 -2
  61. package/dist/tools/_errors.js +97 -6
  62. package/dist/tools/account-wizard.d.ts +33 -0
  63. package/dist/tools/account-wizard.js +284 -0
  64. package/dist/tools/accounts-tool.d.ts +8 -5
  65. package/dist/tools/accounts-tool.js +38 -15
  66. package/dist/tools/admin.js +2 -2
  67. package/dist/tools/calendar.js +2 -2
  68. package/dist/tools/chat.js +2 -2
  69. package/dist/tools/contacts.d.ts +40 -0
  70. package/dist/tools/contacts.js +135 -2
  71. package/dist/tools/docs.d.ts +3 -0
  72. package/dist/tools/docs.js +60 -9
  73. package/dist/tools/drive.d.ts +3 -0
  74. package/dist/tools/drive.js +60 -8
  75. package/dist/tools/forms.js +4 -2
  76. package/dist/tools/generated/_shared.d.ts +1 -3
  77. package/dist/tools/generated/_shared.js +3 -3
  78. package/dist/tools/generated/admin.js +175 -132
  79. package/dist/tools/generated/appsmarket.js +6 -2
  80. package/dist/tools/generated/calendar.js +45 -27
  81. package/dist/tools/generated/chat.js +81 -47
  82. package/dist/tools/generated/classroom.js +131 -104
  83. package/dist/tools/generated/cloudidentity.js +73 -61
  84. package/dist/tools/generated/cloudsearch.js +59 -49
  85. package/dist/tools/generated/contacts.js +22 -14
  86. package/dist/tools/generated/drive.js +51 -35
  87. package/dist/tools/generated/driveactivity.js +5 -1
  88. package/dist/tools/generated/drivelabels.js +30 -25
  89. package/dist/tools/generated/forms.js +7 -3
  90. package/dist/tools/generated/gmail.js +73 -58
  91. package/dist/tools/generated/groupsmigration.js +5 -1
  92. package/dist/tools/generated/groupssettings.js +7 -3
  93. package/dist/tools/generated/keep.js +12 -7
  94. package/dist/tools/generated/licensing.js +11 -7
  95. package/dist/tools/generated/meet.js +20 -13
  96. package/dist/tools/generated/postmaster.js +8 -4
  97. package/dist/tools/generated/reseller.js +22 -17
  98. package/dist/tools/generated/script.js +26 -16
  99. package/dist/tools/generated/sheets.js +11 -7
  100. package/dist/tools/generated/tasks.js +6 -2
  101. package/dist/tools/generated/vault.js +38 -33
  102. package/dist/tools/generated/workspaceevents.js +12 -7
  103. package/dist/tools/gmail-mime.d.ts +38 -8
  104. package/dist/tools/gmail-mime.js +75 -71
  105. package/dist/tools/gmail.d.ts +31 -0
  106. package/dist/tools/gmail.js +483 -99
  107. package/dist/tools/google-api.js +7 -4
  108. package/dist/tools/meet.js +2 -2
  109. package/dist/tools/searchconsole.js +2 -2
  110. package/dist/tools/sheets.js +6 -2
  111. package/dist/tools/slides.js +4 -2
  112. package/dist/tools/tasks.js +2 -2
  113. package/dist/types.d.ts +1 -1
  114. package/dist/write-control.d.ts +24 -1
  115. package/dist/write-control.js +26 -1
  116. package/package.json +26 -7
@@ -1,14 +1,18 @@
1
1
  import { z } from 'zod';
2
- import { coerceArray, coerceBoolean } from './_coerce.js';
2
+ import { coerceArray, coerceBoolean, coerceJson } from './_coerce.js';
3
3
  import { gmail as gmailClient } from '@googleapis/gmail';
4
- import { ACCOUNTS } from '../accounts.js';
4
+ import { accountAliasSchema } from '../accounts.js';
5
5
  import { getClient } from '../client.js';
6
- import { handleGoogleApiError } from './_errors.js';
7
- import { buildMultipartAlternative, buildReplyHeaders, encodeAddressHeader, encodeHeaderValue, htmlToText, normalizeBodyLineEndings } from './gmail-mime.js';
6
+ import { handleGoogleApiError, mapGoogleError } from './_errors.js';
7
+ import { buildReplyHeaders, composeRaw, renderMarkdown, htmlToMarkdown, HeaderInjectionError } from './gmail-mime.js';
8
+ import addressparser from 'nodemailer/lib/addressparser/index.js';
9
+ import { lookup as lookupMime } from 'mime-types';
10
+ import { configDir } from '../config-file.js';
11
+ import { getTokenDir } from '../accounts.js';
8
12
  import { sliceClean } from '../trim.js';
9
13
  import * as path from 'path';
10
14
  import * as fs from 'fs';
11
- const accountEnum = z.enum(ACCOUNTS);
15
+ const accountEnum = accountAliasSchema.optional();
12
16
  function getHeader(headers, name) {
13
17
  return headers?.find((h) => h.name?.toLowerCase() === name.toLowerCase())?.value ?? '';
14
18
  }
@@ -35,13 +39,18 @@ function decodeBody(payload, rawHtml = false) {
35
39
  collectTextParts(payload, plain, html, true);
36
40
  // Concatenating every plain leaf keeps forwarded/mixed messages whole;
37
41
  // any plain content beats HTML because alternatives duplicate the same body.
42
+ // A plain leaf is returned verbatim (byte-identical to v5).
38
43
  if (plain.length > 0)
39
- return { body: plain.join('\n\n'), bodyOrigin: 'text/plain' };
44
+ return { body: plain.join('\n\n'), bodyFormat: 'plain' };
40
45
  if (html.length > 0) {
41
46
  const joined = html.join('\n\n');
42
- return { body: rawHtml ? joined : htmlToText(joined), bodyOrigin: 'text/html' };
47
+ if (rawHtml)
48
+ return { body: joined, bodyFormat: 'html' };
49
+ // HTML-only -> Markdown (D6). turndown failure degrades to plain text.
50
+ const { text, ok } = htmlToMarkdown(joined);
51
+ return { body: text, bodyFormat: ok ? 'markdown' : 'plain' };
43
52
  }
44
- return { body: '' };
53
+ return { body: '', bodyFormat: 'plain' };
45
54
  }
46
55
  function getAttachments(payload) {
47
56
  const attachments = [];
@@ -65,26 +74,241 @@ function getAttachments(payload) {
65
74
  }
66
75
  return attachments;
67
76
  }
68
- async function resolveReplyHeaders(gmail, replyToMessageId) {
77
+ function parseAddresses(headerValue) {
78
+ if (!headerValue)
79
+ return [];
80
+ const out = [];
81
+ const walk = (entries) => {
82
+ for (const e of entries) {
83
+ if (e?.group)
84
+ walk(e.group);
85
+ else if (e?.address)
86
+ out.push({ address: String(e.address).trim(), name: String(e.name ?? '').trim() });
87
+ }
88
+ };
89
+ walk(addressparser(headerValue));
90
+ return out;
91
+ }
92
+ const normAddr = (a) => a.trim().toLowerCase();
93
+ /** Rebuild a comma-separated address header; composeRaw/MailComposer re-encodes
94
+ * names (RFC 2047) and the A4 CRLF pre-check applies, so derived recipients get
95
+ * the same header-injection guard as caller-supplied ones. */
96
+ function formatAddresses(list) {
97
+ return list.map((a) => (a.name ? `${a.name} <${a.address}>` : a.address)).join(', ');
98
+ }
99
+ /** Re: prefix unless the subject already carries one (case-insensitive, after
100
+ * trimming); never double-prefix. */
101
+ export function deriveReplySubject(sourceSubject) {
102
+ const s = sourceSubject.trim();
103
+ return /^re:/i.test(s) ? s : `Re: ${s}`;
104
+ }
105
+ // The account's own-address set (primary + Gmail send-as aliases) used to
106
+ // exclude the caller from reply-all. Send-as rarely changes, so memoize per
107
+ // process; a stale miss only costs one extra self-copy, never a wrong send.
108
+ const ownAddressCache = new Map();
109
+ function getOwnAddresses(gmail, account, primaryEmail) {
110
+ let cached = ownAddressCache.get(account);
111
+ if (!cached) {
112
+ cached = (async () => {
113
+ const set = new Set([normAddr(primaryEmail)]);
114
+ try {
115
+ const res = await gmail.users.settings.sendAs.list({ userId: 'me' });
116
+ for (const entry of res.data.sendAs ?? []) {
117
+ if (entry.sendAsEmail)
118
+ set.add(normAddr(entry.sendAsEmail));
119
+ }
120
+ }
121
+ catch {
122
+ // insufficient_scope / 5xx: degrade to the primary alone, never block the send.
123
+ }
124
+ return set;
125
+ })();
126
+ ownAddressCache.set(account, cached);
127
+ }
128
+ return cached;
129
+ }
130
+ /** Fetch the reply source once and derive threading headers plus (auto-fill)
131
+ * to/cc/subject. On any fetch failure, degrade to the API id for threading and
132
+ * report sourceFound:false so the caller can decide (per A8 error dispositions). */
133
+ export async function resolveReply(gmail, account, primaryEmail, replyToMessageId, replyAll) {
134
+ let headers;
69
135
  try {
70
136
  const meta = await gmail.users.messages.get({
71
137
  userId: 'me',
72
138
  id: replyToMessageId,
73
139
  format: 'metadata',
74
- metadataHeaders: ['Message-ID', 'References'],
140
+ metadataHeaders: ['From', 'To', 'Cc', 'Subject', 'Message-ID', 'References'],
75
141
  });
76
- const headers = meta.data.payload?.headers;
77
- return buildReplyHeaders(replyToMessageId, getHeader(headers, 'Message-ID'), getHeader(headers, 'References'));
142
+ headers = meta.data.payload?.headers;
78
143
  }
79
144
  catch {
80
145
  // Degrade to the API id (pre-lookup behavior) rather than blocking the send.
81
- return { inReplyTo: replyToMessageId, references: replyToMessageId };
146
+ return { inReplyTo: replyToMessageId, references: replyToMessageId, sourceFound: false };
82
147
  }
148
+ const threading = buildReplyHeaders(replyToMessageId, getHeader(headers, 'Message-ID'), getHeader(headers, 'References'));
149
+ const own = await getOwnAddresses(gmail, account, primaryEmail);
150
+ const fromList = parseAddresses(getHeader(headers, 'From'));
151
+ const toList = parseAddresses(getHeader(headers, 'To'));
152
+ const ccList = parseAddresses(getHeader(headers, 'Cc'));
153
+ // Replying to your own sent mail: From is self, so reply to the original To.
154
+ const fromIsSelf = fromList.length > 0 && fromList.every((a) => own.has(normAddr(a.address)));
155
+ const derivedToList = fromIsSelf ? toList : fromList;
156
+ const derivedTo = formatAddresses(derivedToList);
157
+ let derivedCc;
158
+ if (replyAll) {
159
+ const toAddrs = new Set(derivedToList.map((a) => normAddr(a.address)));
160
+ const seen = new Set();
161
+ const ccOut = [];
162
+ for (const a of [...toList, ...ccList]) {
163
+ const key = normAddr(a.address);
164
+ if (own.has(key) || toAddrs.has(key) || seen.has(key))
165
+ continue;
166
+ seen.add(key);
167
+ ccOut.push(a);
168
+ }
169
+ if (ccOut.length > 0)
170
+ derivedCc = formatAddresses(ccOut);
171
+ }
172
+ return {
173
+ ...threading,
174
+ sourceFound: true,
175
+ to: derivedTo || undefined,
176
+ cc: derivedCc,
177
+ subject: deriveReplySubject(getHeader(headers, 'Subject')),
178
+ };
83
179
  }
84
180
  const BODY_CAP_CHARS = 50_000;
181
+ // gmail_read_batch aggregate ceiling: a batch of up to 100 messages must never
182
+ // blow the context window, so the summed serialized output is bounded here
183
+ // (matches the tool's anthropic/maxResultSizeChars hint). Per-message bodies are
184
+ // still individually capped at BODY_CAP_CHARS first.
185
+ const BATCH_MAX_RESULT_CHARS = 100_000;
186
+ // Gmail's messages.send raw/JSON path rejects messages near ~25 MB (the wire
187
+ // message is base64-encoded, ~+33% over the raw bytes), so cap the ESTIMATED
188
+ // ENCODED total there rather than the spec's nominal 35 MB raw (spike/live
189
+ // correction — a 35 MB raw payload is ~47 MB on the wire and Gmail 400s it).
190
+ const GMAIL_MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
191
+ const estimateEncoded = (rawBytes) => Math.ceil((rawBytes * 4) / 3);
192
+ const attachmentSchema = z
193
+ .array(z.object({
194
+ path: z.string().describe('Absolute local path to the file to attach'),
195
+ filename: z.string().optional().describe('MIME filename; defaults to the path basename'),
196
+ contentType: z.string().optional().describe('MIME type; defaults to a lookup on the filename'),
197
+ }))
198
+ .optional()
199
+ .describe('Files to attach (each { path, filename?, contentType? }); path must be absolute');
200
+ /** Reads attachment files into buffers (THIS server reads them, never
201
+ * MailComposer), enforces absolute-path + total-size guards, and derives the
202
+ * MIME filename via basename so a caller name can't inject path separators. */
203
+ // Deny reading anything inside the server's own secret dirs — mailing out
204
+ // master.key / <alias>.enc / mcp-jwt.key would be a full-account-takeover
205
+ // exfil channel (this same server also reads untrusted mail/drive content, so
206
+ // a prompt-injected attach path is a real confused-deputy vector).
207
+ function isInside(dir, target) {
208
+ let d = path.resolve(dir);
209
+ let t = path.resolve(target);
210
+ // Windows path comparison is case-insensitive; without folding, a
211
+ // drive-letter/casing difference makes path.relative report "outside".
212
+ if (process.platform === 'win32') {
213
+ d = d.toLowerCase();
214
+ t = t.toLowerCase();
215
+ }
216
+ const rel = path.relative(d, t);
217
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
218
+ }
219
+ /** Deny if realTarget resolves inside `dir` (both realpath'd so a symlinked
220
+ * dir or 8.3/extended-prefix form can't slip past). */
221
+ async function isInsideRealDir(dir, realTarget) {
222
+ let realDir;
223
+ try {
224
+ realDir = await fs.promises.realpath(dir);
225
+ }
226
+ catch {
227
+ return false; // dir does not exist → target cannot be inside it
228
+ }
229
+ return isInside(realDir, realTarget);
230
+ }
231
+ export async function readAttachments(raw, bodyBytes) {
232
+ if (!raw || raw.length === 0)
233
+ return undefined;
234
+ const denied = [configDir(), getTokenDir()];
235
+ const out = [];
236
+ let total = bodyBytes;
237
+ for (const a of raw) {
238
+ if (!path.isAbsolute(a.path)) {
239
+ throw new GmailComposeError('validation_error', `attachment path must be absolute: ${path.basename(a.path)}`);
240
+ }
241
+ // Resolve symlinks BEFORE any confinement check, or a symlink defeats it.
242
+ let real;
243
+ try {
244
+ real = await fs.promises.realpath(a.path);
245
+ }
246
+ catch {
247
+ throw new GmailComposeError('E_ATTACHMENT_NOT_FOUND', `attachment not found or unreadable: ${path.basename(a.path)}`);
248
+ }
249
+ for (const d of denied) {
250
+ if (await isInsideRealDir(d, real)) {
251
+ throw new GmailComposeError('E_ATTACHMENT_FORBIDDEN', `refusing to attach a file inside the server's config/token directory: ${path.basename(a.path)}`);
252
+ }
253
+ }
254
+ // stat BEFORE read: reject non-regular files (a FIFO would block readFile
255
+ // forever) and over-cap files without buffering them.
256
+ let stat;
257
+ try {
258
+ stat = await fs.promises.stat(real);
259
+ }
260
+ catch {
261
+ throw new GmailComposeError('E_ATTACHMENT_NOT_FOUND', `attachment not found or unreadable: ${path.basename(a.path)}`);
262
+ }
263
+ if (!stat.isFile()) {
264
+ throw new GmailComposeError('validation_error', `attachment is not a regular file: ${path.basename(a.path)}`);
265
+ }
266
+ total += stat.size;
267
+ if (estimateEncoded(total) > GMAIL_MAX_MESSAGE_BYTES) {
268
+ throw new GmailComposeError('E_ATTACHMENT_TOO_LARGE', `attachments + body exceed Gmail's ~${Math.round(GMAIL_MAX_MESSAGE_BYTES / 1024 / 1024)}MB message limit once encoded (estimated ${Math.round(estimateEncoded(total) / 1024 / 1024)}MB)`);
269
+ }
270
+ const content = await fs.promises.readFile(real);
271
+ const filename = path.basename(a.filename ?? a.path);
272
+ out.push({
273
+ filename,
274
+ content,
275
+ contentType: a.contentType || lookupMime(filename) || 'application/octet-stream',
276
+ });
277
+ }
278
+ return out;
279
+ }
280
+ /** Tagged compose-time failure; the handlers map it to an isError envelope.
281
+ * `category` is the taxonomy error field (default validation_error); reply
282
+ * auto-fill raises it as not_found when a source message can't be fetched. */
283
+ class GmailComposeError extends Error {
284
+ slug;
285
+ category;
286
+ constructor(slug, message, category = 'validation_error') {
287
+ super(message);
288
+ this.slug = slug;
289
+ this.category = category;
290
+ }
291
+ }
292
+ /** Maps compose-time (non-Google) failures to an isError envelope;
293
+ * returns null for anything else so the Google error mapper handles it. */
294
+ function composeErrorResult(error, account) {
295
+ const slug = error instanceof HeaderInjectionError ? 'E_HEADER_INJECTION'
296
+ : error instanceof GmailComposeError ? error.slug
297
+ : null;
298
+ if (!slug)
299
+ return null;
300
+ const category = error instanceof GmailComposeError ? error.category : 'validation_error';
301
+ return {
302
+ content: [{
303
+ type: 'text',
304
+ text: JSON.stringify({ error: category, slug, message: error.message, retriable: false, account }),
305
+ }],
306
+ isError: true,
307
+ };
308
+ }
85
309
  export function parseMessage(msg, bodyCap, opts) {
86
310
  const headers = msg.payload?.headers ?? [];
87
- const { body, bodyOrigin } = decodeBody(msg.payload, opts?.rawHtml === true);
311
+ const { body, bodyFormat } = decodeBody(msg.payload, opts?.rawHtml === true);
88
312
  const capped = bodyCap !== undefined && body.length > bodyCap;
89
313
  const messageIdHeader = getHeader(headers, 'Message-ID');
90
314
  const inReplyTo = getHeader(headers, 'In-Reply-To');
@@ -98,7 +322,7 @@ export function parseMessage(msg, bodyCap, opts) {
98
322
  cc: getHeader(headers, 'Cc'),
99
323
  date: getHeader(headers, 'Date'),
100
324
  body: capped ? sliceClean(body, bodyCap) : body,
101
- ...(bodyOrigin ? { bodyOrigin } : {}),
325
+ bodyFormat,
102
326
  ...(capped ? { bodyTruncated: true, bodyTotalChars: body.length } : {}),
103
327
  ...(messageIdHeader ? { messageIdHeader } : {}),
104
328
  ...(inReplyTo ? { inReplyTo } : {}),
@@ -108,6 +332,96 @@ export function parseMessage(msg, bodyCap, opts) {
108
332
  attachments: getAttachments(msg.payload),
109
333
  };
110
334
  }
335
+ /**
336
+ * A9 gmail_read_batch core: fetch N ids with bounded parallelism, parse each,
337
+ * and bound the aggregate output. Order is preserved by input index. A per-id
338
+ * failure becomes a `{ id, error }` entry; an account-wide auth/scope failure
339
+ * is rethrown so the caller maps it to a whole-call isError. Returns the
340
+ * ordered per-id entries followed by a trailing counts summary.
341
+ */
342
+ export async function readBatch(gmail, account, ids, full, rawHtml) {
343
+ if (ids.length === 0) {
344
+ throw new GmailComposeError('validation_error', '`ids` must be a non-empty array of 1..100 message IDs.');
345
+ }
346
+ if (ids.length > 100) {
347
+ throw new GmailComposeError('validation_error', `\`ids\` accepts at most 100 message IDs per call (got ${ids.length}).`);
348
+ }
349
+ const cap = full ? undefined : BODY_CAP_CHARS;
350
+ const CHUNK_SIZE = 10;
351
+ const entries = new Array(ids.length);
352
+ let ok = 0;
353
+ let failed = 0;
354
+ for (let i = 0; i < ids.length; i += CHUNK_SIZE) {
355
+ const slice = ids.slice(i, i + CHUNK_SIZE);
356
+ const settled = await Promise.all(slice.map(async (id, j) => {
357
+ try {
358
+ const res = await gmail.users.messages.get({ userId: 'me', id, format: 'full' });
359
+ return { idx: i + j, id, ok: true, data: res.data };
360
+ }
361
+ catch (err) {
362
+ return { idx: i + j, id, ok: false, err };
363
+ }
364
+ }));
365
+ for (const s of settled) {
366
+ if (s.ok) {
367
+ entries[s.idx] = parseMessage(s.data, cap, { rawHtml });
368
+ ok++;
369
+ }
370
+ else {
371
+ const env = mapGoogleError(s.err, account);
372
+ // Auth/scope problems are account-wide, not id-specific: fail the whole
373
+ // batch rather than emit N identical per-item errors.
374
+ if (env.error === 'auth_required' || env.error === 'insufficient_scope' || env.error === 'invalid_scope') {
375
+ throw s.err;
376
+ }
377
+ const { account: _dropped, ...itemError } = env;
378
+ entries[s.idx] = { id: s.id, error: itemError };
379
+ failed++;
380
+ }
381
+ }
382
+ }
383
+ // Aggregate guard: walk in order, accumulating serialized size. Once the
384
+ // running total would exceed the maxResultSizeChars budget, cap this and every
385
+ // later success body so a big batch never blows the context window.
386
+ let running = 0;
387
+ let truncatedAny = false;
388
+ let exhausted = false;
389
+ for (const e of entries) {
390
+ if (!e || e.error) {
391
+ running += JSON.stringify(e ?? {}).length;
392
+ continue;
393
+ }
394
+ const body = e.body ?? '';
395
+ if (exhausted) {
396
+ if (body.length > 0) {
397
+ if (!e.bodyTruncated)
398
+ e.bodyTotalChars = body.length;
399
+ e.body = '';
400
+ e.bodyTruncated = true;
401
+ truncatedAny = true;
402
+ }
403
+ running += JSON.stringify(e).length;
404
+ continue;
405
+ }
406
+ const serialized = JSON.stringify(e).length;
407
+ if (running + serialized > BATCH_MAX_RESULT_CHARS) {
408
+ const envelope = serialized - body.length; // non-body overhead of this entry
409
+ const remaining = Math.max(0, BATCH_MAX_RESULT_CHARS - running - envelope);
410
+ if (!e.bodyTruncated)
411
+ e.bodyTotalChars = body.length;
412
+ e.body = sliceClean(body, Math.min(body.length, remaining));
413
+ e.bodyTruncated = true;
414
+ truncatedAny = true;
415
+ exhausted = true;
416
+ running += JSON.stringify(e).length;
417
+ }
418
+ else {
419
+ running += serialized;
420
+ }
421
+ }
422
+ const summary = { counts: { ok, failed }, ...(truncatedAny ? { truncated: true } : {}) };
423
+ return [...entries, summary];
424
+ }
111
425
  export function registerGmailTools(server) {
112
426
  server.registerTool('gmail_search', {
113
427
  description: 'Search messages in a Gmail account',
@@ -156,10 +470,12 @@ export function registerGmailTools(server) {
156
470
  };
157
471
  }
158
472
  catch (error) {
159
- return handleGmailError(error, account);
473
+ const mapped = composeErrorResult(error, account);
474
+ return mapped ?? handleGmailError(error, account);
160
475
  }
161
476
  });
162
477
  server.registerTool('gmail_read', {
478
+ _meta: { 'anthropic/maxResultSizeChars': 50_000 },
163
479
  description: 'Read a full Gmail message by ID (body capped at 50k chars unless full=true)',
164
480
  inputSchema: {
165
481
  account: accountEnum.describe('Google account alias'),
@@ -183,10 +499,12 @@ export function registerGmailTools(server) {
183
499
  };
184
500
  }
185
501
  catch (error) {
186
- return handleGmailError(error, account);
502
+ const mapped = composeErrorResult(error, account);
503
+ return mapped ?? handleGmailError(error, account);
187
504
  }
188
505
  });
189
506
  server.registerTool('gmail_read_thread', {
507
+ _meta: { 'anthropic/maxResultSizeChars': 50_000 },
190
508
  description: 'Read all messages in a Gmail thread (bodies capped at 50k chars each unless full=true). mode=summary returns headers + snippets only.',
191
509
  inputSchema: {
192
510
  account: accountEnum.describe('Google account alias'),
@@ -232,55 +550,93 @@ export function registerGmailTools(server) {
232
550
  };
233
551
  }
234
552
  catch (error) {
235
- return handleGmailError(error, account);
553
+ const mapped = composeErrorResult(error, account);
554
+ return mapped ?? handleGmailError(error, account);
555
+ }
556
+ });
557
+ server.registerTool('gmail_read_batch', {
558
+ _meta: { 'anthropic/maxResultSizeChars': BATCH_MAX_RESULT_CHARS },
559
+ annotations: { readOnlyHint: true, openWorldHint: true },
560
+ description: 'Read many Gmail messages by ID in one call, collapsing the search→read triage loop. Bodies are capped at 50k chars each (unless full=true) and the aggregate output is bounded. Returns one ordered entry per id plus a trailing counts summary; a single failed id does NOT fail the batch.',
561
+ inputSchema: {
562
+ account: accountEnum.describe('Google account alias'),
563
+ ids: coerceArray(z.string()).describe('Gmail message IDs to read (1..100). Comma-separated string or JSON array.'),
564
+ full: coerceBoolean.optional().describe('Return entire bodies without the per-message 50k character cap'),
565
+ rawHtml: coerceBoolean.optional()
566
+ .describe('Return HTML bodies unconverted instead of the plain-text rendering (HTML-only messages)'),
567
+ },
568
+ }, async ({ account, ids, full, rawHtml }) => {
569
+ try {
570
+ const auth = await getClient(account);
571
+ const gmail = gmailClient({ version: 'v1', auth });
572
+ const result = await readBatch(gmail, account, ids ?? [], full === true, rawHtml === true);
573
+ return {
574
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
575
+ };
576
+ }
577
+ catch (error) {
578
+ const mapped = composeErrorResult(error, account);
579
+ return mapped ?? handleGmailError(error, account);
236
580
  }
237
581
  });
238
582
  server.registerTool('gmail_send', {
239
583
  description: 'Send an email from a Gmail account',
240
584
  inputSchema: {
241
585
  account: accountEnum.describe('Google account alias'),
242
- to: z.string().describe('Recipient(s), comma-separated'),
243
- subject: z.string().describe('Email subject'),
244
- body: z.string().describe('Plain text body (always required; also used as fallback when htmlBody is set)'),
586
+ to: z.string().optional().describe('Recipient(s), comma-separated. Optional when replyToMessageId is set (derived from the source); a supplied value wins.'),
587
+ subject: z.string().optional().describe('Email subject. Optional when replyToMessageId is set (derived as "Re: ..."); a supplied value wins.'),
588
+ body: z.string().describe('Email body as Markdown (headings, links, lists, tables, blockquotes). Rendered to HTML for the rich part; the Markdown source is the plain-text part.'),
245
589
  htmlBody: z.string().optional()
246
- .describe('Optional HTML body. When set, sends multipart/alternative so HTML-capable clients render the rich version. Use bare tags only: <p>, <a>, <br>, <strong>, <em>, <ul><li>.'),
247
- cc: z.string().optional().describe('CC recipients, comma-separated'),
590
+ .describe('REMOVED in v6: author Markdown in `body` instead; for literal HTML (e.g. inline color) pass `allowRawHtml: true`. Passing htmlBody now errors.'),
591
+ allowRawHtml: z.boolean().optional()
592
+ .describe('When true, raw HTML in `body` passes through into the HTML part instead of being escaped. Default false (HTML is shown literally).'),
593
+ cc: z.string().optional().describe('CC recipients, comma-separated. With replyToMessageId + replyAll, derived from the source minus your own addresses; a supplied value wins.'),
248
594
  replyToMessageId: z.string().optional()
249
- .describe('Message ID to reply to (sets In-Reply-To and References headers)'),
595
+ .describe('Message ID to reply to. Sets In-Reply-To/References and, unless overridden, derives to/subject (and cc when replyAll) from the source, so you need not read it first.'),
596
+ replyAll: coerceBoolean.optional()
597
+ .describe('With replyToMessageId: include the source To+Cc (minus your own addresses) in cc. Default false (reply to sender only).'),
250
598
  replyToThreadId: z.string().optional()
251
599
  .describe('Thread ID to send the message in'),
600
+ attachments: coerceJson(attachmentSchema),
252
601
  },
253
- }, async ({ account, to, subject, body, htmlBody, cc, replyToMessageId, replyToThreadId }) => {
602
+ }, async ({ account, to, subject, body, htmlBody, allowRawHtml, cc, replyToMessageId, replyAll, replyToThreadId, attachments }) => {
254
603
  try {
255
604
  const auth = await getClient(account);
256
605
  const gmail = gmailClient({ version: 'v1', auth });
257
- const config = (await import('../accounts.js')).ACCOUNT_CONFIG[account];
258
- const headers = [
259
- `From: ${encodeAddressHeader(config.email)}`,
260
- `To: ${encodeAddressHeader(to)}`,
261
- `Subject: ${encodeHeaderValue(subject)}`,
262
- 'MIME-Version: 1.0',
263
- ];
264
- let bodyText;
265
- if (htmlBody) {
266
- const { contentType, body: mp } = buildMultipartAlternative(body, htmlBody);
267
- headers.push(`Content-Type: ${contentType}`);
268
- bodyText = mp;
606
+ const config = (await import('../accounts.js')).getAccountSet().configs[account];
607
+ if (htmlBody !== undefined) {
608
+ throw new GmailComposeError('E_HTMLBODY_REMOVED', 'htmlBody was removed in v6: author Markdown in `body`; for literal HTML pass `allowRawHtml: true`.');
269
609
  }
270
- else {
271
- headers.push('Content-Type: text/plain; charset="UTF-8"');
272
- headers.push('Content-Transfer-Encoding: 8bit');
273
- bodyText = normalizeBodyLineEndings(body);
610
+ const reply = replyToMessageId
611
+ ? await resolveReply(gmail, account, config.email, replyToMessageId, replyAll === true)
612
+ : undefined;
613
+ // Caller value > derived value. A missing source with no caller `to`
614
+ // means we cannot address the reply: fail rather than silently drop it.
615
+ if (reply && !reply.sourceFound && to === undefined) {
616
+ throw new GmailComposeError('E_REPLY_SOURCE_NOT_FOUND', `reply source message ${replyToMessageId} not found; recipients could not be derived and no \`to\` was provided.`, 'not_found');
617
+ }
618
+ const finalTo = to ?? reply?.to;
619
+ const finalSubject = subject ?? reply?.subject;
620
+ const finalCc = cc ?? reply?.cc;
621
+ if (finalTo === undefined || finalTo === '') {
622
+ throw new GmailComposeError('E_MISSING_RECIPIENT', '`to` is required (or set replyToMessageId to derive it from the source).');
274
623
  }
275
- if (cc)
276
- headers.push(`Cc: ${encodeAddressHeader(cc)}`);
277
- if (replyToMessageId) {
278
- const { inReplyTo, references } = await resolveReplyHeaders(gmail, replyToMessageId);
279
- headers.push(`In-Reply-To: ${inReplyTo}`);
280
- headers.push(`References: ${references}`);
624
+ if (finalSubject === undefined) {
625
+ throw new GmailComposeError('E_MISSING_SUBJECT', '`subject` is required (or set replyToMessageId to derive it from the source).');
281
626
  }
282
- const rawMessage = [...headers, '', bodyText].join('\r\n');
283
- const encoded = Buffer.from(rawMessage, 'utf-8').toString('base64url');
627
+ const html = renderMarkdown(body, allowRawHtml === true);
628
+ const files = await readAttachments(attachments, Buffer.byteLength(body ?? '') + Buffer.byteLength(html));
629
+ const encoded = await composeRaw({
630
+ from: config.email,
631
+ to: finalTo,
632
+ subject: finalSubject,
633
+ text: body,
634
+ html,
635
+ cc: finalCc,
636
+ inReplyTo: reply?.inReplyTo,
637
+ references: reply?.references,
638
+ attachments: files,
639
+ });
284
640
  const sendParams = {
285
641
  userId: 'me',
286
642
  requestBody: { raw: encoded },
@@ -297,7 +653,8 @@ export function registerGmailTools(server) {
297
653
  };
298
654
  }
299
655
  catch (error) {
300
- return handleGmailError(error, account);
656
+ const mapped = composeErrorResult(error, account);
657
+ return mapped ?? handleGmailError(error, account);
301
658
  }
302
659
  });
303
660
  server.registerTool('gmail_download_attachment', {
@@ -330,55 +687,66 @@ export function registerGmailTools(server) {
330
687
  };
331
688
  }
332
689
  catch (error) {
333
- return handleGmailError(error, account);
690
+ const mapped = composeErrorResult(error, account);
691
+ return mapped ?? handleGmailError(error, account);
334
692
  }
335
693
  });
336
694
  server.registerTool('gmail_create_draft', {
337
695
  description: 'Create a Gmail draft without sending',
338
696
  inputSchema: {
339
697
  account: accountEnum.describe('Google account alias'),
340
- to: z.string().describe('Recipient(s), comma-separated'),
341
- subject: z.string().describe('Email subject'),
342
- body: z.string().describe('Plain text body (always required; also used as fallback when htmlBody is set)'),
698
+ to: z.string().optional().describe('Recipient(s), comma-separated. Optional when replyToMessageId is set (derived from the source); a supplied value wins.'),
699
+ subject: z.string().optional().describe('Email subject. Optional when replyToMessageId is set (derived as "Re: ..."); a supplied value wins.'),
700
+ body: z.string().describe('Email body as Markdown (headings, links, lists, tables, blockquotes). Rendered to HTML for the rich part; the Markdown source is the plain-text part.'),
343
701
  htmlBody: z.string().optional()
344
- .describe('Optional HTML body. When set, drafts as multipart/alternative so HTML-capable clients render the rich version. Use bare tags only: <p>, <a>, <br>, <strong>, <em>, <ul><li>.'),
345
- cc: z.string().optional().describe('CC recipients, comma-separated'),
702
+ .describe('REMOVED in v6: author Markdown in `body` instead; for literal HTML (e.g. inline color) pass `allowRawHtml: true`. Passing htmlBody now errors.'),
703
+ allowRawHtml: z.boolean().optional()
704
+ .describe('When true, raw HTML in `body` passes through into the HTML part instead of being escaped. Default false (HTML is shown literally).'),
705
+ cc: z.string().optional().describe('CC recipients, comma-separated. With replyToMessageId + replyAll, derived from the source minus your own addresses; a supplied value wins.'),
346
706
  replyToMessageId: z.string().optional()
347
- .describe('Message ID to reply to (sets In-Reply-To and References headers)'),
707
+ .describe('Message ID to reply to. Sets In-Reply-To/References and, unless overridden, derives to/subject (and cc when replyAll) from the source, so you need not read it first.'),
708
+ replyAll: coerceBoolean.optional()
709
+ .describe('With replyToMessageId: include the source To+Cc (minus your own addresses) in cc. Default false (reply to sender only).'),
348
710
  replyToThreadId: z.string().optional()
349
711
  .describe('Thread ID to associate the draft with'),
712
+ attachments: coerceJson(attachmentSchema),
350
713
  },
351
- }, async ({ account, to, subject, body, htmlBody, cc, replyToMessageId, replyToThreadId }) => {
714
+ }, async ({ account, to, subject, body, htmlBody, allowRawHtml, cc, replyToMessageId, replyAll, replyToThreadId, attachments }) => {
352
715
  try {
353
716
  const auth = await getClient(account);
354
717
  const gmail = gmailClient({ version: 'v1', auth });
355
- const config = (await import('../accounts.js')).ACCOUNT_CONFIG[account];
356
- const headers = [
357
- `From: ${encodeAddressHeader(config.email)}`,
358
- `To: ${encodeAddressHeader(to)}`,
359
- `Subject: ${encodeHeaderValue(subject)}`,
360
- 'MIME-Version: 1.0',
361
- ];
362
- let bodyText;
363
- if (htmlBody) {
364
- const { contentType, body: mp } = buildMultipartAlternative(body, htmlBody);
365
- headers.push(`Content-Type: ${contentType}`);
366
- bodyText = mp;
718
+ const config = (await import('../accounts.js')).getAccountSet().configs[account];
719
+ if (htmlBody !== undefined) {
720
+ throw new GmailComposeError('E_HTMLBODY_REMOVED', 'htmlBody was removed in v6: author Markdown in `body`; for literal HTML pass `allowRawHtml: true`.');
367
721
  }
368
- else {
369
- headers.push('Content-Type: text/plain; charset="UTF-8"');
370
- headers.push('Content-Transfer-Encoding: 8bit');
371
- bodyText = normalizeBodyLineEndings(body);
722
+ const reply = replyToMessageId
723
+ ? await resolveReply(gmail, account, config.email, replyToMessageId, replyAll === true)
724
+ : undefined;
725
+ if (reply && !reply.sourceFound && to === undefined) {
726
+ throw new GmailComposeError('E_REPLY_SOURCE_NOT_FOUND', `reply source message ${replyToMessageId} not found; recipients could not be derived and no \`to\` was provided.`, 'not_found');
372
727
  }
373
- if (cc)
374
- headers.push(`Cc: ${encodeAddressHeader(cc)}`);
375
- if (replyToMessageId) {
376
- const { inReplyTo, references } = await resolveReplyHeaders(gmail, replyToMessageId);
377
- headers.push(`In-Reply-To: ${inReplyTo}`);
378
- headers.push(`References: ${references}`);
728
+ const finalTo = to ?? reply?.to;
729
+ const finalSubject = subject ?? reply?.subject;
730
+ const finalCc = cc ?? reply?.cc;
731
+ if (finalTo === undefined || finalTo === '') {
732
+ throw new GmailComposeError('E_MISSING_RECIPIENT', '`to` is required (or set replyToMessageId to derive it from the source).');
379
733
  }
380
- const rawMessage = [...headers, '', bodyText].join('\r\n');
381
- const encoded = Buffer.from(rawMessage, 'utf-8').toString('base64url');
734
+ if (finalSubject === undefined) {
735
+ throw new GmailComposeError('E_MISSING_SUBJECT', '`subject` is required (or set replyToMessageId to derive it from the source).');
736
+ }
737
+ const html = renderMarkdown(body, allowRawHtml === true);
738
+ const files = await readAttachments(attachments, Buffer.byteLength(body ?? '') + Buffer.byteLength(html));
739
+ const encoded = await composeRaw({
740
+ from: config.email,
741
+ to: finalTo,
742
+ subject: finalSubject,
743
+ text: body,
744
+ html,
745
+ cc: finalCc,
746
+ inReplyTo: reply?.inReplyTo,
747
+ references: reply?.references,
748
+ attachments: files,
749
+ });
382
750
  const draftParams = {
383
751
  userId: 'me',
384
752
  requestBody: {
@@ -397,7 +765,8 @@ export function registerGmailTools(server) {
397
765
  };
398
766
  }
399
767
  catch (error) {
400
- return handleGmailError(error, account);
768
+ const mapped = composeErrorResult(error, account);
769
+ return mapped ?? handleGmailError(error, account);
401
770
  }
402
771
  });
403
772
  server.registerTool('gmail_modify_labels', {
@@ -425,7 +794,8 @@ export function registerGmailTools(server) {
425
794
  };
426
795
  }
427
796
  catch (error) {
428
- return handleGmailError(error, account);
797
+ const mapped = composeErrorResult(error, account);
798
+ return mapped ?? handleGmailError(error, account);
429
799
  }
430
800
  });
431
801
  server.registerTool('gmail_trash', {
@@ -444,7 +814,8 @@ export function registerGmailTools(server) {
444
814
  };
445
815
  }
446
816
  catch (error) {
447
- return handleGmailError(error, account);
817
+ const mapped = composeErrorResult(error, account);
818
+ return mapped ?? handleGmailError(error, account);
448
819
  }
449
820
  });
450
821
  server.registerTool('gmail_delete', {
@@ -463,7 +834,8 @@ export function registerGmailTools(server) {
463
834
  };
464
835
  }
465
836
  catch (error) {
466
- return handleGmailError(error, account);
837
+ const mapped = composeErrorResult(error, account);
838
+ return mapped ?? handleGmailError(error, account);
467
839
  }
468
840
  });
469
841
  server.registerTool('gmail_batch_modify', {
@@ -491,7 +863,8 @@ export function registerGmailTools(server) {
491
863
  };
492
864
  }
493
865
  catch (error) {
494
- return handleGmailError(error, account);
866
+ const mapped = composeErrorResult(error, account);
867
+ return mapped ?? handleGmailError(error, account);
495
868
  }
496
869
  });
497
870
  server.registerTool('gmail_batch_delete', {
@@ -513,7 +886,8 @@ export function registerGmailTools(server) {
513
886
  };
514
887
  }
515
888
  catch (error) {
516
- return handleGmailError(error, account);
889
+ const mapped = composeErrorResult(error, account);
890
+ return mapped ?? handleGmailError(error, account);
517
891
  }
518
892
  });
519
893
  server.registerTool('gmail_list_drafts', {
@@ -538,7 +912,8 @@ export function registerGmailTools(server) {
538
912
  };
539
913
  }
540
914
  catch (error) {
541
- return handleGmailError(error, account);
915
+ const mapped = composeErrorResult(error, account);
916
+ return mapped ?? handleGmailError(error, account);
542
917
  }
543
918
  });
544
919
  server.registerTool('gmail_get_draft', {
@@ -561,7 +936,8 @@ export function registerGmailTools(server) {
561
936
  };
562
937
  }
563
938
  catch (error) {
564
- return handleGmailError(error, account);
939
+ const mapped = composeErrorResult(error, account);
940
+ return mapped ?? handleGmailError(error, account);
565
941
  }
566
942
  });
567
943
  server.registerTool('gmail_send_draft', {
@@ -583,7 +959,8 @@ export function registerGmailTools(server) {
583
959
  };
584
960
  }
585
961
  catch (error) {
586
- return handleGmailError(error, account);
962
+ const mapped = composeErrorResult(error, account);
963
+ return mapped ?? handleGmailError(error, account);
587
964
  }
588
965
  });
589
966
  server.registerTool('gmail_list_labels', {
@@ -601,14 +978,15 @@ export function registerGmailTools(server) {
601
978
  };
602
979
  }
603
980
  catch (error) {
604
- return handleGmailError(error, account);
981
+ const mapped = composeErrorResult(error, account);
982
+ return mapped ?? handleGmailError(error, account);
605
983
  }
606
984
  });
607
985
  server.registerTool('gmail_create_label', {
608
986
  description: 'Create a new custom Gmail label',
609
987
  inputSchema: {
610
988
  account: accountEnum.describe('Google account alias'),
611
- name: z.string().describe('Label name, e.g. "Ideacrafters/ComptaLegal"'),
989
+ name: z.string().describe('Label name, e.g. "Work/Projects" (nested labels use "/")'),
612
990
  messageListVisibility: z.enum(['show', 'hide']).optional()
613
991
  .describe('Whether messages with this label show in message list (default: show)'),
614
992
  labelListVisibility: z.enum(['labelShow', 'labelShowIfUnread', 'labelHide']).optional()
@@ -631,7 +1009,8 @@ export function registerGmailTools(server) {
631
1009
  };
632
1010
  }
633
1011
  catch (error) {
634
- return handleGmailError(error, account);
1012
+ const mapped = composeErrorResult(error, account);
1013
+ return mapped ?? handleGmailError(error, account);
635
1014
  }
636
1015
  });
637
1016
  server.registerTool('gmail_delete_label', {
@@ -650,7 +1029,8 @@ export function registerGmailTools(server) {
650
1029
  };
651
1030
  }
652
1031
  catch (error) {
653
- return handleGmailError(error, account);
1032
+ const mapped = composeErrorResult(error, account);
1033
+ return mapped ?? handleGmailError(error, account);
654
1034
  }
655
1035
  });
656
1036
  server.registerTool('gmail_get_profile', {
@@ -668,7 +1048,8 @@ export function registerGmailTools(server) {
668
1048
  };
669
1049
  }
670
1050
  catch (error) {
671
- return handleGmailError(error, account);
1051
+ const mapped = composeErrorResult(error, account);
1052
+ return mapped ?? handleGmailError(error, account);
672
1053
  }
673
1054
  });
674
1055
  server.registerTool('gmail_list_history', {
@@ -696,7 +1077,8 @@ export function registerGmailTools(server) {
696
1077
  };
697
1078
  }
698
1079
  catch (error) {
699
- return handleGmailError(error, account);
1080
+ const mapped = composeErrorResult(error, account);
1081
+ return mapped ?? handleGmailError(error, account);
700
1082
  }
701
1083
  });
702
1084
  server.registerTool('gmail_get_vacation', {
@@ -714,7 +1096,8 @@ export function registerGmailTools(server) {
714
1096
  };
715
1097
  }
716
1098
  catch (error) {
717
- return handleGmailError(error, account);
1099
+ const mapped = composeErrorResult(error, account);
1100
+ return mapped ?? handleGmailError(error, account);
718
1101
  }
719
1102
  });
720
1103
  server.registerTool('gmail_set_vacation', {
@@ -750,7 +1133,8 @@ export function registerGmailTools(server) {
750
1133
  };
751
1134
  }
752
1135
  catch (error) {
753
- return handleGmailError(error, account);
1136
+ const mapped = composeErrorResult(error, account);
1137
+ return mapped ?? handleGmailError(error, account);
754
1138
  }
755
1139
  });
756
1140
  }