@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.1

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 (67) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1185 -34
  3. package/dist/cli.js +15 -12
  4. package/dist/core/credentials.d.ts +21 -0
  5. package/dist/core/credentials.js +45 -0
  6. package/dist/core/origins.d.ts +18 -0
  7. package/dist/core/origins.js +40 -0
  8. package/dist/core/upload-hosts.d.ts +15 -0
  9. package/dist/core/upload-hosts.js +43 -0
  10. package/dist/host/describe.d.ts +10 -0
  11. package/dist/host/describe.js +38 -0
  12. package/dist/host/env.d.ts +25 -2
  13. package/dist/host/env.js +24 -7
  14. package/dist/host/guarded-fetch.d.ts +36 -9
  15. package/dist/host/guarded-fetch.js +175 -52
  16. package/dist/host/index.d.ts +8 -5
  17. package/dist/host/index.js +12 -1
  18. package/dist/host/load.js +31 -1
  19. package/dist/host/server.d.ts +13 -2
  20. package/dist/host/server.js +15 -2
  21. package/dist/types.d.ts +96 -5
  22. package/dist/vendors/adapty.js +1303 -0
  23. package/dist/vendors/adjust.js +1372 -0
  24. package/dist/vendors/apollo.js +2499 -0
  25. package/dist/vendors/apple-appstore.js +2798 -0
  26. package/dist/vendors/beehiiv.js +1965 -0
  27. package/dist/vendors/blogger.js +1687 -0
  28. package/dist/vendors/bluesky.js +850 -127
  29. package/dist/vendors/brevo.js +2195 -0
  30. package/dist/vendors/calendarific.js +1116 -0
  31. package/dist/vendors/devto.js +685 -92
  32. package/dist/vendors/facebook-pages.js +2185 -0
  33. package/dist/vendors/firebase.js +1333 -0
  34. package/dist/vendors/ga4.js +1585 -0
  35. package/dist/vendors/gmail.js +1962 -0
  36. package/dist/vendors/google-ads.js +2201 -0
  37. package/dist/vendors/google-business.js +1621 -0
  38. package/dist/vendors/google-calendar.js +1936 -0
  39. package/dist/vendors/google-drive.js +2654 -0
  40. package/dist/vendors/google-merchant-center.js +1742 -0
  41. package/dist/vendors/google-play.js +1856 -0
  42. package/dist/vendors/google-search-console.js +1572 -0
  43. package/dist/vendors/hashnode.js +1722 -0
  44. package/dist/vendors/instagram.js +2249 -0
  45. package/dist/vendors/kaggle.js +2043 -0
  46. package/dist/vendors/keepa.js +2087 -0
  47. package/dist/vendors/linkedin.js +1588 -0
  48. package/dist/vendors/mailchimp.js +2402 -0
  49. package/dist/vendors/mastodon.js +1836 -0
  50. package/dist/vendors/meta-ads.js +2375 -0
  51. package/dist/vendors/notion.js +1950 -0
  52. package/dist/vendors/pinterest.js +1744 -0
  53. package/dist/vendors/qiita.js +1552 -0
  54. package/dist/vendors/reddit.js +1791 -0
  55. package/dist/vendors/revenuecat.js +1593 -0
  56. package/dist/vendors/roasit.js +1460 -0
  57. package/dist/vendors/sendgrid.js +2188 -0
  58. package/dist/vendors/serper.js +901 -179
  59. package/dist/vendors/shopify.js +2511 -0
  60. package/dist/vendors/threads.js +1869 -0
  61. package/dist/vendors/tiktok.js +2199 -0
  62. package/dist/vendors/tumblr.js +1793 -0
  63. package/dist/vendors/twitter.js +1650 -0
  64. package/dist/vendors/woocommerce.js +2258 -0
  65. package/dist/vendors/wordpress.js +1904 -0
  66. package/dist/vendors/youtube.js +2542 -0
  67. package/package.json +12 -1
@@ -0,0 +1,1962 @@
1
+ /* gmail connector module (MIT License). Built from src/vendors/gmail; do not edit. */
2
+ "use strict";
3
+
4
+ // src/core/errors.ts
5
+ var ToolFailure = class extends Error {
6
+ details;
7
+ constructor(message, details = {}) {
8
+ super(message);
9
+ this.name = "ToolFailure";
10
+ this.details = details;
11
+ }
12
+ };
13
+ var OutcomeUnknown = class extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "OutcomeUnknown";
17
+ }
18
+ };
19
+
20
+ // src/core/accounts.ts
21
+ function allowedAccounts(accounts, key) {
22
+ if (accounts === null) return null;
23
+ const list = accounts?.[key];
24
+ return Array.isArray(list) ? list.map(String) : [];
25
+ }
26
+ function requireAccounts(accounts, key, ids, label = "account") {
27
+ const allowed = allowedAccounts(accounts, key);
28
+ if (allowed === null) return;
29
+ const requested = (Array.isArray(ids) ? ids : [ids]).map(String);
30
+ const refused = requested.filter((id) => !allowed.includes(id));
31
+ if (!refused.length) return;
32
+ throw new ToolFailure(
33
+ `The ${label} ${refused.join(", ")} ${refused.length > 1 ? "are" : "is"} not among the ${label}s chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`) + " Nothing was sent."
34
+ );
35
+ }
36
+
37
+ // src/core/text.ts
38
+ var encoder = new TextEncoder();
39
+ var decoder = new TextDecoder();
40
+ function utf8Bytes(text2) {
41
+ return encoder.encode(text2);
42
+ }
43
+ function utf8Length(text2) {
44
+ return encoder.encode(text2).length;
45
+ }
46
+ function utf8Decode(bytes) {
47
+ return decoder.decode(bytes);
48
+ }
49
+ function base64Encode(bytes) {
50
+ let binary = "";
51
+ for (let i = 0; i < bytes.length; i += 32768) {
52
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
53
+ }
54
+ return btoa(binary);
55
+ }
56
+ function base64UrlEncode(bytes) {
57
+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
58
+ }
59
+ function base64UrlDecode(text2) {
60
+ if (!/^[A-Za-z0-9_-]*$/.test(text2)) throw new Error("not base64url");
61
+ const padded = text2.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text2.length + 3) % 4);
62
+ const binary = atob(padded);
63
+ const bytes = new Uint8Array(binary.length);
64
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
65
+ return bytes;
66
+ }
67
+ function truncate(text2, max) {
68
+ if (text2.length <= max) return text2;
69
+ const points = Array.from(text2);
70
+ if (points.length <= max) return text2;
71
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
72
+ }
73
+ function cleanVendorText(text2, max = 300) {
74
+ if (typeof text2 !== "string") return void 0;
75
+ if (/^\s*</.test(text2)) return void 0;
76
+ const line = text2.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
77
+ return line ? truncate(line, max) : void 0;
78
+ }
79
+ function formatNumber(value) {
80
+ return value.toLocaleString("en-US");
81
+ }
82
+
83
+ // src/core/output.ts
84
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
85
+ function jsonSize(value) {
86
+ return utf8Length(JSON.stringify(value) ?? "");
87
+ }
88
+ function cutStrings(value, max) {
89
+ if (typeof value === "string") return truncate(value, max);
90
+ if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
91
+ if (typeof value === "object" && value !== null) {
92
+ const out = {};
93
+ for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
94
+ return out;
95
+ }
96
+ return value;
97
+ }
98
+ function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
99
+ if (jsonSize(value) <= limit) return { value, truncated: false };
100
+ for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
101
+ const cut = cutStrings(value, max);
102
+ if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
103
+ }
104
+ return void 0;
105
+ }
106
+ function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
107
+ const build = (count) => {
108
+ const cut = count < input.items.length;
109
+ const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
110
+ const next = cut ? input.resumeAt(count) : input.nextPage;
111
+ if (next) result2["nextCursor"] = next;
112
+ if (cut) result2["truncated"] = true;
113
+ return result2;
114
+ };
115
+ const all = build(input.items.length);
116
+ if (jsonSize(all) <= limit) return all;
117
+ let low = 1;
118
+ let high = input.items.length - 1;
119
+ while (low < high) {
120
+ const middle = Math.ceil((low + high) / 2);
121
+ if (jsonSize(build(middle)) <= limit) low = middle;
122
+ else high = middle - 1;
123
+ }
124
+ const best = build(low);
125
+ if (jsonSize(best) <= limit) return best;
126
+ const shrunk = shrinkToFit(best, limit);
127
+ if (shrunk) return { ...shrunk.value, truncated: true };
128
+ throw new ToolFailure("The result is too large to return, even one item at a time.");
129
+ }
130
+ function encodeCursor(tool, state) {
131
+ return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
132
+ }
133
+ function decodeCursor(tool, cursor) {
134
+ if (cursor === void 0 || cursor === "") return null;
135
+ try {
136
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
137
+ if (typeof state === "object" && state !== null && state.t === tool) {
138
+ return state;
139
+ }
140
+ } catch {
141
+ }
142
+ throw new ToolFailure(
143
+ "The cursor is not valid for this tool. Pass the nextCursor value of the previous result unchanged, or leave cursor out to start from the beginning."
144
+ );
145
+ }
146
+
147
+ // src/core/api-tools.ts
148
+ var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
149
+ var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
150
+ var NOTE_ROOM = 400;
151
+ var MAX_CUT_POINTS = 4e4;
152
+ function isQueryValue(value) {
153
+ return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
154
+ }
155
+ function nothingSent(sentence) {
156
+ return new ToolFailure(`${sentence} Nothing was sent.`);
157
+ }
158
+ function fitReply(reply) {
159
+ if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
160
+ const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
161
+ if (shrunk) {
162
+ return {
163
+ ...shrunk.value,
164
+ truncated: true,
165
+ note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
166
+ };
167
+ }
168
+ const text2 = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
169
+ const points = Array.from(text2.length > MAX_CUT_POINTS ? text2.slice(0, MAX_CUT_POINTS) : text2);
170
+ if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
171
+ const cut = (count) => ({
172
+ status: reply["status"],
173
+ ...reply["headers"] ? { headers: reply["headers"] } : {},
174
+ truncated: true,
175
+ note: `The reply has ${formatNumber(utf8Length(text2))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
176
+ text: points.slice(0, count).join("")
177
+ });
178
+ let low = 0;
179
+ let high = points.length;
180
+ while (low < high) {
181
+ const middle = Math.ceil((low + high) / 2);
182
+ if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
183
+ else high = middle - 1;
184
+ }
185
+ return cut(low);
186
+ }
187
+ function shapeReply(response, headerNames) {
188
+ const reply = { status: response.status };
189
+ const headers = {};
190
+ for (const name2 of headerNames) {
191
+ const value = response.headers.get(name2);
192
+ if (value) headers[name2] = truncate(value, 2e3);
193
+ }
194
+ if (Object.keys(headers).length) reply["headers"] = headers;
195
+ const type = response.headers.get("content-type") ?? "";
196
+ if (type && !TEXT_TYPES.test(type)) {
197
+ reply["contentType"] = truncate(type, 200);
198
+ reply["note"] = "The reply is a binary file and is not shown.";
199
+ return reply;
200
+ }
201
+ if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
202
+ return fitReply(reply);
203
+ }
204
+ function checkAccounts(rule, request, h) {
205
+ const label = rule.label ?? "account";
206
+ const allowed = allowedAccounts(h.ctx.accounts, rule.key);
207
+ if (allowed === null) return;
208
+ const namesNone = nothingSent(
209
+ `This request names none of the ${label}s chosen for this connection. ` + (allowed.length ? `It must name one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`)
210
+ );
211
+ if (rule.ids) {
212
+ const ids = rule.ids(request).map(String);
213
+ if (!ids.length) throw namesNone;
214
+ requireAccounts(h.ctx.accounts, rule.key, ids, label);
215
+ return;
216
+ }
217
+ if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
218
+ }
219
+ function apiTools(options) {
220
+ const { label, basePath } = options;
221
+ const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
222
+ const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
223
+ const base = basePath?.replace(/\/+$/, "");
224
+ const pathSchema = {
225
+ type: "string",
226
+ minLength: 1,
227
+ maxLength: 2e3,
228
+ pattern: "^(?!.*//)/[^?#]*$",
229
+ description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
230
+ };
231
+ const querySchema = {
232
+ type: "object",
233
+ description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
234
+ };
235
+ const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
236
+ async function run(method, args, h) {
237
+ let origin = h.origins[0];
238
+ if (args.origin !== void 0) {
239
+ let wanted;
240
+ try {
241
+ wanted = new URL(args.origin).origin;
242
+ } catch {
243
+ }
244
+ if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
245
+ origin = wanted;
246
+ }
247
+ const url = new URL(args.path, origin);
248
+ if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
249
+ const path = url.pathname;
250
+ if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
251
+ let segments;
252
+ try {
253
+ segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
254
+ } catch {
255
+ throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
256
+ }
257
+ if (segments[segments.length - 1] === "") segments.pop();
258
+ const query = {};
259
+ const queryLists = {};
260
+ for (const [key, value] of Object.entries(args.query ?? {})) {
261
+ if (value === void 0 || value === null) continue;
262
+ const list = Array.isArray(value) ? value : [value];
263
+ if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
264
+ query[key] = Array.isArray(value) ? list : value;
265
+ queryLists[key] = list.map(String);
266
+ }
267
+ const request = { method, origin, path, query };
268
+ if (method !== "GET") {
269
+ if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
270
+ if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
271
+ if (args.json !== void 0 && !args.content_type) {
272
+ request.json = args.json;
273
+ } else if (args.json !== void 0 || args.body !== void 0) {
274
+ request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
275
+ request.contentType = args.content_type;
276
+ }
277
+ request.write = true;
278
+ }
279
+ const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
280
+ if (options.accounts) checkAccounts(options.accounts, info, h);
281
+ await options.guard?.(info, h);
282
+ const response = options.send ? await options.send(request, h) : await h.api(request);
283
+ return shapeReply(response, headerNames);
284
+ }
285
+ return [
286
+ {
287
+ name: "api_get",
288
+ kind: "read",
289
+ title: `Call the ${label} API (GET)`,
290
+ description: `${options.description} Sends one GET request with the connection's credentials and returns the HTTP status and the reply, JSON or text, cut to fit 32 KB (use the API's own paging and field parameters for long lists). It changes nothing.`,
291
+ inputSchema: {
292
+ type: "object",
293
+ properties: { path: pathSchema, query: querySchema, ...originSchema },
294
+ required: ["path"],
295
+ additionalProperties: false
296
+ },
297
+ run: (args, h) => run("GET", args, h)
298
+ },
299
+ {
300
+ name: "api_request",
301
+ kind: "write",
302
+ check: "api_get",
303
+ title: `Send a request to the ${label} API`,
304
+ description: `${options.description} Sends one ${methods.join(", ")} request with the connection's credentials, with a JSON body (json) or another body (body and content_type), and returns the HTTP status and the reply. It can create, change or delete data. It is never retried: when the outcome is unclear, check with api_get before sending it again.`,
305
+ inputSchema: {
306
+ type: "object",
307
+ properties: {
308
+ method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
309
+ path: pathSchema,
310
+ query: querySchema,
311
+ json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
312
+ body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
313
+ content_type: {
314
+ type: "string",
315
+ pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
316
+ maxLength: 200,
317
+ description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
318
+ },
319
+ ...originSchema
320
+ },
321
+ required: ["method", "path"],
322
+ additionalProperties: false
323
+ },
324
+ run: (args, h) => run(args.method, args, h)
325
+ }
326
+ ];
327
+ }
328
+
329
+ // src/core/credentials.ts
330
+ function requiredAlternatives(module2) {
331
+ return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
332
+ }
333
+ function unmetAlternatives(alternatives, has) {
334
+ const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
335
+ if (lacking.some((list) => list.length === 0)) return [];
336
+ return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
337
+ }
338
+ function andList(items) {
339
+ if (items.length <= 2) return items.join(" and ");
340
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
341
+ }
342
+ function orList(items) {
343
+ if (items.length <= 1) return items.join("");
344
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
345
+ }
346
+
347
+ // src/core/files.ts
348
+ var ATTACHMENT_URI = "attachment:///";
349
+ var MAX_NAME = 200;
350
+ function fileLimitOf(ctx) {
351
+ const maxBytes = ctx.files?.maxBytes;
352
+ return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
353
+ }
354
+ function fileName(name2) {
355
+ const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
356
+ const points = Array.from(clean);
357
+ if (points.length <= MAX_NAME) return clean || "file";
358
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
359
+ return points.slice(0, MAX_NAME - extension.length).join("") + extension;
360
+ }
361
+ function fileType(mimeType) {
362
+ const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
363
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
364
+ }
365
+ function resourceBlock(file) {
366
+ return {
367
+ type: "resource",
368
+ resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
369
+ };
370
+ }
371
+
372
+ // src/core/http.ts
373
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
374
+ var USER_AGENT = "agent-connectors";
375
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
376
+ function errorCode(error) {
377
+ const code = error?.code;
378
+ return typeof code === "string" ? code : void 0;
379
+ }
380
+ function describe(error) {
381
+ const name2 = error?.name;
382
+ const code = errorCode(error);
383
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
384
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
385
+ if (code === "TOO_LARGE") return "the reply was too large";
386
+ return cleanVendorText(error?.message, 200) ?? "a network error";
387
+ }
388
+ function retryAfterSeconds(headers, now = Date.now()) {
389
+ const retryAfter = headers.get("retry-after");
390
+ if (retryAfter) {
391
+ const seconds = Number(retryAfter);
392
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
393
+ const date = Date.parse(retryAfter);
394
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
395
+ }
396
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
397
+ if (reset) {
398
+ const value = Number(reset);
399
+ if (Number.isFinite(value) && value >= 0) {
400
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
401
+ }
402
+ }
403
+ return void 0;
404
+ }
405
+ function vendorCode(data) {
406
+ if (typeof data !== "object" || data === null) return void 0;
407
+ for (const key of ["error", "code"]) {
408
+ const value = data[key];
409
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
410
+ }
411
+ return void 0;
412
+ }
413
+ function vendorMessage(data) {
414
+ if (typeof data === "string") return cleanVendorText(data);
415
+ if (typeof data !== "object" || data === null) return void 0;
416
+ const record = data;
417
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
418
+ const value = record[key];
419
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
420
+ const nested = value?.message;
421
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
422
+ }
423
+ if (Array.isArray(record["errors"])) {
424
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
425
+ if (messages.length) return cleanVendorText(messages.join("; "));
426
+ }
427
+ return void 0;
428
+ }
429
+ var TooLarge = class extends Error {
430
+ constructor(limit) {
431
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
432
+ this.limit = limit;
433
+ }
434
+ limit;
435
+ };
436
+ async function readCapped(response, maxBytes) {
437
+ const declared = Number(response.headers.get("content-length"));
438
+ if (Number.isFinite(declared) && declared > maxBytes) {
439
+ await response.body?.cancel().catch(() => {
440
+ });
441
+ throw new TooLarge(maxBytes);
442
+ }
443
+ if (!response.body) return new Uint8Array(0);
444
+ const reader = response.body.getReader();
445
+ const chunks = [];
446
+ let total = 0;
447
+ for (; ; ) {
448
+ const { done, value } = await reader.read();
449
+ if (done) break;
450
+ total += value.byteLength;
451
+ if (total > maxBytes) {
452
+ await reader.cancel().catch(() => {
453
+ });
454
+ throw new TooLarge(maxBytes);
455
+ }
456
+ chunks.push(value);
457
+ }
458
+ const bytes = new Uint8Array(total);
459
+ let offset = 0;
460
+ for (const chunk of chunks) {
461
+ bytes.set(chunk, offset);
462
+ offset += chunk.byteLength;
463
+ }
464
+ return bytes;
465
+ }
466
+ function parseBody(bytes, contentType) {
467
+ if (bytes.length === 0) return null;
468
+ const text2 = utf8Decode(bytes);
469
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text2)) {
470
+ try {
471
+ return JSON.parse(text2);
472
+ } catch {
473
+ }
474
+ }
475
+ return text2;
476
+ }
477
+ function createHttp(env) {
478
+ const { label, ctx } = env;
479
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
480
+ const checkCredentials = env.credentialLabels.length ? `Check that the ${andList(env.credentialLabels)} ${env.credentialLabels.length > 1 ? "are" : "is"} correct and still active.` : `Check that the ${label} credentials are correct and still active.`;
481
+ function failureFor(status, headers, data, request) {
482
+ const message = vendorMessage(data);
483
+ const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
484
+ const retryAfter = retryAfterSeconds(headers);
485
+ const code = vendorCode(data);
486
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
487
+ const custom = request.errors?.[status];
488
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
489
+ if (status >= 500) {
490
+ if (request.write) {
491
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
492
+ }
493
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
494
+ }
495
+ if (status === 429) {
496
+ return new ToolFailure(
497
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
498
+ { status, ...extra }
499
+ );
500
+ }
501
+ if (status === 401) {
502
+ return new ToolFailure(
503
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
504
+ { status, ...extra }
505
+ );
506
+ }
507
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
508
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
509
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
510
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
511
+ }
512
+ async function api(request) {
513
+ const method = request.method ?? "GET";
514
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
515
+ throw new Error(`read-only tool sent ${method}`);
516
+ }
517
+ const origin = request.origin ?? env.origins[0];
518
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
519
+ const url = new URL(request.path, origin);
520
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
521
+ for (const [key, value] of Object.entries(request.query ?? {})) {
522
+ if (value === void 0 || value === null) continue;
523
+ if (Array.isArray(value)) {
524
+ url.searchParams.delete(key);
525
+ for (const item of value) url.searchParams.append(key, String(item));
526
+ } else {
527
+ url.searchParams.set(key, String(value));
528
+ }
529
+ }
530
+ const headers = {
531
+ accept: "application/json",
532
+ "user-agent": USER_AGENT,
533
+ ...request.auth === false ? {} : env.authHeaders(),
534
+ ...request.headers
535
+ };
536
+ let body;
537
+ if (request.json !== void 0) {
538
+ body = JSON.stringify(request.json);
539
+ headers["content-type"] = "application/json";
540
+ } else if (request.body) {
541
+ body = request.body;
542
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
543
+ }
544
+ const started = Date.now();
545
+ if (request.write) env.onWriteSent();
546
+ let response;
547
+ try {
548
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
549
+ } catch (error) {
550
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
551
+ if (errorCode(error) === "URL_REFUSED") {
552
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
553
+ }
554
+ if (request.write) {
555
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
556
+ }
557
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
558
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
559
+ }
560
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
561
+ let bytes;
562
+ try {
563
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
564
+ } catch (error) {
565
+ if (request.write && (response.ok || response.status >= 500)) {
566
+ throw new OutcomeUnknown(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}), so it is not known whether the change was made.`);
567
+ }
568
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
569
+ }
570
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
571
+ if (response.ok) return { status: response.status, headers: response.headers, data };
572
+ throw failureFor(response.status, response.headers, data, request);
573
+ }
574
+ async function media(rawUrl, options) {
575
+ const { what } = options;
576
+ let url;
577
+ try {
578
+ url = new URL(rawUrl);
579
+ } catch {
580
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
581
+ }
582
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
583
+ const started = Date.now();
584
+ let response;
585
+ try {
586
+ response = await ctx.fetch(url.toString(), {
587
+ method: "GET",
588
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
589
+ ...ctx.signal ? { signal: ctx.signal } : {}
590
+ });
591
+ } catch (error) {
592
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
593
+ if (errorCode(error) === "URL_REFUSED") {
594
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
595
+ }
596
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
597
+ }
598
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
599
+ if (!response.ok) {
600
+ await response.body?.cancel().catch(() => {
601
+ });
602
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
603
+ }
604
+ try {
605
+ const bytes = await readCapped(response, options.maxBytes);
606
+ return { bytes, contentType: response.headers.get("content-type") };
607
+ } catch (error) {
608
+ if (error instanceof TooLarge) {
609
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
610
+ }
611
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
612
+ }
613
+ }
614
+ return { api, media };
615
+ }
616
+
617
+ // src/core/origins.ts
618
+ function parseSiteUrl(value) {
619
+ const text2 = typeof value === "string" ? value.trim() : "";
620
+ if (!text2) return { ok: false, problem: "is empty" };
621
+ let url;
622
+ try {
623
+ url = new URL(text2.includes("://") ? text2 : `https://${text2}`);
624
+ } catch {
625
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
626
+ }
627
+ if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
628
+ if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
629
+ if (!url.hostname) return { ok: false, problem: "has no host name" };
630
+ return { ok: true, url, origin: url.origin };
631
+ }
632
+
633
+ // src/core/schema.ts
634
+ var patterns = /* @__PURE__ */ new Map();
635
+ function patternOf(source) {
636
+ let compiled = patterns.get(source);
637
+ if (!compiled) {
638
+ compiled = new RegExp(source, "u");
639
+ patterns.set(source, compiled);
640
+ }
641
+ return compiled;
642
+ }
643
+ function isPlainObject(value) {
644
+ return typeof value === "object" && value !== null && !Array.isArray(value);
645
+ }
646
+ function isHttpUrl(value) {
647
+ try {
648
+ const url = new URL(value);
649
+ return url.protocol === "https:" || url.protocol === "http:";
650
+ } catch {
651
+ return false;
652
+ }
653
+ }
654
+ function name(path) {
655
+ return `\`${path}\``;
656
+ }
657
+ function child(path, key) {
658
+ return path ? `${path}.${key}` : key;
659
+ }
660
+ function checkValue(schema, value, path, issues) {
661
+ switch (schema.type) {
662
+ case "object":
663
+ checkObject(schema, value, path, issues);
664
+ return;
665
+ case "array": {
666
+ if (!Array.isArray(value)) {
667
+ issues.push(`${name(path)} must be an array`);
668
+ return;
669
+ }
670
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
671
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
672
+ }
673
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
674
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
675
+ }
676
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
677
+ issues.push(`${name(path)} must not repeat an item`);
678
+ }
679
+ if (schema.items) {
680
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
681
+ }
682
+ break;
683
+ }
684
+ case "string": {
685
+ if (typeof value !== "string") {
686
+ issues.push(`${name(path)} must be a string`);
687
+ return;
688
+ }
689
+ const length = Array.from(value).length;
690
+ if (schema.minLength !== void 0 && length < schema.minLength) {
691
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
692
+ }
693
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
694
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
695
+ }
696
+ if (schema.format === "uri" && !isHttpUrl(value)) {
697
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
698
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
699
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
700
+ }
701
+ break;
702
+ }
703
+ case "integer":
704
+ case "number": {
705
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
706
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
707
+ return;
708
+ }
709
+ if (schema.minimum !== void 0 && value < schema.minimum) {
710
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
711
+ }
712
+ if (schema.maximum !== void 0 && value > schema.maximum) {
713
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
714
+ }
715
+ break;
716
+ }
717
+ case "boolean":
718
+ if (typeof value !== "boolean") {
719
+ issues.push(`${name(path)} must be true or false`);
720
+ return;
721
+ }
722
+ break;
723
+ default:
724
+ break;
725
+ }
726
+ if (schema.enum && !schema.enum.includes(value)) {
727
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
728
+ }
729
+ }
730
+ function checkObject(schema, value, path, issues) {
731
+ if (!isPlainObject(value)) {
732
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
733
+ return;
734
+ }
735
+ const properties = schema.properties ?? {};
736
+ for (const key of schema.required ?? []) {
737
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
738
+ }
739
+ const unknown = [];
740
+ for (const [key, item] of Object.entries(value)) {
741
+ const property = properties[key];
742
+ if (!property) {
743
+ if (schema.additionalProperties === false) unknown.push(key);
744
+ continue;
745
+ }
746
+ if (item === void 0 || item === null) continue;
747
+ checkValue(property, item, child(path, key), issues);
748
+ }
749
+ if (unknown.length) {
750
+ const known = Object.keys(properties);
751
+ issues.push(`unknown ${path ? `field${unknown.length > 1 ? "s" : ""} in ${name(path)}` : `argument${unknown.length > 1 ? "s" : ""}`} ${unknown.map((key) => JSON.stringify(key)).join(", ")}` + (known.length ? ` (expected: ${known.join(", ")})` : ""));
752
+ }
753
+ }
754
+ function copyDefault(value) {
755
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
756
+ }
757
+ function validateArguments(schema, args) {
758
+ const input = args === void 0 || args === null ? {} : args;
759
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
760
+ const value = { ...input };
761
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
762
+ const issues = [];
763
+ checkObject(schema, value, "", issues);
764
+ if (issues.length) return { ok: false, issues };
765
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
766
+ if (value[key] === null) delete value[key];
767
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
768
+ }
769
+ return { ok: true, value };
770
+ }
771
+
772
+ // src/core/upload-hosts.ts
773
+ var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
774
+ function uploadHostProblem(entry) {
775
+ if (typeof entry !== "string") return "must be a host name";
776
+ const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
777
+ const labels = name2.split(".");
778
+ if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
779
+ return "must be a lowercase host name like uploads.example.com, or one with a leading dot like .example.com for every host under it";
780
+ }
781
+ if (labels.length < 2) return "needs at least two labels, like example.com";
782
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
783
+ return void 0;
784
+ }
785
+
786
+ // src/core/connector.ts
787
+ var ANNOTATIONS = {
788
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
789
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
790
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
791
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
792
+ write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
793
+ };
794
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
795
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
796
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
797
+ var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
798
+ var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
799
+ var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
800
+ var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
801
+ function deepFreeze(value) {
802
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
803
+ Object.freeze(value);
804
+ for (const item of Object.values(value)) deepFreeze(item);
805
+ }
806
+ return value;
807
+ }
808
+ function assertDefinition(def) {
809
+ const problem = (message) => {
810
+ throw new Error(`connector "${def.vendor}": ${message}`);
811
+ };
812
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
813
+ if (!def.label?.trim()) problem("label is required");
814
+ const originFields = def.originFields ?? [];
815
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
816
+ for (const origin of def.origins) {
817
+ let url;
818
+ try {
819
+ url = new URL(origin);
820
+ } catch {
821
+ }
822
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
823
+ }
824
+ for (const name2 of def.credentials) {
825
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
826
+ }
827
+ for (const [index, name2] of originFields.entries()) {
828
+ if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
829
+ if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
830
+ }
831
+ const names = /* @__PURE__ */ new Set();
832
+ for (const tool of def.tools) {
833
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
834
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
835
+ names.add(tool.name);
836
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
837
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
838
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
839
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
840
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
841
+ }
842
+ }
843
+ for (const tool of def.tools) {
844
+ if (tool.kind === "read") continue;
845
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
846
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
847
+ }
848
+ assertUploadHosts(def, problem);
849
+ assertRequiredCredentials(def, problem);
850
+ assertAccountPickers(def, problem);
851
+ }
852
+ function assertUploadHosts(def, problem) {
853
+ const hosts = def.uploadHosts;
854
+ if (hosts === void 0) return;
855
+ if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
856
+ hosts.forEach((entry, index) => {
857
+ const wrong = uploadHostProblem(entry);
858
+ if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
859
+ if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
860
+ });
861
+ }
862
+ function assertRequiredCredentials(def, problem) {
863
+ const required = def.requiredCredentials;
864
+ if (required === void 0) return;
865
+ if (!Array.isArray(required) || !required.length) {
866
+ problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
867
+ }
868
+ required.forEach((list, index) => {
869
+ const which = `requiredCredentials[${index}]`;
870
+ if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
871
+ list.forEach((name2, position) => {
872
+ if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
873
+ if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
874
+ });
875
+ });
876
+ const lists = required;
877
+ lists.forEach((list, index) => {
878
+ const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
879
+ if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
880
+ if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
881
+ problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
882
+ }
883
+ });
884
+ }
885
+ function isDotPath(value) {
886
+ return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
887
+ }
888
+ function assertAccountPickers(def, problem) {
889
+ const pickers = def.accountPickers;
890
+ if (pickers === void 0) return;
891
+ if (!Array.isArray(pickers)) problem("accountPickers must be a list");
892
+ const keys = /* @__PURE__ */ new Set();
893
+ for (const item of pickers) {
894
+ if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
895
+ const picker = item;
896
+ const key = picker["key"];
897
+ if (typeof key !== "string" || !PICKER_KEY_PATTERN.test(key)) problem(`account picker ${JSON.stringify(key)}: key must match ^[a-z][a-z0-9_]{0,63}$`);
898
+ if (keys.has(key)) problem(`account picker ${key} is defined twice`);
899
+ keys.add(key);
900
+ const fail = (message) => problem(`account picker ${key}: ${message}`);
901
+ const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
902
+ if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
903
+ const { label, description, multiple, legacyField } = picker;
904
+ if (typeof label !== "string" || !label.trim()) fail("label is required");
905
+ if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
906
+ fail("description, when given, must be a text of 1 to 1024 characters");
907
+ }
908
+ if (typeof multiple !== "boolean") fail("multiple must be true or false");
909
+ const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
910
+ if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
911
+ if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
912
+ for (const field of ["idField", "nameField"]) {
913
+ if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
914
+ }
915
+ if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
916
+ fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
917
+ }
918
+ }
919
+ }
920
+ function copyPicker(picker) {
921
+ return {
922
+ key: picker.key,
923
+ label: picker.label,
924
+ ...picker.description !== void 0 ? { description: picker.description } : {},
925
+ multiple: picker.multiple,
926
+ tool: picker.tool,
927
+ idField: picker.idField,
928
+ nameField: picker.nameField,
929
+ ...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
930
+ };
931
+ }
932
+ function result(payload, isError, files = []) {
933
+ return {
934
+ content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
935
+ ...isError ? { isError: true } : {}
936
+ };
937
+ }
938
+ function failure(message, details = {}) {
939
+ return result({ error: message, ...details }, true);
940
+ }
941
+ function trimmed(values) {
942
+ const out = {};
943
+ if (typeof values !== "object" || values === null) return out;
944
+ for (const [key, value] of Object.entries(values)) {
945
+ if (value === void 0 || value === null) continue;
946
+ const text2 = String(value).trim();
947
+ if (text2) out[key] = text2;
948
+ }
949
+ return out;
950
+ }
951
+ function defineConnector(def) {
952
+ assertDefinition(def);
953
+ const { label } = def;
954
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
955
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
956
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
957
+ const required = requiredAlternatives(def);
958
+ const notConnected = (unmet) => {
959
+ const [first] = unmet;
960
+ if (unmet.length === 1 && first) {
961
+ return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
962
+ }
963
+ return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
964
+ };
965
+ const descriptors = def.tools.map((tool) => ({
966
+ name: tool.name,
967
+ title: tool.title,
968
+ description: tool.description,
969
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
970
+ annotations: { ...ANNOTATIONS[tool.kind] }
971
+ }));
972
+ async function call(toolName, args, ctx) {
973
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
974
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
975
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
976
+ const log = (text2) => {
977
+ try {
978
+ ctx.log?.(text2);
979
+ } catch {
980
+ }
981
+ };
982
+ const given = trimmed(ctx.credentials);
983
+ const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
984
+ const has = (name2) => Boolean(credentials[name2]);
985
+ const unmet = unmetAlternatives(required, has);
986
+ if (unmet.length) return failure(notConnected(unmet));
987
+ const complete = required.filter((list) => list.every(has));
988
+ const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
989
+ const fieldOrigins = /* @__PURE__ */ new Map();
990
+ for (const name2 of def.originFields ?? []) {
991
+ if (!given[name2] && !inUse.includes(name2)) continue;
992
+ const site = parseSiteUrl(given[name2] ?? "");
993
+ if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
994
+ fieldOrigins.set(name2, site.origin);
995
+ }
996
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
997
+ const parsed = validateArguments(tool.inputSchema, args);
998
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
999
+ const frozenCredentials = Object.freeze({ ...credentials });
1000
+ let writeSent = false;
1001
+ const fileLimit = fileLimitOf(ctx);
1002
+ const files = [];
1003
+ let fileBytes = 0;
1004
+ const http = createHttp({
1005
+ vendor: def.vendor,
1006
+ label,
1007
+ tool: tool.name,
1008
+ readOnly: tool.kind === "read",
1009
+ origins,
1010
+ // A 401 names the credentials in use (for a module that needs none, the ones given).
1011
+ credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
1012
+ ctx,
1013
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
1014
+ log,
1015
+ onWriteSent: () => {
1016
+ writeSent = true;
1017
+ }
1018
+ });
1019
+ const helpers = {
1020
+ tool: tool.name,
1021
+ credentials: frozenCredentials,
1022
+ ctx,
1023
+ origins: Object.freeze([...origins]),
1024
+ originOf: (credential) => {
1025
+ const origin = fieldOrigins.get(credential);
1026
+ if (!origin) throw new Error(`${credential} gives no origin in this call`);
1027
+ return origin;
1028
+ },
1029
+ api: http.api,
1030
+ media: http.media,
1031
+ page: (input) => fitPage(input),
1032
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
1033
+ makeCursor: (state) => encodeCursor(tool.name, state),
1034
+ fileLimit: () => fileLimit,
1035
+ file: ({ name: name2, mimeType, bytes }) => {
1036
+ if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
1037
+ const total = fileBytes + bytes.byteLength;
1038
+ if (total > fileLimit) {
1039
+ throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total)} bytes in all, more than the ${formatNumber(fileLimit)} bytes this host takes from one call.` : `The file has ${formatNumber(bytes.byteLength)} bytes, more than the ${formatNumber(fileLimit)} bytes this host takes.`);
1040
+ }
1041
+ fileBytes = total;
1042
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
1043
+ files.push({ ...info, bytes });
1044
+ return { ...info };
1045
+ },
1046
+ log
1047
+ };
1048
+ try {
1049
+ const data = await tool.run(parsed.value, helpers);
1050
+ const fitted = shrinkToFit(data ?? {});
1051
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
1052
+ const payload = fitted.value;
1053
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
1054
+ } catch (error) {
1055
+ if (error instanceof OutcomeUnknown) {
1056
+ return result({
1057
+ outcome: "unknown",
1058
+ check: tool.check,
1059
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
1060
+ }, true);
1061
+ }
1062
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
1063
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
1064
+ if (writeSent) {
1065
+ return result({
1066
+ outcome: "unknown",
1067
+ check: tool.check,
1068
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
1069
+ }, true);
1070
+ }
1071
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
1072
+ }
1073
+ }
1074
+ return deepFreeze({
1075
+ vendor: def.vendor,
1076
+ origins: [...def.origins],
1077
+ originFields: [...def.originFields ?? []],
1078
+ uploadHosts: [...def.uploadHosts ?? []],
1079
+ credentials: [...def.credentials],
1080
+ requiredCredentials: required.map((list) => [...list]),
1081
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
1082
+ tools: descriptors,
1083
+ call
1084
+ });
1085
+ }
1086
+
1087
+ // src/core/jwt.ts
1088
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
1089
+
1090
+ // src/vendors/gmail/google.ts
1091
+ function plain(text2) {
1092
+ return text2.replace(/<\/?[A-Za-z][^<>]{0,300}>/g, "");
1093
+ }
1094
+ async function googleApi(h, request) {
1095
+ try {
1096
+ return await h.api(request);
1097
+ } catch (error) {
1098
+ if (error instanceof ToolFailure) {
1099
+ const message = plain(error.message);
1100
+ throw message === error.message ? error : new ToolFailure(message, error.details);
1101
+ }
1102
+ if (error instanceof OutcomeUnknown) {
1103
+ const message = plain(error.message);
1104
+ throw message === error.message ? error : new OutcomeUnknown(message);
1105
+ }
1106
+ throw error;
1107
+ }
1108
+ }
1109
+ function compact(value) {
1110
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
1111
+ }
1112
+ function cursorNumber(state, key, fallback, min, max) {
1113
+ const value = state?.[key];
1114
+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max ? value : fallback;
1115
+ }
1116
+ function jsonBytes(text2, index) {
1117
+ const code = text2.charCodeAt(index);
1118
+ if (code === 34 || code === 92) return 2;
1119
+ if (code < 32) return code === 8 || code === 9 || code === 10 || code === 12 || code === 13 ? 2 : 6;
1120
+ if (code < 128) return 1;
1121
+ if (code < 2048) return 2;
1122
+ if (code >= 55296 && code <= 56319) {
1123
+ const next = text2.charCodeAt(index + 1);
1124
+ return next >= 56320 && next <= 57343 ? 0 : 6;
1125
+ }
1126
+ if (code >= 56320 && code <= 57343) {
1127
+ const previous = text2.charCodeAt(index - 1);
1128
+ return previous >= 55296 && previous <= 56319 ? 4 : 6;
1129
+ }
1130
+ return 3;
1131
+ }
1132
+ function sliceJsonText(text2, start, maxBytes) {
1133
+ let index = Math.max(0, Math.min(Math.trunc(start), text2.length));
1134
+ if (index > 0 && index < text2.length && jsonBytes(text2, index) === 4) index -= 1;
1135
+ const from = index;
1136
+ let bytes = 0;
1137
+ while (index < text2.length) {
1138
+ const unit = jsonBytes(text2, index);
1139
+ const size = unit === 0 ? 4 : unit;
1140
+ if (bytes + size > maxBytes) break;
1141
+ bytes += size;
1142
+ index += unit === 0 ? 2 : 1;
1143
+ }
1144
+ return { text: text2.slice(from, index), ...index < text2.length ? { next: index } : {} };
1145
+ }
1146
+ function fitTextPart(text2, start, build) {
1147
+ let room = OUTPUT_LIMIT_BYTES - jsonSize(build("", text2.length)) - 16;
1148
+ for (let round = 0; round < 5 && room > 0; round++) {
1149
+ const part = sliceJsonText(text2, start, room);
1150
+ const result2 = build(part.text, part.next);
1151
+ const over = jsonSize(result2) - OUTPUT_LIMIT_BYTES;
1152
+ if (over <= 0) return result2;
1153
+ room -= over;
1154
+ }
1155
+ throw new ToolFailure("The result is too large to return.");
1156
+ }
1157
+
1158
+ // src/vendors/gmail/mime.ts
1159
+ function header(headers, name2) {
1160
+ if (!Array.isArray(headers)) return void 0;
1161
+ const wanted = name2.toLowerCase();
1162
+ for (const item of headers) {
1163
+ if (typeof item?.name === "string" && item.name.toLowerCase() === wanted && typeof item.value === "string") return item.value;
1164
+ }
1165
+ return void 0;
1166
+ }
1167
+ function oneLine(value) {
1168
+ const line = value?.replace(/[\r\n]+/g, " ").trim();
1169
+ return line ? line : void 0;
1170
+ }
1171
+ var ENTITIES = {
1172
+ amp: "&",
1173
+ lt: "<",
1174
+ gt: ">",
1175
+ quot: '"',
1176
+ apos: "'",
1177
+ nbsp: " ",
1178
+ ndash: "\u2013",
1179
+ mdash: "\u2014",
1180
+ hellip: "\u2026",
1181
+ lsquo: "\u2018",
1182
+ rsquo: "\u2019",
1183
+ ldquo: "\u201C",
1184
+ rdquo: "\u201D",
1185
+ copy: "\xA9",
1186
+ reg: "\xAE",
1187
+ trade: "\u2122",
1188
+ euro: "\u20AC",
1189
+ bull: "\u2022",
1190
+ middot: "\xB7"
1191
+ };
1192
+ function decodeEntities(text2) {
1193
+ return text2.replace(/&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[A-Za-z]{2,8});/g, (match, entity) => {
1194
+ if (entity.startsWith("#")) {
1195
+ const code = entity[1] === "x" || entity[1] === "X" ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);
1196
+ return code > 0 && code <= 1114111 && (code < 55296 || code > 57343) ? String.fromCodePoint(code) : match;
1197
+ }
1198
+ return ENTITIES[entity.toLowerCase()] ?? match;
1199
+ });
1200
+ }
1201
+ var MAX_HTML_CHARS = 1e6;
1202
+ var HIDDEN = /* @__PURE__ */ new Set(["script", "style", "head", "title"]);
1203
+ var BLOCKS = /* @__PURE__ */ new Set(["p", "div", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "li", "blockquote", "table", "ul", "ol", "section", "article", "header", "footer"]);
1204
+ function isLetter(code) {
1205
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122;
1206
+ }
1207
+ function isNameChar(code) {
1208
+ return isLetter(code) || code >= 48 && code <= 57;
1209
+ }
1210
+ function tagName(html, from, end) {
1211
+ let at = from;
1212
+ while (at < end && isNameChar(html.charCodeAt(at))) at++;
1213
+ return at > from && isLetter(html.charCodeAt(from)) ? html.slice(from, at).toLowerCase() : "";
1214
+ }
1215
+ function afterClosing(html, from, name2) {
1216
+ let at = from;
1217
+ for (; ; ) {
1218
+ const open = html.indexOf("</", at);
1219
+ if (open === -1) return -1;
1220
+ const end = open + 2 + name2.length;
1221
+ if (html.slice(open + 2, end).toLowerCase() === name2 && !isNameChar(html.charCodeAt(end))) {
1222
+ const close = html.indexOf(">", end);
1223
+ return close === -1 ? -1 : close + 1;
1224
+ }
1225
+ at = open + 2;
1226
+ }
1227
+ }
1228
+ function hrefOf(tag) {
1229
+ const match = /\shref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i.exec(tag);
1230
+ const href = (match?.[1] ?? match?.[2] ?? match?.[3] ?? "").trim();
1231
+ return href || void 0;
1232
+ }
1233
+ function htmlToText(html) {
1234
+ const source = html.length > MAX_HTML_CHARS ? html.slice(0, MAX_HTML_CHARS) : html;
1235
+ const pieces = [];
1236
+ let link;
1237
+ let index = 0;
1238
+ while (index < source.length) {
1239
+ const open = source.indexOf("<", index);
1240
+ if (open === -1) {
1241
+ pieces.push(source.slice(index));
1242
+ break;
1243
+ }
1244
+ if (open > index) pieces.push(source.slice(index, open));
1245
+ const next = source.charCodeAt(open + 1);
1246
+ if (!isLetter(next) && next !== 47 && next !== 33 && next !== 63) {
1247
+ pieces.push("<");
1248
+ index = open + 1;
1249
+ continue;
1250
+ }
1251
+ if (source.startsWith("<!--", open)) {
1252
+ const end = source.indexOf("-->", open + 4);
1253
+ if (end === -1) break;
1254
+ index = end + 3;
1255
+ continue;
1256
+ }
1257
+ const close = source.indexOf(">", open + 1);
1258
+ if (close === -1) break;
1259
+ index = close + 1;
1260
+ const closing = next === 47;
1261
+ const name2 = tagName(source, closing ? open + 2 : open + 1, close);
1262
+ if (!name2) continue;
1263
+ if (closing) {
1264
+ if (name2 === "a" && link) {
1265
+ const words = pieces.slice(link.at).join("").trim();
1266
+ const { href } = link;
1267
+ pieces.length = link.at;
1268
+ pieces.push(!words || words === href || /^mailto:/i.test(href) ? words || href : `${words} (${href})`);
1269
+ link = void 0;
1270
+ } else if (BLOCKS.has(name2)) {
1271
+ pieces.push("\n");
1272
+ }
1273
+ continue;
1274
+ }
1275
+ if (HIDDEN.has(name2)) {
1276
+ const after = afterClosing(source, index, name2);
1277
+ if (after === -1) break;
1278
+ index = after;
1279
+ continue;
1280
+ }
1281
+ if (name2 === "br") pieces.push("\n");
1282
+ else if (name2 === "li") pieces.push("- ");
1283
+ else if (name2 === "a") {
1284
+ const href = hrefOf(source.slice(open, Math.min(close, open + 2e3)));
1285
+ if (href) link = { href, at: pieces.length };
1286
+ }
1287
+ }
1288
+ return decodeEntities(pieces.join("")).replace(/[ \t\u00a0]+/g, " ").replace(/ *\n */g, "\n").replace(/\n{3,}/g, "\n\n").trim();
1289
+ }
1290
+ function charsetOf(part) {
1291
+ const type = header(part?.headers, "Content-Type") ?? "";
1292
+ const match = /charset\s*=\s*"?([^";\s]+)"?/i.exec(type);
1293
+ return match?.[1] ?? "utf-8";
1294
+ }
1295
+ function decodeData(data, charset = "utf-8") {
1296
+ let bytes;
1297
+ try {
1298
+ bytes = base64UrlDecode(data.replace(/=+$/, "").replace(/\s+/g, ""));
1299
+ } catch {
1300
+ return "";
1301
+ }
1302
+ try {
1303
+ return new TextDecoder(charset).decode(bytes);
1304
+ } catch {
1305
+ return utf8Decode(bytes);
1306
+ }
1307
+ }
1308
+ function readPayload(payload) {
1309
+ const out = { plain: [], html: [], attachments: [] };
1310
+ const walk = (part, depth) => {
1311
+ if (!part || typeof part !== "object" || depth > 20) return;
1312
+ if (Array.isArray(part.parts) && part.parts.length) {
1313
+ for (const child2 of part.parts) walk(child2, depth + 1);
1314
+ return;
1315
+ }
1316
+ const mime = typeof part.mimeType === "string" ? part.mimeType.toLowerCase() : "";
1317
+ const filename = typeof part.filename === "string" ? part.filename : "";
1318
+ const disposition = header(part.headers, "Content-Disposition") ?? "";
1319
+ const isText = mime === "text/plain" || mime === "text/html";
1320
+ if (filename || /^\s*attachment/i.test(disposition) || !isText && part.body?.attachmentId) {
1321
+ out.attachments.push({
1322
+ ...filename ? { filename: truncate(filename, 300) } : {},
1323
+ ...mime ? { mime_type: mime } : {},
1324
+ ...typeof part.body?.size === "number" ? { size: part.body.size } : {},
1325
+ ...typeof part.body?.attachmentId === "string" ? { attachment_id: part.body.attachmentId } : {},
1326
+ ...typeof part.partId === "string" ? { part_id: part.partId } : {}
1327
+ });
1328
+ return;
1329
+ }
1330
+ if (isText && typeof part.body?.data === "string") {
1331
+ (mime === "text/plain" ? out.plain : out.html).push(decodeData(part.body.data, charsetOf(part)));
1332
+ }
1333
+ };
1334
+ walk(payload, 0);
1335
+ return out;
1336
+ }
1337
+ function bodyText(body) {
1338
+ if (body.plain.some((part) => part.trim())) return { text: body.plain.join("\n\n").trim(), from: "text" };
1339
+ if (body.html.length) {
1340
+ const html = body.html.join("\n");
1341
+ return { text: htmlToText(html), from: "html", ...html.length > MAX_HTML_CHARS ? { cut: true } : {} };
1342
+ }
1343
+ return { text: "", from: "none" };
1344
+ }
1345
+ function base64(bytes) {
1346
+ let binary = "";
1347
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
1348
+ return btoa(binary);
1349
+ }
1350
+ var ASCII = /^[\x20-\x7e]*$/;
1351
+ function encodeHeader(value) {
1352
+ if (ASCII.test(value)) return value;
1353
+ const words = [];
1354
+ let chunk = "";
1355
+ for (const char of value) {
1356
+ if (chunk && utf8Length(chunk + char) > 45) {
1357
+ words.push(chunk);
1358
+ chunk = "";
1359
+ }
1360
+ chunk += char;
1361
+ }
1362
+ if (chunk) words.push(chunk);
1363
+ return words.map((word) => `=?UTF-8?B?${base64(utf8Bytes(word))}?=`).join("\r\n ");
1364
+ }
1365
+ var BARE_ADDRESS = /^[^\s@<>,;:"()[\]\\]+@[^\s@<>,;:"()[\]\\]+$/;
1366
+ var NAMED_ADDRESS = /^(.*?)\s*<([^\s@<>,;:"()[\]\\]+@[^\s@<>,;:"()[\]\\]+)>$/;
1367
+ function formatAddress(value) {
1368
+ const text2 = value.trim();
1369
+ if (BARE_ADDRESS.test(text2)) return text2;
1370
+ const match = NAMED_ADDRESS.exec(text2);
1371
+ if (!match) return void 0;
1372
+ const name2 = (match[1] ?? "").trim().replace(/^"(.*)"$/, "$1").trim();
1373
+ const address = match[2];
1374
+ if (!name2) return address;
1375
+ if (ASCII.test(name2)) return `"${name2.replace(/(["\\])/g, "\\$1")}" <${address}>`;
1376
+ return `${encodeHeader(name2)} <${address}>`;
1377
+ }
1378
+ function lines76(text2) {
1379
+ const out = [];
1380
+ for (let i = 0; i < text2.length; i += 76) out.push(text2.slice(i, i + 76));
1381
+ return out;
1382
+ }
1383
+ function textPart(body, subtype) {
1384
+ return [`Content-Type: text/${subtype}; charset=UTF-8`, "Content-Transfer-Encoding: base64", "", ...lines76(base64(utf8Bytes(body)))];
1385
+ }
1386
+ function buildMessage(mail, boundary) {
1387
+ const lines = [];
1388
+ if (mail.to.length) lines.push(`To: ${mail.to.join(",\r\n ")}`);
1389
+ if (mail.cc.length) lines.push(`Cc: ${mail.cc.join(",\r\n ")}`);
1390
+ if (mail.bcc.length) lines.push(`Bcc: ${mail.bcc.join(",\r\n ")}`);
1391
+ lines.push(`Subject: ${encodeHeader(mail.subject)}`);
1392
+ if (mail.inReplyTo) lines.push(`In-Reply-To: ${mail.inReplyTo}`);
1393
+ if (mail.references) lines.push(`References: ${mail.references}`);
1394
+ lines.push("MIME-Version: 1.0");
1395
+ const text2 = mail.text ?? (mail.html !== void 0 ? htmlToText(mail.html) : "");
1396
+ if (mail.html !== void 0) {
1397
+ lines.push(
1398
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
1399
+ "",
1400
+ `--${boundary}`,
1401
+ ...textPart(text2, "plain"),
1402
+ `--${boundary}`,
1403
+ ...textPart(mail.html, "html"),
1404
+ `--${boundary}--`,
1405
+ ""
1406
+ );
1407
+ } else {
1408
+ lines.push(...textPart(text2, "plain"));
1409
+ }
1410
+ return lines.join("\r\n");
1411
+ }
1412
+
1413
+ // src/vendors/gmail/index.ts
1414
+ var BASE = "/gmail/v1/users/me";
1415
+ var REST_BYTES = 16 * 1024;
1416
+ var MAX_LISTED_ATTACHMENTS = 20;
1417
+ var MAX_LABELS = 100;
1418
+ var THREAD_BODY_CHARS = 3e3;
1419
+ var MAX_OFFSET = 1e5;
1420
+ var PARALLEL_READS = 5;
1421
+ var LIST_HEADERS = ["From", "To", "Subject", "Date"];
1422
+ var ID = "^[A-Za-z0-9_-]{1,100}$";
1423
+ var MESSAGE_ID = { type: "string", pattern: ID, description: "The message id, from list_messages." };
1424
+ var MESSAGE_IDS = {
1425
+ type: "array",
1426
+ items: { type: "string", pattern: ID },
1427
+ minItems: 1,
1428
+ maxItems: 1e3,
1429
+ uniqueItems: true,
1430
+ description: "Message ids, from list_messages (1 to 1000)."
1431
+ };
1432
+ var LABEL_IDS = {
1433
+ type: "array",
1434
+ items: { type: "string", minLength: 1, maxLength: 200 },
1435
+ maxItems: 100,
1436
+ uniqueItems: true
1437
+ };
1438
+ var ADDRESSES = {
1439
+ type: "array",
1440
+ items: { type: "string", minLength: 3, maxLength: 320, pattern: "^[^\\r\\n]*@[^\\r\\n]*$" },
1441
+ maxItems: 100,
1442
+ uniqueItems: true
1443
+ };
1444
+ var CURSOR = { type: "string", description: "nextCursor from the previous result (send the same filters with it)." };
1445
+ var MAIL_FIELDS = {
1446
+ to: { ...ADDRESSES, description: 'Recipients, as "name@example.com" or "Name <name@example.com>". A reply goes to the original sender when left out.' },
1447
+ cc: { ...ADDRESSES, description: "Copy recipients." },
1448
+ bcc: { ...ADDRESSES, description: "Blind copy recipients." },
1449
+ subject: { type: "string", maxLength: 500, pattern: "^[^\\r\\n]*$", description: 'The subject. A reply takes "Re: " and the original subject when left out.' },
1450
+ body: { type: "string", maxLength: 5e5, description: "The message as plain text." },
1451
+ html_body: { type: "string", maxLength: 1e6, description: "The message as HTML, sent with a plain-text copy (the body, or text made from the HTML)." },
1452
+ reply_to_message_id: { type: "string", pattern: ID, description: "Answer this message: the mail joins its thread, with the reply headers set." }
1453
+ };
1454
+ function text(value, max) {
1455
+ return typeof value === "string" && value.trim() ? truncate(value.trim(), max) : void 0;
1456
+ }
1457
+ function messagePath(id) {
1458
+ return `${BASE}/messages/${encodeURIComponent(id)}`;
1459
+ }
1460
+ function labelsOf(message) {
1461
+ return Array.isArray(message?.labelIds) ? message.labelIds.map((label) => String(label)) : [];
1462
+ }
1463
+ function receivedAt(message) {
1464
+ const ms = Number(message?.internalDate);
1465
+ return Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : void 0;
1466
+ }
1467
+ function trimSummary(message) {
1468
+ const headers = message?.payload?.headers;
1469
+ const labels = labelsOf(message);
1470
+ return compact({
1471
+ id: message?.id,
1472
+ thread_id: message?.threadId,
1473
+ from: text(header(headers, "From"), 300),
1474
+ to: text(header(headers, "To"), 300),
1475
+ subject: text(header(headers, "Subject"), 300),
1476
+ date: text(header(headers, "Date"), 100),
1477
+ received: receivedAt(message),
1478
+ snippet: typeof message?.snippet === "string" ? truncate(decodeEntities(message.snippet), 300) : void 0,
1479
+ unread: labels.includes("UNREAD"),
1480
+ labels: labels.slice(0, MAX_LABELS)
1481
+ });
1482
+ }
1483
+ async function readSummary(h, id) {
1484
+ try {
1485
+ const { data } = await googleApi(h, { path: messagePath(id), query: { format: "metadata", metadataHeaders: LIST_HEADERS } });
1486
+ return trimSummary(data);
1487
+ } catch (error) {
1488
+ if (error instanceof ToolFailure && error.details.status === 404) return void 0;
1489
+ throw error;
1490
+ }
1491
+ }
1492
+ async function mapLimit(items, limit, fn) {
1493
+ const results = new Array(items.length);
1494
+ let next = 0;
1495
+ const worker = async () => {
1496
+ while (next < items.length) {
1497
+ const index = next++;
1498
+ results[index] = await fn(items[index]);
1499
+ }
1500
+ };
1501
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1502
+ return results;
1503
+ }
1504
+ function readFull(message) {
1505
+ const headers = message?.payload?.headers;
1506
+ return {
1507
+ headers: compact({
1508
+ from: text(header(headers, "From"), 500),
1509
+ to: text(header(headers, "To"), 2e3),
1510
+ cc: text(header(headers, "Cc"), 2e3),
1511
+ bcc: text(header(headers, "Bcc"), 2e3),
1512
+ reply_to: text(header(headers, "Reply-To"), 500),
1513
+ subject: text(header(headers, "Subject"), 1e3),
1514
+ date: text(header(headers, "Date"), 100),
1515
+ message_id_header: text(header(headers, "Message-ID"), 500),
1516
+ in_reply_to: text(header(headers, "In-Reply-To"), 500)
1517
+ }),
1518
+ parts: readPayload(message?.payload)
1519
+ };
1520
+ }
1521
+ function withPlaces(read) {
1522
+ const items = [];
1523
+ const places = [];
1524
+ read.forEach((item, place) => {
1525
+ if (item === void 0) return;
1526
+ items.push(item);
1527
+ places.push(place);
1528
+ });
1529
+ return { items, places };
1530
+ }
1531
+ async function compose(h, args, sending) {
1532
+ const format = (list, field) => (list ?? []).map((value) => {
1533
+ const item = formatAddress(value);
1534
+ if (!item) throw new ToolFailure(`${field} has an address Gmail cannot use: give "name@example.com" or "Name <name@example.com>". Nothing was sent.`);
1535
+ return item;
1536
+ });
1537
+ let to = format(args.to, "to");
1538
+ const cc = format(args.cc, "cc");
1539
+ const bcc = format(args.bcc, "bcc");
1540
+ let subject = args.subject;
1541
+ let threadId;
1542
+ let inReplyTo;
1543
+ let references;
1544
+ if (args.reply_to_message_id) {
1545
+ const { data } = await googleApi(h, {
1546
+ path: messagePath(args.reply_to_message_id),
1547
+ query: { format: "metadata", metadataHeaders: ["Message-ID", "References", "Subject", "From", "Reply-To"] },
1548
+ errors: { 404: `Gmail found no message ${args.reply_to_message_id} to reply to` }
1549
+ });
1550
+ const headers = data?.payload?.headers;
1551
+ threadId = typeof data?.threadId === "string" ? data.threadId : void 0;
1552
+ const messageId = oneLine(header(headers, "Message-ID"));
1553
+ if (messageId) {
1554
+ inReplyTo = messageId;
1555
+ references = [...oneLine(header(headers, "References"))?.split(/\s+/) ?? [], messageId].slice(-20).join(" ");
1556
+ }
1557
+ if (subject === void 0) {
1558
+ const original = oneLine(header(headers, "Subject")) ?? "";
1559
+ subject = /^re:/i.test(original) ? original : `Re: ${original}`.trim();
1560
+ }
1561
+ if (!to.length && !cc.length && !bcc.length) {
1562
+ const sender = oneLine(header(headers, "Reply-To")) ?? oneLine(header(headers, "From"));
1563
+ if (sender) to = [sender];
1564
+ }
1565
+ }
1566
+ if (sending) {
1567
+ if (!to.length && !cc.length && !bcc.length) throw new ToolFailure("Give at least one recipient in to, cc or bcc. Nothing was sent.");
1568
+ if (args.body === void 0 && args.html_body === void 0) throw new ToolFailure("Give body or html_body: the message is empty. Nothing was sent.");
1569
+ }
1570
+ const random = crypto.getRandomValues(new Uint8Array(12));
1571
+ const boundary = `part_${Array.from(random, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
1572
+ const message = buildMessage({
1573
+ to,
1574
+ cc,
1575
+ bcc,
1576
+ subject: subject ?? "",
1577
+ ...args.body !== void 0 ? { text: args.body } : {},
1578
+ ...args.html_body !== void 0 ? { html: args.html_body } : {},
1579
+ ...inReplyTo ? { inReplyTo } : {},
1580
+ ...references ? { references } : {}
1581
+ }, boundary);
1582
+ return { raw: base64UrlEncode(utf8Bytes(message)), ...threadId ? { threadId } : {}, to, subject: subject ?? "" };
1583
+ }
1584
+ function settingsGuard(request) {
1585
+ if (request.method !== "GET" && request.segments[4] === "settings") {
1586
+ throw new ToolFailure("Gmail settings (forwarding, filters, delegates, send-as addresses, vacation replies) are not changed here: change them in Gmail. Nothing was sent.");
1587
+ }
1588
+ }
1589
+ var connector = defineConnector({
1590
+ vendor: "gmail",
1591
+ label: "Gmail",
1592
+ origins: ["https://gmail.googleapis.com"],
1593
+ credentials: ["access_token"],
1594
+ credentialLabels: { access_token: "Gmail access token" },
1595
+ authHeaders: (credentials) => ({ authorization: `Bearer ${credentials["access_token"]}` }),
1596
+ tools: [
1597
+ {
1598
+ name: "get_profile",
1599
+ kind: "read",
1600
+ title: "Get the Gmail mailbox",
1601
+ description: "Returns the connected mailbox: its address and its total numbers of messages and threads.",
1602
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1603
+ async run(_args, h) {
1604
+ const { data } = await googleApi(h, { path: `${BASE}/profile` });
1605
+ return compact({ email: data?.emailAddress, messages_total: data?.messagesTotal, threads_total: data?.threadsTotal, history_id: data?.historyId });
1606
+ }
1607
+ },
1608
+ {
1609
+ name: "list_messages",
1610
+ kind: "read",
1611
+ title: "List Gmail messages",
1612
+ description: `Lists messages of the mailbox, newest first, with each one's id, thread, sender, recipients, subject, date, snippet, labels and whether it is unread. query takes Gmail's search syntax: "in:inbox is:unread" for unread inbox mail, "from:alice@example.com newer_than:7d", "subject:invoice has:attachment", "in:sent". Pass nextCursor back as cursor for more.`,
1613
+ inputSchema: {
1614
+ type: "object",
1615
+ properties: {
1616
+ query: { type: "string", maxLength: 2e3, description: 'A Gmail search, such as "in:inbox is:unread". Leave out for all mail except spam and trash.' },
1617
+ label_ids: { ...LABEL_IDS, description: 'Only messages with all of these label ids, such as ["INBOX", "UNREAD"] (list_labels has the ids of your own labels).' },
1618
+ include_spam_trash: { type: "boolean", default: false, description: "Include spam and trash (default false)." },
1619
+ max_results: { type: "integer", minimum: 1, maximum: 50, default: 20, description: "Messages per page, 1 to 50 (default 20)." },
1620
+ cursor: CURSOR
1621
+ },
1622
+ additionalProperties: false
1623
+ },
1624
+ async run(args, h) {
1625
+ const state = h.cursor(args.cursor);
1626
+ const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
1627
+ const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
1628
+ const max = cursorNumber(state, "n", args.max_results, 1, 50);
1629
+ const { data } = await googleApi(h, {
1630
+ path: `${BASE}/messages`,
1631
+ query: { q: args.query, labelIds: args.label_ids, includeSpamTrash: args.include_spam_trash || void 0, maxResults: max, pageToken }
1632
+ });
1633
+ const ids = (Array.isArray(data?.messages) ? data.messages : []).map((message) => message?.id).filter((id) => typeof id === "string").slice(skip);
1634
+ const { items, places } = withPlaces(await mapLimit(ids, PARALLEL_READS, (id) => readSummary(h, id)));
1635
+ return h.page({
1636
+ key: "messages",
1637
+ items,
1638
+ extra: compact({ result_size_estimate: data?.resultSizeEstimate }),
1639
+ resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + places[index], n: max }),
1640
+ ...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0, n: max }) } : {}
1641
+ });
1642
+ }
1643
+ },
1644
+ {
1645
+ name: "get_message",
1646
+ kind: "read",
1647
+ title: "Read a Gmail message",
1648
+ description: `Reads one message: sender, recipients, subject, date, reply headers, labels, the body as text (HTML-only mail is made readable) and, with the first part of the body, up to ${MAX_LISTED_ATTACHMENTS} attachments with their ids (attachment_count is the total). A long body comes in parts: when next_content_offset is set, call again with content_offset set to it; the parts join up to the whole body. Reading a message does not mark it read; mark_as_read does.`,
1649
+ inputSchema: {
1650
+ type: "object",
1651
+ properties: {
1652
+ message_id: MESSAGE_ID,
1653
+ body_format: { type: "string", enum: ["text", "html"], default: "text", description: "text (default), or html for the HTML part as sent when there is one." },
1654
+ content_offset: { type: "integer", minimum: 0, default: 0, description: "Where to start reading the body: 0, or next_content_offset from the previous result." }
1655
+ },
1656
+ required: ["message_id"],
1657
+ additionalProperties: false
1658
+ },
1659
+ async run(args, h) {
1660
+ const { data } = await googleApi(h, {
1661
+ path: messagePath(args.message_id),
1662
+ query: { format: "full" },
1663
+ errors: { 404: `Gmail found no message ${args.message_id}`, 400: `Gmail found no message ${args.message_id}` }
1664
+ });
1665
+ const message = readFull(data);
1666
+ const allLabels = labelsOf(data);
1667
+ const labels = allLabels.slice(0, MAX_LABELS);
1668
+ const html = args.body_format === "html" && message.parts.html.length ? message.parts.html.join("\n") : void 0;
1669
+ const asText = html === void 0 ? bodyText(message.parts) : void 0;
1670
+ const body = html ?? asText?.text ?? "";
1671
+ const { attachments } = message.parts;
1672
+ let listed = args.content_offset === 0 ? attachments.slice(0, MAX_LISTED_ATTACHMENTS) : [];
1673
+ let headers = message.headers;
1674
+ const build = (part, next) => compact({
1675
+ id: data?.id,
1676
+ thread_id: data?.threadId,
1677
+ ...headers,
1678
+ received: receivedAt(data),
1679
+ unread: allLabels.includes("UNREAD"),
1680
+ labels,
1681
+ body_type: html !== void 0 ? "html" : asText?.from === "html" ? "text from html" : asText?.from,
1682
+ body_length: body.length,
1683
+ body_note: asText?.cut ? `The HTML part is longer than ${formatNumber(MAX_HTML_CHARS)} characters: the text was made from its first ${formatNumber(MAX_HTML_CHARS)}. body_format html returns all of it.` : void 0,
1684
+ body: part,
1685
+ next_content_offset: next,
1686
+ attachment_count: attachments.length || void 0,
1687
+ attachments: listed.length ? listed : void 0,
1688
+ size: data?.sizeEstimate
1689
+ });
1690
+ const restSize = () => jsonSize(build("", body.length));
1691
+ while (listed.length && restSize() > REST_BYTES) listed = listed.slice(0, -1);
1692
+ if (restSize() > REST_BYTES) {
1693
+ const others = restSize() - jsonSize(headers);
1694
+ headers = shrinkToFit(headers, Math.max(0, REST_BYTES - others))?.value ?? {};
1695
+ }
1696
+ return fitTextPart(body, args.content_offset, build);
1697
+ }
1698
+ },
1699
+ {
1700
+ name: "get_thread",
1701
+ kind: "read",
1702
+ title: "Read a Gmail thread",
1703
+ description: `Reads a conversation: every message of the thread, oldest first, with sender, recipients, date, subject, labels, the body as text (each cut at ${THREAD_BODY_CHARS} characters; get_message reads one whole) and the attachment names. Pass nextCursor back as cursor for more.`,
1704
+ inputSchema: {
1705
+ type: "object",
1706
+ properties: {
1707
+ thread_id: { type: "string", pattern: ID, description: "The thread id, from list_messages." },
1708
+ cursor: { type: "string", description: "nextCursor from the previous result." }
1709
+ },
1710
+ required: ["thread_id"],
1711
+ additionalProperties: false
1712
+ },
1713
+ async run(args, h) {
1714
+ const state = h.cursor(args.cursor);
1715
+ const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
1716
+ const { data } = await googleApi(h, {
1717
+ path: `${BASE}/threads/${encodeURIComponent(args.thread_id)}`,
1718
+ query: { format: "full" },
1719
+ errors: { 404: `Gmail found no thread ${args.thread_id}`, 400: `Gmail found no thread ${args.thread_id}` }
1720
+ });
1721
+ const messages = (Array.isArray(data?.messages) ? data.messages : []).map((item) => {
1722
+ const message = readFull(item);
1723
+ const labels = labelsOf(item);
1724
+ const { attachments } = message.parts;
1725
+ return compact({
1726
+ id: item?.id,
1727
+ ...message.headers,
1728
+ received: receivedAt(item),
1729
+ unread: labels.includes("UNREAD"),
1730
+ labels: labels.slice(0, MAX_LABELS),
1731
+ body: truncate(bodyText(message.parts).text, THREAD_BODY_CHARS),
1732
+ attachments: attachments.length ? attachments.map((attachment) => attachment.filename ?? attachment.mime_type).slice(0, 20) : void 0
1733
+ });
1734
+ });
1735
+ return h.page({
1736
+ key: "messages",
1737
+ items: messages.slice(skip),
1738
+ extra: { thread_id: data?.id ?? args.thread_id, message_count: messages.length },
1739
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
1740
+ });
1741
+ }
1742
+ },
1743
+ {
1744
+ name: "list_labels",
1745
+ kind: "read",
1746
+ title: "List Gmail labels",
1747
+ description: "Lists the labels of the mailbox, system ones (INBOX, UNREAD, STARRED, IMPORTANT, SENT, SPAM, TRASH) and your own, with the id each tool takes.",
1748
+ inputSchema: { type: "object", properties: { cursor: { type: "string", description: "nextCursor from the previous result." } }, additionalProperties: false },
1749
+ async run(args, h) {
1750
+ const state = h.cursor(args.cursor);
1751
+ const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
1752
+ const { data } = await googleApi(h, { path: `${BASE}/labels` });
1753
+ const labels = (Array.isArray(data?.labels) ? data.labels : []).map((label) => compact({ id: label?.id, name: text(label?.name, 300), type: typeof label?.type === "string" ? label.type.toLowerCase() : void 0 }));
1754
+ return h.page({ key: "labels", items: labels.slice(skip), resumeAt: (index) => h.makeCursor({ o: skip + index }) });
1755
+ }
1756
+ },
1757
+ {
1758
+ name: "list_drafts",
1759
+ kind: "read",
1760
+ title: "List Gmail drafts",
1761
+ description: "Lists the drafts of the mailbox, newest first, with each one's draft id, message id, recipients, subject and snippet. Pass nextCursor back as cursor for more.",
1762
+ inputSchema: {
1763
+ type: "object",
1764
+ properties: {
1765
+ query: { type: "string", maxLength: 2e3, description: 'A Gmail search to narrow the drafts, such as "subject:offer".' },
1766
+ max_results: { type: "integer", minimum: 1, maximum: 50, default: 20, description: "Drafts per page, 1 to 50 (default 20)." },
1767
+ cursor: CURSOR
1768
+ },
1769
+ additionalProperties: false
1770
+ },
1771
+ async run(args, h) {
1772
+ const state = h.cursor(args.cursor);
1773
+ const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
1774
+ const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
1775
+ const max = cursorNumber(state, "n", args.max_results, 1, 50);
1776
+ const { data } = await googleApi(h, { path: `${BASE}/drafts`, query: { q: args.query, maxResults: max, pageToken } });
1777
+ const drafts = (Array.isArray(data?.drafts) ? data.drafts : []).filter((draft) => typeof draft?.message?.id === "string").slice(skip);
1778
+ const { items, places } = withPlaces(await mapLimit(drafts, PARALLEL_READS, async (draft) => {
1779
+ const summary = await readSummary(h, draft.message.id);
1780
+ return summary ? { draft_id: draft.id, ...summary } : void 0;
1781
+ }));
1782
+ return h.page({
1783
+ key: "drafts",
1784
+ items,
1785
+ resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + places[index], n: max }),
1786
+ ...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0, n: max }) } : {}
1787
+ });
1788
+ }
1789
+ },
1790
+ {
1791
+ name: "mark_as_read",
1792
+ kind: "update",
1793
+ check: "get_message",
1794
+ title: "Mark Gmail messages read or unread",
1795
+ description: "Marks messages as read (default) or, with read: false, as unread. Returns how many were changed.",
1796
+ inputSchema: {
1797
+ type: "object",
1798
+ properties: {
1799
+ message_ids: MESSAGE_IDS,
1800
+ read: { type: "boolean", default: true, description: "true (default) marks them read, false unread." }
1801
+ },
1802
+ required: ["message_ids"],
1803
+ additionalProperties: false
1804
+ },
1805
+ async run(args, h) {
1806
+ await googleApi(h, {
1807
+ method: "POST",
1808
+ path: `${BASE}/messages/batchModify`,
1809
+ json: { ids: args.message_ids, ...args.read ? { removeLabelIds: ["UNREAD"] } : { addLabelIds: ["UNREAD"] } },
1810
+ write: true
1811
+ });
1812
+ return { updated: args.message_ids.length, read: args.read };
1813
+ }
1814
+ },
1815
+ {
1816
+ name: "modify_labels",
1817
+ kind: "update",
1818
+ check: "get_message",
1819
+ title: "Add or remove Gmail labels",
1820
+ description: 'Adds labels to messages and removes others, by label id (list_labels): archive by removing INBOX, star with STARRED, file under one of your labels with its id such as "Label_12". Returns how many messages were changed.',
1821
+ inputSchema: {
1822
+ type: "object",
1823
+ properties: {
1824
+ message_ids: MESSAGE_IDS,
1825
+ add_label_ids: { ...LABEL_IDS, description: "Label ids to add." },
1826
+ remove_label_ids: { ...LABEL_IDS, description: "Label ids to remove." }
1827
+ },
1828
+ required: ["message_ids"],
1829
+ additionalProperties: false
1830
+ },
1831
+ async run(args, h) {
1832
+ if (!args.add_label_ids?.length && !args.remove_label_ids?.length) {
1833
+ throw new ToolFailure("Nothing to change: give add_label_ids or remove_label_ids. Nothing was changed.");
1834
+ }
1835
+ await googleApi(h, {
1836
+ method: "POST",
1837
+ path: `${BASE}/messages/batchModify`,
1838
+ json: { ids: args.message_ids, ...args.add_label_ids?.length ? { addLabelIds: args.add_label_ids } : {}, ...args.remove_label_ids?.length ? { removeLabelIds: args.remove_label_ids } : {} },
1839
+ write: true,
1840
+ errors: { 400: "Gmail did not accept the change: check the message and label ids (list_labels)" }
1841
+ });
1842
+ return compact({ updated: args.message_ids.length, added: args.add_label_ids, removed: args.remove_label_ids });
1843
+ }
1844
+ },
1845
+ {
1846
+ name: "trash_message",
1847
+ kind: "delete",
1848
+ check: "get_message",
1849
+ title: "Move a Gmail message to the trash",
1850
+ description: "Moves a message to the trash. Gmail deletes it for good after 30 days; until then it can be taken back out of the trash in Gmail.",
1851
+ inputSchema: { type: "object", properties: { message_id: MESSAGE_ID }, required: ["message_id"], additionalProperties: false },
1852
+ async run(args, h) {
1853
+ const { data } = await googleApi(h, {
1854
+ method: "POST",
1855
+ path: `${messagePath(args.message_id)}/trash`,
1856
+ write: true,
1857
+ errors: { 404: `Gmail found no message ${args.message_id}` }
1858
+ });
1859
+ return { trashed: true, message_id: data?.id ?? args.message_id, labels: labelsOf(data) };
1860
+ }
1861
+ },
1862
+ {
1863
+ name: "create_label",
1864
+ kind: "create",
1865
+ check: "list_labels",
1866
+ title: "Create a Gmail label",
1867
+ description: "Creates a label in the mailbox, shown in the label list and on messages unless told otherwise. Returns its id. Gmail refuses a name that exists.",
1868
+ inputSchema: {
1869
+ type: "object",
1870
+ properties: {
1871
+ name: { type: "string", minLength: 1, maxLength: 225, pattern: "^[^\\r\\n]+$", description: 'The label name; a slash nests it under another label, such as "Clients/Acme".' },
1872
+ show_in_label_list: { type: "boolean", default: true, description: "Show it in the label list (default true)." },
1873
+ show_in_message_list: { type: "boolean", default: true, description: "Show it on messages in the list (default true)." }
1874
+ },
1875
+ required: ["name"],
1876
+ additionalProperties: false
1877
+ },
1878
+ async run(args, h) {
1879
+ const { data } = await googleApi(h, {
1880
+ method: "POST",
1881
+ path: `${BASE}/labels`,
1882
+ json: {
1883
+ name: args.name,
1884
+ labelListVisibility: args.show_in_label_list ? "labelShow" : "labelHide",
1885
+ messageListVisibility: args.show_in_message_list ? "show" : "hide"
1886
+ },
1887
+ write: true,
1888
+ errors: { 409: "Gmail already has a label with that name" }
1889
+ });
1890
+ return compact({ id: data?.id, name: data?.name, type: typeof data?.type === "string" ? data.type.toLowerCase() : void 0 });
1891
+ }
1892
+ },
1893
+ {
1894
+ name: "create_draft",
1895
+ kind: "create",
1896
+ check: "list_drafts",
1897
+ title: "Save a Gmail draft",
1898
+ description: "Saves a message as a draft in the mailbox, without sending it: to show a reply or a new mail before it goes out. With reply_to_message_id it joins that thread as a reply. Send it later with send_draft. Returns the draft id.",
1899
+ inputSchema: { type: "object", properties: { ...MAIL_FIELDS }, additionalProperties: false },
1900
+ async run(args, h) {
1901
+ const mail = await compose(h, args, false);
1902
+ const { data } = await googleApi(h, {
1903
+ method: "POST",
1904
+ path: `${BASE}/drafts`,
1905
+ json: { message: { raw: mail.raw, ...mail.threadId ? { threadId: mail.threadId } : {} } },
1906
+ write: true
1907
+ });
1908
+ return compact({ draft_id: data?.id, message_id: data?.message?.id, thread_id: data?.message?.threadId, to: mail.to.length ? mail.to : void 0, subject: mail.subject });
1909
+ }
1910
+ },
1911
+ {
1912
+ name: "send_draft",
1913
+ kind: "create",
1914
+ check: "list_messages",
1915
+ title: "Send a Gmail draft",
1916
+ description: "Sends a saved draft as it is, from the mailbox. It cannot be called back: send only what was approved. Returns the sent message id.",
1917
+ inputSchema: {
1918
+ type: "object",
1919
+ properties: { draft_id: { type: "string", pattern: ID, description: "The draft id, from create_draft or list_drafts." } },
1920
+ required: ["draft_id"],
1921
+ additionalProperties: false
1922
+ },
1923
+ async run(args, h) {
1924
+ const { data } = await googleApi(h, {
1925
+ method: "POST",
1926
+ path: `${BASE}/drafts/send`,
1927
+ json: { id: args.draft_id },
1928
+ write: true,
1929
+ errors: { 404: `Gmail found no draft ${args.draft_id}` }
1930
+ });
1931
+ return compact({ sent: true, message_id: data?.id, thread_id: data?.threadId, labels: labelsOf(data) });
1932
+ }
1933
+ },
1934
+ {
1935
+ name: "send_message",
1936
+ kind: "create",
1937
+ check: "list_messages",
1938
+ title: "Send a Gmail message",
1939
+ description: 'Sends a mail from the mailbox right away, as plain text or HTML (with a plain-text copy). With reply_to_message_id it answers that message in its thread, to the original sender unless to is given. It cannot be called back: send only what was approved (create_draft saves one for review). Sent once; when the outcome is unclear, look in Sent (list_messages with "in:sent") before sending again.',
1940
+ inputSchema: { type: "object", properties: { ...MAIL_FIELDS }, additionalProperties: false },
1941
+ async run(args, h) {
1942
+ const mail = await compose(h, args, true);
1943
+ const { data } = await googleApi(h, {
1944
+ method: "POST",
1945
+ path: `${BASE}/messages/send`,
1946
+ json: { raw: mail.raw, ...mail.threadId ? { threadId: mail.threadId } : {} },
1947
+ write: true
1948
+ });
1949
+ return compact({ sent: true, message_id: data?.id, thread_id: data?.threadId, to: mail.to, subject: mail.subject, labels: labelsOf(data) });
1950
+ }
1951
+ },
1952
+ // The rest of the Gmail API: history, attachments, threads, drafts updates.
1953
+ ...apiTools({
1954
+ label: "Gmail",
1955
+ description: "The Gmail API v1 for the connected mailbox at https://gmail.googleapis.com/gmail/v1/users/me: paths start with /gmail/v1/users/me/, such as /gmail/v1/users/me/history (startHistoryId in query), /gmail/v1/users/me/messages/MESSAGE_ID/attachments/ATTACHMENT_ID, /gmail/v1/users/me/threads/THREAD_ID/modify or /gmail/v1/users/me/drafts/DRAFT_ID (a DELETE there deletes the draft for good, as one on /gmail/v1/users/me/labels/LABEL_ID does the label). Settings are read only, and messages and threads cannot be deleted for good. Reference: https://developers.google.com/gmail/api/reference/rest.",
1956
+ basePath: "/gmail/v1/users/me/",
1957
+ guard: settingsGuard,
1958
+ send: (request, h) => googleApi(h, request)
1959
+ })
1960
+ ]
1961
+ });
1962
+ module.exports = connector;