@blackbelt-technology/pi-dashboard-gmail-plugin 0.9.0 → 0.11.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/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-gmail-plugin",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Multi-account Gmail for pi agents — guided Google OAuth setup, per-account permission levels, server-side token leasing and account-scoped Gmail tools with confirmed writes.",
5
+ "keywords": [
6
+ "pi-dashboard-plugin"
7
+ ],
5
8
  "license": "MIT",
6
9
  "publishConfig": {
7
10
  "access": "public"
@@ -61,14 +64,16 @@
61
64
  "react-dom": ">=18.0.0"
62
65
  },
63
66
  "dependencies": {
64
- "@blackbelt-technology/dashboard-plugin-runtime": "^0.9.0",
65
- "@blackbelt-technology/pi-dashboard-shared": "^0.9.0",
67
+ "@blackbelt-technology/dashboard-plugin-runtime": "^0.11.0",
68
+ "@blackbelt-technology/pi-dashboard-shared": "^0.11.0",
66
69
  "@fastify/rate-limit": "^11.2.0",
67
- "oauth4webapi": "^3.8.8"
70
+ "oauth4webapi": "^3.8.8",
71
+ "ws": "^8.18.0"
68
72
  },
69
73
  "devDependencies": {
70
74
  "@types/react": "^19.0.0",
71
75
  "@types/react-dom": "^19.0.0",
76
+ "@types/ws": "^8.18.1",
72
77
  "react": "^19.0.0",
73
78
  "react-dom": "^19.0.0"
74
79
  }
@@ -17,7 +17,9 @@ import { isPathInside } from "@blackbelt-technology/pi-dashboard-shared/path-con
17
17
  export const MAX_ATTACH_BYTES = 20 * 1024 * 1024;
18
18
 
19
19
  class PathRefusedError extends Error {
20
- constructor(readonly code: "path_refused" | "exists" | "too_large") {
20
+ readonly code: "path_refused" | "exists" | "too_large";
21
+
22
+ constructor(code: "path_refused" | "exists" | "too_large") {
21
23
  super(
22
24
  code === "exists"
23
25
  ? "path_refused: target already exists (attachments never overwrite)"
@@ -25,6 +27,7 @@ class PathRefusedError extends Error {
25
27
  ? "path_refused: file exceeds the 20 MiB attachment limit"
26
28
  : "path_refused: path must stay inside the session working directory",
27
29
  );
30
+ this.code = code;
28
31
  this.name = "PathRefusedError";
29
32
  }
30
33
  }
@@ -33,12 +33,27 @@ export interface GmailMessage {
33
33
  payload?: GmailPart;
34
34
  }
35
35
 
36
+ /** A Gmail filter (`users.settings.filters`): criteria + label actions only are ever sent. */
37
+ export interface GmailFilter {
38
+ id: string;
39
+ criteria?: Record<string, unknown>;
40
+ action?: { addLabelIds?: string[]; removeLabelIds?: string[]; forward?: string };
41
+ }
42
+
36
43
  export class GmailApi {
44
+ private readonly base: string;
45
+ private readonly token: string;
46
+ private readonly fetchImpl: typeof fetch;
47
+
37
48
  constructor(
38
- private readonly base: string,
39
- private readonly token: string,
40
- private readonly fetchImpl: typeof fetch = fetch,
41
- ) {}
49
+ base: string,
50
+ token: string,
51
+ fetchImpl: typeof fetch = fetch,
52
+ ) {
53
+ this.base = base;
54
+ this.token = token;
55
+ this.fetchImpl = fetchImpl;
56
+ }
42
57
 
43
58
  private async call<T>(method: string, pathAndQuery: string, body?: unknown): Promise<T> {
44
59
  let res: Response;
@@ -117,6 +132,22 @@ export class GmailApi {
117
132
  trash(id: string) {
118
133
  return this.call<unknown>("POST", `messages/${encodeURIComponent(id)}/trash`);
119
134
  }
135
+
136
+ listFilters() {
137
+ return this.call<{ filter?: GmailFilter[] }>("GET", "settings/filters");
138
+ }
139
+
140
+ getFilter(id: string) {
141
+ return this.call<GmailFilter>("GET", `settings/filters/${encodeURIComponent(id)}`);
142
+ }
143
+
144
+ createFilter(criteria: Record<string, unknown>, action: Record<string, unknown>) {
145
+ return this.call<GmailFilter>("POST", "settings/filters", { criteria, action });
146
+ }
147
+
148
+ deleteFilter(id: string) {
149
+ return this.call<unknown>("DELETE", `settings/filters/${encodeURIComponent(id)}`);
150
+ }
120
151
  }
121
152
 
122
153
  const GMAIL_403 = () => new GmailToolError("gmail_error", "gmail_error: Gmail returned HTTP 403");
@@ -15,11 +15,14 @@ import { isTier, type Op, tierAllows } from "../shared/scopes.js";
15
15
  export type LaneRequest = (pluginId: string, type: string, payload?: unknown) => Promise<PluginLaneReply>;
16
16
 
17
17
  export class GmailToolError extends Error {
18
+ readonly code: string;
19
+
18
20
  constructor(
19
- readonly code: string,
21
+ code: string,
20
22
  message: string,
21
23
  ) {
22
24
  super(message);
25
+ this.code = code;
23
26
  this.name = "GmailToolError";
24
27
  }
25
28
  }
@@ -34,7 +37,11 @@ function laneError(error: string): GmailToolError {
34
37
  }
35
38
 
36
39
  export class LeaseClient {
37
- constructor(private readonly request: LaneRequest = requestPluginServer) {}
40
+ private readonly request: LaneRequest;
41
+
42
+ constructor(request: LaneRequest = requestPluginServer) {
43
+ this.request = request;
44
+ }
38
45
 
39
46
  async lease(account: string, op: Op): Promise<LeaseReply> {
40
47
  const reply = await this.request(PLUGIN_ID, LEASE_TYPE, { account, op });
@@ -13,15 +13,23 @@
13
13
  * See change: add-gmail-plugin.
14
14
  */
15
15
  import type { GoogleEndpoints } from "../shared/endpoints.js";
16
- import type { LeaseReply } from "../shared/protocol.js";
17
- import type { Op } from "../shared/scopes.js";
16
+ import type { AccountInfo, LeaseReply } from "../shared/protocol.js";
17
+ import { type Op, tierAllows } from "../shared/scopes.js";
18
18
  import { MAX_ATTACH_BYTES, readInsideCwd, saveInsideCwd } from "./attachments.js";
19
- import { extractBody, GmailApi, type GmailMessage, header, listAttachments } from "./gmail-api.js";
19
+ import { extractBody, GmailApi, type GmailFilter, type GmailMessage, header, listAttachments } from "./gmail-api.js";
20
20
  import { GmailToolError, type LeaseClient } from "./lease-client.js";
21
21
  import { buildMime, type MimeAttachment, toRaw } from "./mime.js";
22
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;
23
+ export const READ_TOOLS = ["gmail_search", "gmail_get", "gmail_labels", "gmail_attachments", "gmail_filters_list"] as const;
24
+ export const WRITE_TOOLS = [
25
+ "gmail_draft",
26
+ "gmail_send",
27
+ "gmail_reply",
28
+ "gmail_modify",
29
+ "gmail_trash",
30
+ "gmail_filter_create",
31
+ "gmail_filter_delete",
32
+ ] as const;
25
33
 
26
34
  const MAX_SEARCH_RESULTS = 50;
27
35
  const PREVIEW_CHARS = 500;
@@ -149,19 +157,98 @@ function messageLines(m: { account: string; to: string[]; cc?: string[]; bcc?: s
149
157
  ];
150
158
  }
151
159
 
152
- async function confirmWrite(ctx: ToolContext | undefined, title: string, lines: string[]): Promise<void> {
160
+ /** A confirmed write needs an interactive UI; checked before anything reaches Google. */
161
+ function assertInteractive(ctx: ToolContext | undefined): void {
153
162
  if (!ctx?.hasUI || !ctx.ui) {
154
163
  throw new GmailToolError("blocked", "blocked: this Gmail write needs user confirmation, but no UI is available");
155
164
  }
165
+ }
166
+
167
+ async function confirmWrite(ctx: ToolContext | undefined, title: string, lines: string[]): Promise<void> {
168
+ assertInteractive(ctx);
169
+ const ui = (ctx as ToolContext).ui as NonNullable<ToolContext["ui"]>;
156
170
  let ok = false;
157
171
  try {
158
- ok = (await ctx.ui.confirm(title, lines.join("\n"))) === true;
172
+ ok = (await ui.confirm(title, lines.join("\n"))) === true;
159
173
  } catch {
160
174
  ok = false; // dismissed / timed out / transport error → deny
161
175
  }
162
176
  if (!ok) throw new GmailToolError("denied", "denied: the user did not approve this Gmail action");
163
177
  }
164
178
 
179
+ const CRITERIA_STRING_KEYS = ["from", "to", "subject", "query", "negatedQuery"] as const;
180
+ const CRITERIA_KEYS: readonly string[] = [...CRITERIA_STRING_KEYS, "hasAttachment"];
181
+ const ACTION_KEYS: readonly string[] = ["addLabelIds", "removeLabelIds"];
182
+ const FORBIDDEN_ADD_LABELS = new Set(["TRASH", "SPAM"]);
183
+
184
+ const isPlain = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
185
+ const isForwardKey = (k: string) => k.toLowerCase().startsWith("forward");
186
+ const invalidFilter = (why: string) => new GmailToolError("invalid_filter", `invalid_filter: ${why}`);
187
+
188
+ interface FilterSpec {
189
+ criteria: Record<string, string | true>;
190
+ action: { addLabelIds?: string[]; removeLabelIds?: string[] };
191
+ }
192
+
193
+ /**
194
+ * Fail-closed allow-list for `gmail_filter_create`, run before any account
195
+ * check, confirm, lease or request: label actions only, no forwarding, no
196
+ * blank / `*` / match-all criteria, no TRASH/SPAM additions.
197
+ */
198
+ export function parseFilterSpec(p: Record<string, unknown>): FilterSpec {
199
+ const sections: Array<[string, unknown]> = [["request", p], ["criteria", p.criteria], ["filterAction", p.filterAction]];
200
+ for (const [, obj] of sections) {
201
+ if (isPlain(obj) && Object.keys(obj).some(isForwardKey)) {
202
+ throw new GmailToolError("forward_refused", "forward_refused: forwarding filters are not supported");
203
+ }
204
+ }
205
+ const extra = Object.keys(p).filter((k) => !["account", "criteria", "filterAction"].includes(k));
206
+ if (extra.length) throw invalidFilter(`unsupported field \`${extra[0]}\``);
207
+ if (!isPlain(p.criteria)) throw invalidFilter("`criteria` must be an object");
208
+ if (!isPlain(p.filterAction)) throw invalidFilter("`filterAction` must be an object");
209
+
210
+ const criteria: Record<string, string | true> = {};
211
+ for (const [k, v] of Object.entries(p.criteria)) {
212
+ if (!CRITERIA_KEYS.includes(k)) throw invalidFilter(`unsupported criteria field \`${k}\``);
213
+ if (k === "hasAttachment") {
214
+ if (typeof v !== "boolean") throw invalidFilter("`hasAttachment` must be a boolean");
215
+ if (v) criteria[k] = true;
216
+ } else {
217
+ if (typeof v !== "string") throw invalidFilter(`criteria \`${k}\` must be a string`);
218
+ const t = v.trim();
219
+ if (t && t !== "*") criteria[k] = t;
220
+ }
221
+ }
222
+ if (!Object.keys(criteria).length) throw invalidFilter("at least one non-blank criterion (not `*`) is required");
223
+
224
+ const action: FilterSpec["action"] = {};
225
+ for (const [k, v] of Object.entries(p.filterAction)) {
226
+ if (!ACTION_KEYS.includes(k)) throw invalidFilter(`unsupported action field \`${k}\``);
227
+ if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) throw invalidFilter(`\`${k}\` must be a list of label ids`);
228
+ const ids = (v as string[]).map((x) => x.trim()).filter(Boolean);
229
+ if (k === "addLabelIds" && ids.some((x) => FORBIDDEN_ADD_LABELS.has(x.toUpperCase()))) {
230
+ throw invalidFilter("a filter must not add the TRASH or SPAM label");
231
+ }
232
+ if (ids.length) action[k as "addLabelIds" | "removeLabelIds"] = ids;
233
+ }
234
+ if (!action.addLabelIds?.length && !action.removeLabelIds?.length) throw invalidFilter("at least one label id to add or remove is required");
235
+ return { criteria, action };
236
+ }
237
+
238
+ function describeCriteria(c: Record<string, unknown> | undefined): string {
239
+ const parts = Object.entries(c ?? {}).map(([k, v]) => `${k}=${typeof v === "string" ? v : String(v)}`);
240
+ return parts.length ? parts.join(", ") : "(none)";
241
+ }
242
+
243
+ function describeAction(a: GmailFilter["action"]): string {
244
+ const parts = [
245
+ ...(a?.addLabelIds?.length ? [`add labels ${a.addLabelIds.join(", ")}`] : []),
246
+ ...(a?.removeLabelIds?.length ? [`remove labels ${a.removeLabelIds.join(", ")}`] : []),
247
+ ...(a?.forward ? ["forward (not supported by this tool)"] : []),
248
+ ];
249
+ return parts.length ? parts.join("; ") : "(none)";
250
+ }
251
+
165
252
  export function createGmailTools(deps: GmailToolDeps): GmailToolDef[] {
166
253
  const api = (l: LeaseReply) => new GmailApi(deps.endpoints.gmail, l.accessToken, deps.fetchImpl);
167
254
 
@@ -186,6 +273,33 @@ export function createGmailTools(deps: GmailToolDeps): GmailToolDef[] {
186
273
  return run(await requireAccount(p), p, ctx);
187
274
  };
188
275
 
276
+ /**
277
+ * Resolve `ref` (alias or email) against the secret-free account list and
278
+ * refuse a filter call the server would refuse anyway — BEFORE any confirm,
279
+ * lease or request. The lease stays authoritative.
280
+ */
281
+ async function filterPrecheck(ref: string, op: "filters_read" | "filters_write"): Promise<AccountInfo> {
282
+ const list = await deps.leases.accounts();
283
+ const key = ref.trim().toLowerCase();
284
+ const hits = list.filter((a) => a.alias?.toLowerCase() === key || a.email.toLowerCase() === key);
285
+ if (hits.length === 0) {
286
+ const known = list.map((x) => (x.alias ? `${x.alias} (${x.email})` : x.email)).join(", ") || "none connected";
287
+ throw new GmailToolError("not_found", `not_found: no connected account matches "${ref}". Connected accounts: ${known}`);
288
+ }
289
+ if (hits.length > 1) throw new GmailToolError("ambiguous", `ambiguous: "${ref}" matches several accounts; use an alias`);
290
+ const acct = hits[0] as AccountInfo;
291
+ if (acct.filters !== true) {
292
+ throw new GmailToolError(
293
+ "filters_disabled",
294
+ `filters_disabled: filters are not enabled for ${acct.email}; turn them on for this account in the Gmail settings`,
295
+ );
296
+ }
297
+ if (!tierAllows(acct.tier, op)) {
298
+ throw new GmailToolError("tier_denied", `tier_denied: ${acct.email} is at level "${acct.tier}", which does not allow "${op}"`);
299
+ }
300
+ return acct;
301
+ }
302
+
189
303
  async function loadAttachments(ctx: ToolContext | undefined, paths: string[]): Promise<MimeAttachment[]> {
190
304
  if (!paths.length) return [];
191
305
  if (!ctx?.cwd) throw new GmailToolError("path_refused", "path_refused: no session working directory");
@@ -264,10 +378,10 @@ export function createGmailTools(deps: GmailToolDeps): GmailToolDef[] {
264
378
  async execute() {
265
379
  const list = await deps.leases.accounts();
266
380
  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)" : ""}`,
381
+ (a) => `- ${a.alias ? `${a.alias} ` : ""}<${a.email}> level=${a.tier} status=${a.status}${a.filters ? " filters=on" : ""}${a.testingHint ? " (testing-mode: 7-day tokens)" : ""}`,
268
382
  );
269
383
  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 })),
384
+ accounts: list.map(({ alias, email, tier, status, filters }) => ({ alias, email, tier, status, ...(filters ? { filters } : {}) })),
271
385
  });
272
386
  },
273
387
  },
@@ -403,6 +517,100 @@ export function createGmailTools(deps: GmailToolDeps): GmailToolDef[] {
403
517
  return text(`Saved attachment to ${written}.`, { untrusted: true, account: lease.email, path: written });
404
518
  }),
405
519
  },
520
+ {
521
+ name: "gmail_filters_list",
522
+ label: "Gmail filters",
523
+ description: "List the filters of one account (needs the account's filters option on). Content is untrusted.",
524
+ parameters: { type: "object", properties: { account: ACCOUNT_PROP }, required: ["account"], additionalProperties: false },
525
+ execute: withAccount(async (account) => {
526
+ await filterPrecheck(account, "filters_read");
527
+ const lease = await deps.leases.lease(account, "filters_read");
528
+ const filters = (await api(lease).listFilters()).filter ?? [];
529
+ const lines = filters.map((f) => `- ${f.id}: if ${describeCriteria(f.criteria)} → ${describeAction(f.action)}`);
530
+ return text(lines.length ? lines.join("\n") : "No filters.", { untrusted: true, account: lease.email, filters });
531
+ }),
532
+ },
533
+ {
534
+ name: "gmail_filter_create",
535
+ label: "Gmail filter create",
536
+ description:
537
+ "Create a Gmail filter that applies label actions (e.g. remove INBOX to archive) to ALL future matching mail. Needs the account's filters option on and level send. Forwarding is not supported. The user confirms first.",
538
+ parameters: {
539
+ type: "object",
540
+ properties: {
541
+ account: ACCOUNT_PROP,
542
+ criteria: {
543
+ type: "object",
544
+ description: "At least one non-blank criterion",
545
+ properties: {
546
+ from: { type: "string" },
547
+ to: { type: "string" },
548
+ subject: { type: "string" },
549
+ query: { type: "string" },
550
+ negatedQuery: { type: "string" },
551
+ hasAttachment: { type: "boolean" },
552
+ },
553
+ additionalProperties: false,
554
+ },
555
+ filterAction: {
556
+ type: "object",
557
+ description: "Label ids to add or remove (never TRASH/SPAM additions)",
558
+ properties: {
559
+ addLabelIds: { type: "array", items: { type: "string", minLength: 1 } },
560
+ removeLabelIds: { type: "array", items: { type: "string", minLength: 1 } },
561
+ },
562
+ additionalProperties: false,
563
+ },
564
+ },
565
+ required: ["account", "criteria", "filterAction"],
566
+ additionalProperties: false,
567
+ },
568
+ // Order: validate → account-summary pre-check → no-UI check → confirm → write lease → REST.
569
+ execute: withAccount(async (account, p, ctx) => {
570
+ const spec = parseFilterSpec(p);
571
+ await filterPrecheck(account, "filters_write");
572
+ assertInteractive(ctx);
573
+ await confirmWrite(ctx, `Gmail: create filter in ${account}`, [
574
+ `Account: ${account}`,
575
+ `Criteria: ${describeCriteria(spec.criteria)}`,
576
+ `Actions: ${describeAction(spec.action)}`,
577
+ "",
578
+ "This filter applies to all future matching mail.",
579
+ ]);
580
+ const lease = await deps.leases.lease(account, "filters_write");
581
+ const f = await api(lease).createFilter(spec.criteria, spec.action);
582
+ return text(`Filter ${f.id} created in ${lease.email}.`, { account: lease.email, filterId: f.id });
583
+ }),
584
+ },
585
+ {
586
+ name: "gmail_filter_delete",
587
+ label: "Gmail filter delete",
588
+ description:
589
+ "Delete a Gmail filter by id (needs the account's filters option on and level send). The user confirms first, seeing the filter's criteria and actions.",
590
+ parameters: {
591
+ type: "object",
592
+ properties: { account: ACCOUNT_PROP, id: { type: "string", minLength: 1, description: "Filter id (from gmail_filters_list)" } },
593
+ required: ["account", "id"],
594
+ additionalProperties: false,
595
+ },
596
+ // Order: validate → pre-check → no-UI check → read lease + GET → confirm → write lease → DELETE.
597
+ execute: withAccount(async (account, p, ctx) => {
598
+ const id = str(p.id, "id") as string;
599
+ await filterPrecheck(account, "filters_write");
600
+ assertInteractive(ctx);
601
+ const readLease = await deps.leases.lease(account, "filters_read");
602
+ const filter = await api(readLease).getFilter(id);
603
+ await confirmWrite(ctx, `Gmail: delete filter in ${account}`, [
604
+ `Account: ${account}`,
605
+ `Filter: ${filter.id ?? id}`,
606
+ `Criteria: ${describeCriteria(filter.criteria)}`,
607
+ `Actions: ${describeAction(filter.action)}`,
608
+ ]);
609
+ const lease = await deps.leases.lease(account, "filters_write");
610
+ await api(lease).deleteFilter(id);
611
+ return text(`Filter ${id} deleted in ${lease.email}.`, { account: lease.email, filterId: id });
612
+ }),
613
+ },
406
614
  compose("draft"),
407
615
  compose("send"),
408
616
  {