@blackbelt-technology/pi-dashboard-gmail-plugin 0.8.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.
@@ -0,0 +1,524 @@
1
+ /**
2
+ * Gmail pi tools (design D6). `gmail_accounts` takes no account; every other
3
+ * tool REQUIRES `account` (alias or email — never an implicit default).
4
+ *
5
+ * - Reads (`gmail_search`/`gmail_get`/`gmail_labels`/`gmail_attachments`)
6
+ * return `details.untrusted = true`; HTML bodies carry
7
+ * `details.contentType: "text/html"` so the untrusted-content guard scans them.
8
+ * - Writes (`gmail_draft`/`gmail_send`/`gmail_reply`/`gmail_modify`/
9
+ * `gmail_trash`) are confirmed via `ctx.ui.confirm` (account, recipients,
10
+ * subject, ≤500-char preview). No UI → blocked; dismissed / timed out /
11
+ * throwing confirm → denied.
12
+ * - One lease per call (`LeaseClient`); the lease's tier is re-checked.
13
+ * See change: add-gmail-plugin.
14
+ */
15
+ import type { GoogleEndpoints } from "../shared/endpoints.js";
16
+ import type { LeaseReply } from "../shared/protocol.js";
17
+ import type { Op } from "../shared/scopes.js";
18
+ import { MAX_ATTACH_BYTES, readInsideCwd, saveInsideCwd } from "./attachments.js";
19
+ import { extractBody, GmailApi, type GmailMessage, header, listAttachments } from "./gmail-api.js";
20
+ import { GmailToolError, type LeaseClient } from "./lease-client.js";
21
+ import { buildMime, type MimeAttachment, toRaw } from "./mime.js";
22
+
23
+ export const READ_TOOLS = ["gmail_search", "gmail_get", "gmail_labels", "gmail_attachments"] as const;
24
+ export const WRITE_TOOLS = ["gmail_draft", "gmail_send", "gmail_reply", "gmail_modify", "gmail_trash"] as const;
25
+
26
+ const MAX_SEARCH_RESULTS = 50;
27
+ const PREVIEW_CHARS = 500;
28
+
29
+ export interface ToolContext {
30
+ cwd?: string;
31
+ hasUI?: boolean;
32
+ ui?: { confirm(title: string, message: string, opts?: unknown): Promise<boolean> };
33
+ }
34
+
35
+ interface ToolResult {
36
+ content: Array<{ type: "text"; text: string }>;
37
+ details: Record<string, unknown>;
38
+ }
39
+
40
+ export interface GmailToolDef {
41
+ name: string;
42
+ label: string;
43
+ description: string;
44
+ parameters: Record<string, unknown>;
45
+ execute(
46
+ toolCallId: string,
47
+ params: Record<string, unknown>,
48
+ signal?: AbortSignal,
49
+ onUpdate?: unknown,
50
+ ctx?: ToolContext,
51
+ ): Promise<ToolResult>;
52
+ }
53
+
54
+ export interface GmailToolDeps {
55
+ leases: LeaseClient;
56
+ endpoints: GoogleEndpoints;
57
+ fetchImpl?: typeof fetch;
58
+ }
59
+
60
+ const ACCOUNT_PROP = {
61
+ type: "string",
62
+ minLength: 1,
63
+ description: "Account alias or email address. Required — list them with gmail_accounts.",
64
+ };
65
+ const RECIPIENTS = {
66
+ type: "array",
67
+ items: { type: "string", minLength: 3 },
68
+ maxItems: 100,
69
+ };
70
+ const ATTACH_PROP = {
71
+ type: "array",
72
+ items: { type: "string", minLength: 1 },
73
+ maxItems: 10,
74
+ description: "Paths of files to attach, relative to the session working directory.",
75
+ };
76
+
77
+ const text = (t: string, details: Record<string, unknown>): ToolResult => ({ content: [{ type: "text", text: t }], details });
78
+
79
+ function str(v: unknown, name: string, required = true): string | undefined {
80
+ if (v === undefined || v === null || v === "") {
81
+ if (required) throw new GmailToolError("invalid_params", `invalid_params: \`${name}\` is required`);
82
+ return undefined;
83
+ }
84
+ if (typeof v !== "string") throw new GmailToolError("invalid_params", `invalid_params: \`${name}\` must be a string`);
85
+ return v;
86
+ }
87
+
88
+ function strList(v: unknown, name: string, { min = 0, max = 100 } = {}): string[] {
89
+ if (v === undefined || v === null) {
90
+ if (min > 0) throw new GmailToolError("invalid_params", `invalid_params: \`${name}\` is required`);
91
+ return [];
92
+ }
93
+ if (!Array.isArray(v) || v.some((x) => typeof x !== "string" || !x.trim()) || v.length < min || v.length > max) {
94
+ throw new GmailToolError("invalid_params", `invalid_params: \`${name}\` must be a list of ${min}–${max} strings`);
95
+ }
96
+ return v as string[];
97
+ }
98
+
99
+ const ADDRESS_RE = /^(?:[^<>\r\n,]*<[^\s@<>,]+@[^\s@<>,]+>|[^\s@<>,]+@[^\s@<>,]+)$/;
100
+ function recipients(v: unknown, name: string, min: number): string[] {
101
+ const list = strList(v, name, { min, max: 100 }).map((s) => s.trim());
102
+ for (const r of list) {
103
+ if (!ADDRESS_RE.test(r)) throw new GmailToolError("invalid_params", `invalid_params: \`${name}\` has an invalid address`);
104
+ }
105
+ return list;
106
+ }
107
+
108
+ /** Split an address-list header on commas OUTSIDE quotes / angle brackets (`"Doe, John" <j@x>`). */
109
+ export function splitAddresses(v: string | undefined): string[] {
110
+ const out: string[] = [];
111
+ let cur = "";
112
+ let quoted = false;
113
+ let angle = 0;
114
+ for (const ch of v ?? "") {
115
+ if (ch === '"') quoted = !quoted;
116
+ else if (!quoted && ch === "<") angle++;
117
+ else if (!quoted && ch === ">") angle = Math.max(0, angle - 1);
118
+ if (ch === "," && !quoted && angle === 0) {
119
+ out.push(cur);
120
+ cur = "";
121
+ } else cur += ch;
122
+ }
123
+ out.push(cur);
124
+ return out.map((s) => s.trim()).filter(Boolean);
125
+ }
126
+
127
+ /** Bare lower-cased address of a header entry (`Name <a@b>` or `a@b`). */
128
+ function addressOf(entry: string): string {
129
+ const m = /<([^<>]+)>\s*$/.exec(entry);
130
+ return (m ? (m[1] as string) : entry).trim().toLowerCase();
131
+ }
132
+
133
+ function preview(body: string): string {
134
+ return body.length > PREVIEW_CHARS ? `${body.slice(0, PREVIEW_CHARS)}…` : body;
135
+ }
136
+
137
+ /** Confirm-prompt body: account, recipients, subject, attachments, ≤500-char preview. */
138
+ function messageLines(m: { account: string; to: string[]; cc?: string[]; bcc?: string[]; subject: string; files: string[]; body: string }) {
139
+ const opt = (label: string, list: string[] | undefined) => (list?.length ? [`${label}: ${list.join(", ")}`] : []);
140
+ return [
141
+ `Account: ${m.account}`,
142
+ `To: ${m.to.join(", ")}`,
143
+ ...opt("Cc", m.cc),
144
+ ...opt("Bcc", m.bcc),
145
+ `Subject: ${m.subject}`,
146
+ ...opt("Attachments", m.files),
147
+ "",
148
+ preview(m.body),
149
+ ];
150
+ }
151
+
152
+ async function confirmWrite(ctx: ToolContext | undefined, title: string, lines: string[]): Promise<void> {
153
+ if (!ctx?.hasUI || !ctx.ui) {
154
+ throw new GmailToolError("blocked", "blocked: this Gmail write needs user confirmation, but no UI is available");
155
+ }
156
+ let ok = false;
157
+ try {
158
+ ok = (await ctx.ui.confirm(title, lines.join("\n"))) === true;
159
+ } catch {
160
+ ok = false; // dismissed / timed out / transport error → deny
161
+ }
162
+ if (!ok) throw new GmailToolError("denied", "denied: the user did not approve this Gmail action");
163
+ }
164
+
165
+ export function createGmailTools(deps: GmailToolDeps): GmailToolDef[] {
166
+ const api = (l: LeaseReply) => new GmailApi(deps.endpoints.gmail, l.accessToken, deps.fetchImpl);
167
+
168
+ /** `account` present, or an error listing the connected accounts (no lease). */
169
+ async function requireAccount(params: Record<string, unknown>): Promise<string> {
170
+ const a = params.account;
171
+ if (typeof a === "string" && a.trim()) return a.trim();
172
+ let known = "none connected";
173
+ try {
174
+ const list = await deps.leases.accounts();
175
+ if (list.length) known = list.map((x) => (x.alias ? `${x.alias} (${x.email})` : x.email)).join(", ");
176
+ } catch {
177
+ known = "unavailable";
178
+ }
179
+ throw new GmailToolError("account_required", `account_required: pass \`account\` (alias or email). Connected accounts: ${known}`);
180
+ }
181
+
182
+ const withAccount =
183
+ (run: (account: string, p: Record<string, unknown>, ctx?: ToolContext) => Promise<ToolResult>) =>
184
+ async (_id: string, params: Record<string, unknown>, _s?: AbortSignal, _u?: unknown, ctx?: ToolContext) => {
185
+ const p = params ?? {};
186
+ return run(await requireAccount(p), p, ctx);
187
+ };
188
+
189
+ async function loadAttachments(ctx: ToolContext | undefined, paths: string[]): Promise<MimeAttachment[]> {
190
+ if (!paths.length) return [];
191
+ if (!ctx?.cwd) throw new GmailToolError("path_refused", "path_refused: no session working directory");
192
+ const cwd = ctx.cwd;
193
+ return Promise.all(
194
+ paths.map(async (p) => ({
195
+ filename: p.split(/[\\/]/).pop() || "attachment",
196
+ mimeType: "application/octet-stream",
197
+ data: await readInsideCwd(cwd, p),
198
+ })),
199
+ );
200
+ }
201
+
202
+ function messageSummary(m: GmailMessage) {
203
+ return {
204
+ id: m.id,
205
+ threadId: m.threadId,
206
+ from: header(m.payload, "From") ?? "",
207
+ subject: header(m.payload, "Subject") ?? "",
208
+ date: header(m.payload, "Date") ?? "",
209
+ snippet: m.snippet ?? "",
210
+ };
211
+ }
212
+
213
+ function compose(kind: "draft" | "send"): GmailToolDef {
214
+ const op: Op = kind;
215
+ return {
216
+ name: kind === "draft" ? "gmail_draft" : "gmail_send",
217
+ label: kind === "draft" ? "Gmail draft" : "Gmail send",
218
+ description:
219
+ kind === "draft"
220
+ ? "Create a Gmail draft in the given account (requires level draft). The user confirms first."
221
+ : "Send an email from the given account (requires level send). The user confirms first.",
222
+ parameters: {
223
+ type: "object",
224
+ properties: {
225
+ account: ACCOUNT_PROP,
226
+ to: { ...RECIPIENTS, minItems: 1, description: "Recipients" },
227
+ cc: { ...RECIPIENTS, description: "Cc recipients" },
228
+ bcc: { ...RECIPIENTS, description: "Bcc recipients" },
229
+ subject: { type: "string", maxLength: 998 },
230
+ body: { type: "string", description: "Plain-text body" },
231
+ attachments: ATTACH_PROP,
232
+ },
233
+ required: ["account", "to", "subject", "body"],
234
+ additionalProperties: false,
235
+ },
236
+ execute: withAccount(async (account, p, ctx) => {
237
+ const to = recipients(p.to, "to", 1);
238
+ const cc = recipients(p.cc, "cc", 0);
239
+ const bcc = recipients(p.bcc, "bcc", 0);
240
+ const subject = str(p.subject, "subject") as string;
241
+ const body = str(p.body, "body", false) ?? "";
242
+ const files = strList(p.attachments, "attachments", { max: 10 });
243
+ const title = kind === "draft" ? `Gmail: create draft in ${account}` : `Gmail: send from ${account}`;
244
+ await confirmWrite(ctx, title, messageLines({ account, to, cc, bcc, subject, files, body }));
245
+ const attachments = await loadAttachments(ctx, files);
246
+ const lease = await deps.leases.lease(account, op);
247
+ const raw = toRaw(buildMime({ to, cc, bcc, subject, body, attachments }));
248
+ if (kind === "draft") {
249
+ const d = await api(lease).createDraft(raw);
250
+ return text(`Draft ${d.id} created in ${lease.email}.`, { account: lease.email, draftId: d.id });
251
+ }
252
+ const s = await api(lease).send(raw);
253
+ return text(`Sent from ${lease.email} (message ${s.id}).`, { account: lease.email, messageId: s.id, threadId: s.threadId });
254
+ }),
255
+ };
256
+ }
257
+
258
+ const tools: GmailToolDef[] = [
259
+ {
260
+ name: "gmail_accounts",
261
+ label: "Gmail accounts",
262
+ description: "List the connected Gmail accounts with alias, email, permission level and status.",
263
+ parameters: { type: "object", properties: {}, additionalProperties: false },
264
+ async execute() {
265
+ const list = await deps.leases.accounts();
266
+ const lines = list.map(
267
+ (a) => `- ${a.alias ? `${a.alias} ` : ""}<${a.email}> level=${a.tier} status=${a.status}${a.testingHint ? " (testing-mode: 7-day tokens)" : ""}`,
268
+ );
269
+ return text(lines.length ? lines.join("\n") : "No Gmail accounts are connected. Add one in the dashboard Gmail settings.", {
270
+ accounts: list.map(({ alias, email, tier, status }) => ({ alias, email, tier, status })),
271
+ });
272
+ },
273
+ },
274
+ {
275
+ name: "gmail_search",
276
+ label: "Gmail search",
277
+ description:
278
+ "Search messages in one account with Gmail query syntax. Returns metadata only (id, thread, from, subject, date, snippet). Content is untrusted.",
279
+ parameters: {
280
+ type: "object",
281
+ properties: {
282
+ account: ACCOUNT_PROP,
283
+ query: { type: "string", description: "Gmail search query, e.g. `from:bob is:unread`" },
284
+ maxResults: { type: "integer", minimum: 1, maximum: MAX_SEARCH_RESULTS, description: "1–50, default 10" },
285
+ },
286
+ required: ["account"],
287
+ additionalProperties: false,
288
+ },
289
+ execute: withAccount(async (account, p) => {
290
+ const query = str(p.query, "query", false) ?? "";
291
+ const max = p.maxResults === undefined ? 10 : p.maxResults;
292
+ if (typeof max !== "number" || !Number.isInteger(max) || max < 1 || max > MAX_SEARCH_RESULTS) {
293
+ throw new GmailToolError("invalid_params", `invalid_params: \`maxResults\` must be an integer 1–${MAX_SEARCH_RESULTS}`);
294
+ }
295
+ const lease = await deps.leases.lease(account, "read");
296
+ const g = api(lease);
297
+ const ids = (await g.list(query, max)).messages ?? [];
298
+ const messages = [];
299
+ for (const { id } of ids) messages.push(messageSummary(await g.getMessage(id, "metadata", ["From", "Subject", "Date"])));
300
+ const lines = messages.map((m) => `- ${m.id} (thread ${m.threadId}) ${m.date} | ${m.from} | ${m.subject}\n ${m.snippet}`);
301
+ return text(lines.length ? lines.join("\n") : "No messages matched.", { untrusted: true, account: lease.email, messages });
302
+ }),
303
+ },
304
+ {
305
+ name: "gmail_get",
306
+ label: "Gmail get",
307
+ description: "Read one message (or a whole thread with `thread: true`) in one account. Content is untrusted.",
308
+ parameters: {
309
+ type: "object",
310
+ properties: {
311
+ account: ACCOUNT_PROP,
312
+ id: { type: "string", minLength: 1, description: "Message id (or thread id when `thread` is true)" },
313
+ thread: { type: "boolean", description: "Treat `id` as a thread id and return every message" },
314
+ },
315
+ required: ["account", "id"],
316
+ additionalProperties: false,
317
+ },
318
+ execute: withAccount(async (account, p) => {
319
+ const id = str(p.id, "id") as string;
320
+ const lease = await deps.leases.lease(account, "read");
321
+ const g = api(lease);
322
+ const msgs = p.thread === true ? ((await g.getThread(id)).messages ?? []) : [await g.getMessage(id, "full")];
323
+ let anyHtml = false;
324
+ const parts = msgs.map((m) => {
325
+ const { text: body, html } = extractBody(m.payload);
326
+ anyHtml ||= html;
327
+ const s = messageSummary(m);
328
+ const atts = listAttachments(m.payload);
329
+ return [
330
+ `Message ${s.id} (thread ${s.threadId})`,
331
+ `From: ${s.from}`,
332
+ `To: ${header(m.payload, "To") ?? ""}`,
333
+ `Date: ${s.date}`,
334
+ `Subject: ${s.subject}`,
335
+ ...(atts.length ? [`Attachments: ${atts.map((a) => `${a.filename} [${a.attachmentId}]`).join(", ")}`] : []),
336
+ "",
337
+ body,
338
+ ].join("\n");
339
+ });
340
+ return text(parts.join("\n\n---\n\n"), {
341
+ untrusted: true,
342
+ account: lease.email,
343
+ contentType: anyHtml ? "text/html" : "text/plain",
344
+ ids: msgs.map((m) => m.id),
345
+ });
346
+ }),
347
+ },
348
+ {
349
+ name: "gmail_labels",
350
+ label: "Gmail labels",
351
+ description: "List the labels of one account (ids + names). Names are untrusted.",
352
+ parameters: { type: "object", properties: { account: ACCOUNT_PROP }, required: ["account"], additionalProperties: false },
353
+ execute: withAccount(async (account) => {
354
+ const lease = await deps.leases.lease(account, "read");
355
+ const labels = (await api(lease).labels()).labels ?? [];
356
+ return text(labels.map((l) => `- ${l.id}: ${l.name}`).join("\n") || "No labels.", {
357
+ untrusted: true,
358
+ account: lease.email,
359
+ labels,
360
+ });
361
+ }),
362
+ },
363
+ {
364
+ name: "gmail_attachments",
365
+ label: "Gmail attachments",
366
+ description:
367
+ "List a message's attachments, or save one (`attachmentId` + `saveAs`) inside the session working directory. Never overwrites. Content is untrusted.",
368
+ parameters: {
369
+ type: "object",
370
+ properties: {
371
+ account: ACCOUNT_PROP,
372
+ messageId: { type: "string", minLength: 1 },
373
+ attachmentId: { type: "string", minLength: 1 },
374
+ saveAs: { type: "string", minLength: 1, description: "Relative path inside the session cwd" },
375
+ },
376
+ required: ["account", "messageId"],
377
+ additionalProperties: false,
378
+ },
379
+ execute: withAccount(async (account, p, ctx) => {
380
+ const messageId = str(p.messageId, "messageId") as string;
381
+ const attachmentId = str(p.attachmentId, "attachmentId", false);
382
+ const saveAs = str(p.saveAs, "saveAs", false);
383
+ if ((attachmentId === undefined) !== (saveAs === undefined)) {
384
+ throw new GmailToolError("invalid_params", "invalid_params: pass both `attachmentId` and `saveAs` to save, or neither to list");
385
+ }
386
+ if (saveAs !== undefined && !ctx?.cwd) throw new GmailToolError("path_refused", "path_refused: no session working directory");
387
+ const lease = await deps.leases.lease(account, "read");
388
+ const g = api(lease);
389
+ if (attachmentId === undefined || saveAs === undefined) {
390
+ const atts = listAttachments((await g.getMessage(messageId, "full")).payload);
391
+ return text(atts.map((a) => `- ${a.attachmentId}: ${a.filename} (${a.mimeType}, ${a.size} B)`).join("\n") || "No attachments.", {
392
+ untrusted: true,
393
+ account: lease.email,
394
+ attachments: atts,
395
+ });
396
+ }
397
+ const att = await g.attachment(messageId, attachmentId);
398
+ const data = att.data ?? "";
399
+ if ((att.size ?? 0) > MAX_ATTACH_BYTES || data.length > Math.ceil((MAX_ATTACH_BYTES * 4) / 3) + 4) {
400
+ throw new GmailToolError("too_large", "too_large: attachment exceeds the 20 MiB save limit");
401
+ }
402
+ const written = await saveInsideCwd(ctx?.cwd as string, saveAs, Buffer.from(data, "base64url"));
403
+ return text(`Saved attachment to ${written}.`, { untrusted: true, account: lease.email, path: written });
404
+ }),
405
+ },
406
+ compose("draft"),
407
+ compose("send"),
408
+ {
409
+ name: "gmail_reply",
410
+ label: "Gmail reply",
411
+ description: "Reply in-thread to a message (requires level send). The user confirms first.",
412
+ parameters: {
413
+ type: "object",
414
+ properties: {
415
+ account: ACCOUNT_PROP,
416
+ messageId: { type: "string", minLength: 1 },
417
+ body: { type: "string" },
418
+ replyAll: { type: "boolean" },
419
+ attachments: ATTACH_PROP,
420
+ },
421
+ required: ["account", "messageId", "body"],
422
+ additionalProperties: false,
423
+ },
424
+ execute: withAccount(async (account, p, ctx) => {
425
+ const messageId = str(p.messageId, "messageId") as string;
426
+ const body = str(p.body, "body", false) ?? "";
427
+ const files = strList(p.attachments, "attachments", { max: 10 });
428
+ const readLease = await deps.leases.lease(account, "read");
429
+ const orig = await api(readLease).getMessage(messageId, "metadata", [
430
+ "Message-ID",
431
+ "References",
432
+ "Subject",
433
+ "From",
434
+ "Reply-To",
435
+ "To",
436
+ "Cc",
437
+ ]);
438
+ const self = readLease.email.toLowerCase();
439
+ const origId = header(orig.payload, "Message-ID");
440
+ const replyTo = header(orig.payload, "Reply-To") ?? header(orig.payload, "From") ?? "";
441
+ const to = [replyTo];
442
+ const cc =
443
+ p.replyAll === true
444
+ ? [...splitAddresses(header(orig.payload, "To")), ...splitAddresses(header(orig.payload, "Cc"))].filter(
445
+ // Exact address match — a substring test would drop `lisa@x.com` for `a@x.com`.
446
+ (a) => addressOf(a) !== self && addressOf(a) !== addressOf(replyTo),
447
+ )
448
+ : [];
449
+ const subj = header(orig.payload, "Subject") ?? "";
450
+ const subject = /^re:/i.test(subj) ? subj : `Re: ${subj}`;
451
+ const references = [header(orig.payload, "References"), origId].filter(Boolean).join(" ") || undefined;
452
+ await confirmWrite(ctx, `Gmail: reply from ${account}`, messageLines({ account, to, cc, subject, files, body }));
453
+ const attachments = await loadAttachments(ctx, files);
454
+ // Fresh send lease AFTER the confirm: a level lowered while the prompt
455
+ // was open must refuse, and the token must not have aged out.
456
+ const lease = await deps.leases.lease(account, "send");
457
+ const raw = toRaw(buildMime({ to, cc, subject, body, inReplyTo: origId, references, attachments }));
458
+ const s = await api(lease).send(raw, orig.threadId);
459
+ return text(`Replied from ${lease.email} (message ${s.id}, thread ${s.threadId}).`, {
460
+ account: lease.email,
461
+ messageId: s.id,
462
+ threadId: s.threadId,
463
+ });
464
+ }),
465
+ },
466
+ {
467
+ name: "gmail_modify",
468
+ label: "Gmail modify labels",
469
+ description:
470
+ "Add/remove label ids on messages (e.g. remove INBOX to archive, add STARRED) — requires level send. The user confirms first.",
471
+ parameters: {
472
+ type: "object",
473
+ properties: {
474
+ account: ACCOUNT_PROP,
475
+ ids: { type: "array", items: { type: "string", minLength: 1 }, minItems: 1, maxItems: 100 },
476
+ addLabels: { type: "array", items: { type: "string", minLength: 1 }, maxItems: 20 },
477
+ removeLabels: { type: "array", items: { type: "string", minLength: 1 }, maxItems: 20 },
478
+ },
479
+ required: ["account", "ids"],
480
+ additionalProperties: false,
481
+ },
482
+ execute: withAccount(async (account, p, ctx) => {
483
+ const ids = strList(p.ids, "ids", { min: 1, max: 100 });
484
+ const add = strList(p.addLabels, "addLabels", { max: 20 });
485
+ const remove = strList(p.removeLabels, "removeLabels", { max: 20 });
486
+ if (!add.length && !remove.length) {
487
+ throw new GmailToolError("invalid_params", "invalid_params: pass `addLabels` and/or `removeLabels`");
488
+ }
489
+ await confirmWrite(ctx, `Gmail: change labels in ${account}`, [
490
+ `Account: ${account}`,
491
+ `Messages: ${ids.length}`,
492
+ ...(add.length ? [`Add: ${add.join(", ")}`] : []),
493
+ ...(remove.length ? [`Remove: ${remove.join(", ")}`] : []),
494
+ ]);
495
+ const lease = await deps.leases.lease(account, "modify");
496
+ await api(lease).modify(ids, add, remove);
497
+ return text(`Updated labels on ${ids.length} message(s) in ${lease.email}.`, { account: lease.email, ids });
498
+ }),
499
+ },
500
+ {
501
+ name: "gmail_trash",
502
+ label: "Gmail trash",
503
+ description: "Move messages to Trash (requires level send). The user confirms first.",
504
+ parameters: {
505
+ type: "object",
506
+ properties: {
507
+ account: ACCOUNT_PROP,
508
+ ids: { type: "array", items: { type: "string", minLength: 1 }, minItems: 1, maxItems: 100 },
509
+ },
510
+ required: ["account", "ids"],
511
+ additionalProperties: false,
512
+ },
513
+ execute: withAccount(async (account, p, ctx) => {
514
+ const ids = strList(p.ids, "ids", { min: 1, max: 100 });
515
+ await confirmWrite(ctx, `Gmail: move to Trash in ${account}`, [`Account: ${account}`, `Messages: ${ids.length}`]);
516
+ const lease = await deps.leases.lease(account, "trash");
517
+ const g = api(lease);
518
+ for (const id of ids) await g.trash(id);
519
+ return text(`Moved ${ids.length} message(s) to Trash in ${lease.email}.`, { account: lease.email, ids });
520
+ }),
521
+ },
522
+ ];
523
+ return tools;
524
+ }