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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1131 -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 +1 -1
@@ -0,0 +1,2654 @@
1
+ /* google-drive connector module (MIT License). Built from src/vendors/google-drive; 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(text) {
41
+ return encoder.encode(text);
42
+ }
43
+ function utf8Length(text) {
44
+ return encoder.encode(text).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(text) {
60
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
61
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.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 base64Decode(text) {
68
+ const clean = text.replace(/\s+/g, "");
69
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 === 1) throw new Error("not base64");
70
+ const binary = atob(clean);
71
+ const bytes = new Uint8Array(binary.length);
72
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
73
+ return bytes;
74
+ }
75
+ async function sha256Hex(text) {
76
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(text)));
77
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
78
+ }
79
+ function truncate(text, max) {
80
+ if (text.length <= max) return text;
81
+ const points = Array.from(text);
82
+ if (points.length <= max) return text;
83
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
84
+ }
85
+ function cleanVendorText(text, max = 300) {
86
+ if (typeof text !== "string") return void 0;
87
+ if (/^\s*</.test(text)) return void 0;
88
+ const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
89
+ return line ? truncate(line, max) : void 0;
90
+ }
91
+ function formatNumber(value) {
92
+ return value.toLocaleString("en-US");
93
+ }
94
+
95
+ // src/core/output.ts
96
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
97
+ function jsonSize(value) {
98
+ return utf8Length(JSON.stringify(value) ?? "");
99
+ }
100
+ function cutStrings(value, max) {
101
+ if (typeof value === "string") return truncate(value, max);
102
+ if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
103
+ if (typeof value === "object" && value !== null) {
104
+ const out = {};
105
+ for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
106
+ return out;
107
+ }
108
+ return value;
109
+ }
110
+ function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
111
+ if (jsonSize(value) <= limit) return { value, truncated: false };
112
+ for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
113
+ const cut = cutStrings(value, max);
114
+ if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
115
+ }
116
+ return void 0;
117
+ }
118
+ function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
119
+ const build = (count) => {
120
+ const cut = count < input.items.length;
121
+ const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
122
+ const next = cut ? input.resumeAt(count) : input.nextPage;
123
+ if (next) result2["nextCursor"] = next;
124
+ if (cut) result2["truncated"] = true;
125
+ return result2;
126
+ };
127
+ const all = build(input.items.length);
128
+ if (jsonSize(all) <= limit) return all;
129
+ let low = 1;
130
+ let high = input.items.length - 1;
131
+ while (low < high) {
132
+ const middle = Math.ceil((low + high) / 2);
133
+ if (jsonSize(build(middle)) <= limit) low = middle;
134
+ else high = middle - 1;
135
+ }
136
+ const best = build(low);
137
+ if (jsonSize(best) <= limit) return best;
138
+ const shrunk = shrinkToFit(best, limit);
139
+ if (shrunk) return { ...shrunk.value, truncated: true };
140
+ throw new ToolFailure("The result is too large to return, even one item at a time.");
141
+ }
142
+ function encodeCursor(tool, state) {
143
+ return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
144
+ }
145
+ function decodeCursor(tool, cursor) {
146
+ if (cursor === void 0 || cursor === "") return null;
147
+ try {
148
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
149
+ if (typeof state === "object" && state !== null && state.t === tool) {
150
+ return state;
151
+ }
152
+ } catch {
153
+ }
154
+ throw new ToolFailure(
155
+ "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."
156
+ );
157
+ }
158
+
159
+ // src/core/api-tools.ts
160
+ var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
161
+ var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
162
+ var NOTE_ROOM = 400;
163
+ var MAX_CUT_POINTS = 4e4;
164
+ function isQueryValue(value) {
165
+ return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
166
+ }
167
+ function nothingSent(sentence) {
168
+ return new ToolFailure(`${sentence} Nothing was sent.`);
169
+ }
170
+ function fitReply(reply) {
171
+ if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
172
+ const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
173
+ if (shrunk) {
174
+ return {
175
+ ...shrunk.value,
176
+ truncated: true,
177
+ note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
178
+ };
179
+ }
180
+ const text = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
181
+ const points = Array.from(text.length > MAX_CUT_POINTS ? text.slice(0, MAX_CUT_POINTS) : text);
182
+ if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
183
+ const cut = (count) => ({
184
+ status: reply["status"],
185
+ ...reply["headers"] ? { headers: reply["headers"] } : {},
186
+ truncated: true,
187
+ note: `The reply has ${formatNumber(utf8Length(text))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
188
+ text: points.slice(0, count).join("")
189
+ });
190
+ let low = 0;
191
+ let high = points.length;
192
+ while (low < high) {
193
+ const middle = Math.ceil((low + high) / 2);
194
+ if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
195
+ else high = middle - 1;
196
+ }
197
+ return cut(low);
198
+ }
199
+ function shapeReply(response, headerNames) {
200
+ const reply = { status: response.status };
201
+ const headers = {};
202
+ for (const name2 of headerNames) {
203
+ const value = response.headers.get(name2);
204
+ if (value) headers[name2] = truncate(value, 2e3);
205
+ }
206
+ if (Object.keys(headers).length) reply["headers"] = headers;
207
+ const type = response.headers.get("content-type") ?? "";
208
+ if (type && !TEXT_TYPES.test(type)) {
209
+ reply["contentType"] = truncate(type, 200);
210
+ reply["note"] = "The reply is a binary file and is not shown.";
211
+ return reply;
212
+ }
213
+ if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
214
+ return fitReply(reply);
215
+ }
216
+ function checkAccounts(rule, request, h) {
217
+ const label = rule.label ?? "account";
218
+ const allowed = allowedAccounts(h.ctx.accounts, rule.key);
219
+ if (allowed === null) return;
220
+ const namesNone = nothingSent(
221
+ `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.`)
222
+ );
223
+ if (rule.ids) {
224
+ const ids = rule.ids(request).map(String);
225
+ if (!ids.length) throw namesNone;
226
+ requireAccounts(h.ctx.accounts, rule.key, ids, label);
227
+ return;
228
+ }
229
+ if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
230
+ }
231
+ function apiTools(options) {
232
+ const { label, basePath } = options;
233
+ const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
234
+ const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
235
+ const base = basePath?.replace(/\/+$/, "");
236
+ const pathSchema = {
237
+ type: "string",
238
+ minLength: 1,
239
+ maxLength: 2e3,
240
+ pattern: "^(?!.*//)/[^?#]*$",
241
+ description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
242
+ };
243
+ const querySchema = {
244
+ type: "object",
245
+ description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
246
+ };
247
+ const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
248
+ async function run(method, args, h) {
249
+ let origin = h.origins[0];
250
+ if (args.origin !== void 0) {
251
+ let wanted;
252
+ try {
253
+ wanted = new URL(args.origin).origin;
254
+ } catch {
255
+ }
256
+ if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
257
+ origin = wanted;
258
+ }
259
+ const url = new URL(args.path, origin);
260
+ if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
261
+ const path = url.pathname;
262
+ if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
263
+ let segments;
264
+ try {
265
+ segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
266
+ } catch {
267
+ throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
268
+ }
269
+ if (segments[segments.length - 1] === "") segments.pop();
270
+ const query = {};
271
+ const queryLists = {};
272
+ for (const [key, value] of Object.entries(args.query ?? {})) {
273
+ if (value === void 0 || value === null) continue;
274
+ const list = Array.isArray(value) ? value : [value];
275
+ if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
276
+ query[key] = Array.isArray(value) ? list : value;
277
+ queryLists[key] = list.map(String);
278
+ }
279
+ const request = { method, origin, path, query };
280
+ if (method !== "GET") {
281
+ if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
282
+ if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
283
+ if (args.json !== void 0 && !args.content_type) {
284
+ request.json = args.json;
285
+ } else if (args.json !== void 0 || args.body !== void 0) {
286
+ request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
287
+ request.contentType = args.content_type;
288
+ }
289
+ request.write = true;
290
+ }
291
+ const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
292
+ if (options.accounts) checkAccounts(options.accounts, info, h);
293
+ await options.guard?.(info, h);
294
+ const response = options.send ? await options.send(request, h) : await h.api(request);
295
+ return shapeReply(response, headerNames);
296
+ }
297
+ return [
298
+ {
299
+ name: "api_get",
300
+ kind: "read",
301
+ title: `Call the ${label} API (GET)`,
302
+ 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.`,
303
+ inputSchema: {
304
+ type: "object",
305
+ properties: { path: pathSchema, query: querySchema, ...originSchema },
306
+ required: ["path"],
307
+ additionalProperties: false
308
+ },
309
+ run: (args, h) => run("GET", args, h)
310
+ },
311
+ {
312
+ name: "api_request",
313
+ kind: "write",
314
+ check: "api_get",
315
+ title: `Send a request to the ${label} API`,
316
+ 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.`,
317
+ inputSchema: {
318
+ type: "object",
319
+ properties: {
320
+ method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
321
+ path: pathSchema,
322
+ query: querySchema,
323
+ json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
324
+ body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
325
+ content_type: {
326
+ type: "string",
327
+ pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
328
+ maxLength: 200,
329
+ description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
330
+ },
331
+ ...originSchema
332
+ },
333
+ required: ["method", "path"],
334
+ additionalProperties: false
335
+ },
336
+ run: (args, h) => run(args.method, args, h)
337
+ }
338
+ ];
339
+ }
340
+
341
+ // src/core/credentials.ts
342
+ function requiredAlternatives(module2) {
343
+ return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
344
+ }
345
+ function unmetAlternatives(alternatives, has) {
346
+ const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
347
+ if (lacking.some((list) => list.length === 0)) return [];
348
+ return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
349
+ }
350
+ function andList(items) {
351
+ if (items.length <= 2) return items.join(" and ");
352
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
353
+ }
354
+ function orList(items) {
355
+ if (items.length <= 1) return items.join("");
356
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
357
+ }
358
+
359
+ // src/core/files.ts
360
+ var ATTACHMENT_URI = "attachment:///";
361
+ var MAX_NAME = 200;
362
+ function fileLimitOf(ctx) {
363
+ const maxBytes = ctx.files?.maxBytes;
364
+ return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
365
+ }
366
+ function fileName(name2) {
367
+ const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
368
+ const points = Array.from(clean);
369
+ if (points.length <= MAX_NAME) return clean || "file";
370
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
371
+ return points.slice(0, MAX_NAME - extension.length).join("") + extension;
372
+ }
373
+ function fileType(mimeType) {
374
+ const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
375
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
376
+ }
377
+ function resourceBlock(file) {
378
+ return {
379
+ type: "resource",
380
+ resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
381
+ };
382
+ }
383
+
384
+ // src/core/http.ts
385
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
386
+ var USER_AGENT = "agent-connectors";
387
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
388
+ function errorCode(error) {
389
+ const code = error?.code;
390
+ return typeof code === "string" ? code : void 0;
391
+ }
392
+ function describe(error) {
393
+ const name2 = error?.name;
394
+ const code = errorCode(error);
395
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
396
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
397
+ if (code === "TOO_LARGE") return "the reply was too large";
398
+ return cleanVendorText(error?.message, 200) ?? "a network error";
399
+ }
400
+ function retryAfterSeconds(headers, now = Date.now()) {
401
+ const retryAfter = headers.get("retry-after");
402
+ if (retryAfter) {
403
+ const seconds = Number(retryAfter);
404
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
405
+ const date = Date.parse(retryAfter);
406
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
407
+ }
408
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
409
+ if (reset) {
410
+ const value = Number(reset);
411
+ if (Number.isFinite(value) && value >= 0) {
412
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
413
+ }
414
+ }
415
+ return void 0;
416
+ }
417
+ function vendorCode(data) {
418
+ if (typeof data !== "object" || data === null) return void 0;
419
+ for (const key of ["error", "code"]) {
420
+ const value = data[key];
421
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
422
+ }
423
+ return void 0;
424
+ }
425
+ function vendorMessage(data) {
426
+ if (typeof data === "string") return cleanVendorText(data);
427
+ if (typeof data !== "object" || data === null) return void 0;
428
+ const record = data;
429
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
430
+ const value = record[key];
431
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
432
+ const nested = value?.message;
433
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
434
+ }
435
+ if (Array.isArray(record["errors"])) {
436
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
437
+ if (messages.length) return cleanVendorText(messages.join("; "));
438
+ }
439
+ return void 0;
440
+ }
441
+ var TooLarge = class extends Error {
442
+ constructor(limit) {
443
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
444
+ this.limit = limit;
445
+ }
446
+ limit;
447
+ };
448
+ async function readCapped(response, maxBytes) {
449
+ const declared = Number(response.headers.get("content-length"));
450
+ if (Number.isFinite(declared) && declared > maxBytes) {
451
+ await response.body?.cancel().catch(() => {
452
+ });
453
+ throw new TooLarge(maxBytes);
454
+ }
455
+ if (!response.body) return new Uint8Array(0);
456
+ const reader = response.body.getReader();
457
+ const chunks = [];
458
+ let total = 0;
459
+ for (; ; ) {
460
+ const { done, value } = await reader.read();
461
+ if (done) break;
462
+ total += value.byteLength;
463
+ if (total > maxBytes) {
464
+ await reader.cancel().catch(() => {
465
+ });
466
+ throw new TooLarge(maxBytes);
467
+ }
468
+ chunks.push(value);
469
+ }
470
+ const bytes = new Uint8Array(total);
471
+ let offset = 0;
472
+ for (const chunk of chunks) {
473
+ bytes.set(chunk, offset);
474
+ offset += chunk.byteLength;
475
+ }
476
+ return bytes;
477
+ }
478
+ function parseBody(bytes, contentType) {
479
+ if (bytes.length === 0) return null;
480
+ const text = utf8Decode(bytes);
481
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
482
+ try {
483
+ return JSON.parse(text);
484
+ } catch {
485
+ }
486
+ }
487
+ return text;
488
+ }
489
+ function createHttp(env) {
490
+ const { label, ctx } = env;
491
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
492
+ 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.`;
493
+ function failureFor(status, headers, data, request) {
494
+ const message = vendorMessage(data);
495
+ const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
496
+ const retryAfter = retryAfterSeconds(headers);
497
+ const code = vendorCode(data);
498
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
499
+ const custom = request.errors?.[status];
500
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
501
+ if (status >= 500) {
502
+ if (request.write) {
503
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
504
+ }
505
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
506
+ }
507
+ if (status === 429) {
508
+ return new ToolFailure(
509
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
510
+ { status, ...extra }
511
+ );
512
+ }
513
+ if (status === 401) {
514
+ return new ToolFailure(
515
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
516
+ { status, ...extra }
517
+ );
518
+ }
519
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
520
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
521
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
522
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
523
+ }
524
+ async function api(request) {
525
+ const method = request.method ?? "GET";
526
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
527
+ throw new Error(`read-only tool sent ${method}`);
528
+ }
529
+ const origin = request.origin ?? env.origins[0];
530
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
531
+ const url = new URL(request.path, origin);
532
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
533
+ for (const [key, value] of Object.entries(request.query ?? {})) {
534
+ if (value === void 0 || value === null) continue;
535
+ if (Array.isArray(value)) {
536
+ url.searchParams.delete(key);
537
+ for (const item of value) url.searchParams.append(key, String(item));
538
+ } else {
539
+ url.searchParams.set(key, String(value));
540
+ }
541
+ }
542
+ const headers = {
543
+ accept: "application/json",
544
+ "user-agent": USER_AGENT,
545
+ ...request.auth === false ? {} : env.authHeaders(),
546
+ ...request.headers
547
+ };
548
+ let body;
549
+ if (request.json !== void 0) {
550
+ body = JSON.stringify(request.json);
551
+ headers["content-type"] = "application/json";
552
+ } else if (request.body) {
553
+ body = request.body;
554
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
555
+ }
556
+ const started = Date.now();
557
+ if (request.write) env.onWriteSent();
558
+ let response;
559
+ try {
560
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
561
+ } catch (error) {
562
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
563
+ if (errorCode(error) === "URL_REFUSED") {
564
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
565
+ }
566
+ if (request.write) {
567
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
568
+ }
569
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
570
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
571
+ }
572
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
573
+ let bytes;
574
+ try {
575
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
576
+ } catch (error) {
577
+ if (request.write && (response.ok || response.status >= 500)) {
578
+ 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.`);
579
+ }
580
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
581
+ }
582
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
583
+ if (response.ok) return { status: response.status, headers: response.headers, data };
584
+ throw failureFor(response.status, response.headers, data, request);
585
+ }
586
+ async function media(rawUrl, options) {
587
+ const { what } = options;
588
+ let url;
589
+ try {
590
+ url = new URL(rawUrl);
591
+ } catch {
592
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
593
+ }
594
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
595
+ const started = Date.now();
596
+ let response;
597
+ try {
598
+ response = await ctx.fetch(url.toString(), {
599
+ method: "GET",
600
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
601
+ ...ctx.signal ? { signal: ctx.signal } : {}
602
+ });
603
+ } catch (error) {
604
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
605
+ if (errorCode(error) === "URL_REFUSED") {
606
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
607
+ }
608
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
609
+ }
610
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
611
+ if (!response.ok) {
612
+ await response.body?.cancel().catch(() => {
613
+ });
614
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
615
+ }
616
+ try {
617
+ const bytes = await readCapped(response, options.maxBytes);
618
+ return { bytes, contentType: response.headers.get("content-type") };
619
+ } catch (error) {
620
+ if (error instanceof TooLarge) {
621
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
622
+ }
623
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
624
+ }
625
+ }
626
+ return { api, media };
627
+ }
628
+
629
+ // src/core/origins.ts
630
+ function parseSiteUrl(value) {
631
+ const text = typeof value === "string" ? value.trim() : "";
632
+ if (!text) return { ok: false, problem: "is empty" };
633
+ let url;
634
+ try {
635
+ url = new URL(text.includes("://") ? text : `https://${text}`);
636
+ } catch {
637
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
638
+ }
639
+ if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
640
+ if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
641
+ if (!url.hostname) return { ok: false, problem: "has no host name" };
642
+ return { ok: true, url, origin: url.origin };
643
+ }
644
+
645
+ // src/core/schema.ts
646
+ var patterns = /* @__PURE__ */ new Map();
647
+ function patternOf(source) {
648
+ let compiled = patterns.get(source);
649
+ if (!compiled) {
650
+ compiled = new RegExp(source, "u");
651
+ patterns.set(source, compiled);
652
+ }
653
+ return compiled;
654
+ }
655
+ function isPlainObject(value) {
656
+ return typeof value === "object" && value !== null && !Array.isArray(value);
657
+ }
658
+ function isHttpUrl(value) {
659
+ try {
660
+ const url = new URL(value);
661
+ return url.protocol === "https:" || url.protocol === "http:";
662
+ } catch {
663
+ return false;
664
+ }
665
+ }
666
+ function name(path) {
667
+ return `\`${path}\``;
668
+ }
669
+ function child(path, key) {
670
+ return path ? `${path}.${key}` : key;
671
+ }
672
+ function checkValue(schema, value, path, issues) {
673
+ switch (schema.type) {
674
+ case "object":
675
+ checkObject(schema, value, path, issues);
676
+ return;
677
+ case "array": {
678
+ if (!Array.isArray(value)) {
679
+ issues.push(`${name(path)} must be an array`);
680
+ return;
681
+ }
682
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
683
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
684
+ }
685
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
686
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
687
+ }
688
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
689
+ issues.push(`${name(path)} must not repeat an item`);
690
+ }
691
+ if (schema.items) {
692
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
693
+ }
694
+ break;
695
+ }
696
+ case "string": {
697
+ if (typeof value !== "string") {
698
+ issues.push(`${name(path)} must be a string`);
699
+ return;
700
+ }
701
+ const length = Array.from(value).length;
702
+ if (schema.minLength !== void 0 && length < schema.minLength) {
703
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
704
+ }
705
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
706
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
707
+ }
708
+ if (schema.format === "uri" && !isHttpUrl(value)) {
709
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
710
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
711
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
712
+ }
713
+ break;
714
+ }
715
+ case "integer":
716
+ case "number": {
717
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
718
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
719
+ return;
720
+ }
721
+ if (schema.minimum !== void 0 && value < schema.minimum) {
722
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
723
+ }
724
+ if (schema.maximum !== void 0 && value > schema.maximum) {
725
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
726
+ }
727
+ break;
728
+ }
729
+ case "boolean":
730
+ if (typeof value !== "boolean") {
731
+ issues.push(`${name(path)} must be true or false`);
732
+ return;
733
+ }
734
+ break;
735
+ default:
736
+ break;
737
+ }
738
+ if (schema.enum && !schema.enum.includes(value)) {
739
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
740
+ }
741
+ }
742
+ function checkObject(schema, value, path, issues) {
743
+ if (!isPlainObject(value)) {
744
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
745
+ return;
746
+ }
747
+ const properties = schema.properties ?? {};
748
+ for (const key of schema.required ?? []) {
749
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
750
+ }
751
+ const unknown = [];
752
+ for (const [key, item] of Object.entries(value)) {
753
+ const property = properties[key];
754
+ if (!property) {
755
+ if (schema.additionalProperties === false) unknown.push(key);
756
+ continue;
757
+ }
758
+ if (item === void 0 || item === null) continue;
759
+ checkValue(property, item, child(path, key), issues);
760
+ }
761
+ if (unknown.length) {
762
+ const known = Object.keys(properties);
763
+ 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(", ")})` : ""));
764
+ }
765
+ }
766
+ function copyDefault(value) {
767
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
768
+ }
769
+ function validateArguments(schema, args) {
770
+ const input = args === void 0 || args === null ? {} : args;
771
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
772
+ const value = { ...input };
773
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
774
+ const issues = [];
775
+ checkObject(schema, value, "", issues);
776
+ if (issues.length) return { ok: false, issues };
777
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
778
+ if (value[key] === null) delete value[key];
779
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
780
+ }
781
+ return { ok: true, value };
782
+ }
783
+
784
+ // src/core/upload-hosts.ts
785
+ var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
786
+ function uploadHostProblem(entry) {
787
+ if (typeof entry !== "string") return "must be a host name";
788
+ const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
789
+ const labels = name2.split(".");
790
+ if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
791
+ 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";
792
+ }
793
+ if (labels.length < 2) return "needs at least two labels, like example.com";
794
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
795
+ return void 0;
796
+ }
797
+
798
+ // src/core/connector.ts
799
+ var ANNOTATIONS = {
800
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
801
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
802
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
803
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
804
+ write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
805
+ };
806
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
807
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
808
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
809
+ var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
810
+ var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
811
+ var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
812
+ var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
813
+ function deepFreeze(value) {
814
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
815
+ Object.freeze(value);
816
+ for (const item of Object.values(value)) deepFreeze(item);
817
+ }
818
+ return value;
819
+ }
820
+ function assertDefinition(def) {
821
+ const problem = (message) => {
822
+ throw new Error(`connector "${def.vendor}": ${message}`);
823
+ };
824
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
825
+ if (!def.label?.trim()) problem("label is required");
826
+ const originFields = def.originFields ?? [];
827
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
828
+ for (const origin of def.origins) {
829
+ let url;
830
+ try {
831
+ url = new URL(origin);
832
+ } catch {
833
+ }
834
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
835
+ }
836
+ for (const name2 of def.credentials) {
837
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
838
+ }
839
+ for (const [index, name2] of originFields.entries()) {
840
+ if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
841
+ if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
842
+ }
843
+ const names = /* @__PURE__ */ new Set();
844
+ for (const tool of def.tools) {
845
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
846
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
847
+ names.add(tool.name);
848
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
849
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
850
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
851
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
852
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
853
+ }
854
+ }
855
+ for (const tool of def.tools) {
856
+ if (tool.kind === "read") continue;
857
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
858
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
859
+ }
860
+ assertUploadHosts(def, problem);
861
+ assertRequiredCredentials(def, problem);
862
+ assertAccountPickers(def, problem);
863
+ }
864
+ function assertUploadHosts(def, problem) {
865
+ const hosts = def.uploadHosts;
866
+ if (hosts === void 0) return;
867
+ if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
868
+ hosts.forEach((entry, index) => {
869
+ const wrong = uploadHostProblem(entry);
870
+ if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
871
+ if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
872
+ });
873
+ }
874
+ function assertRequiredCredentials(def, problem) {
875
+ const required = def.requiredCredentials;
876
+ if (required === void 0) return;
877
+ if (!Array.isArray(required) || !required.length) {
878
+ problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
879
+ }
880
+ required.forEach((list, index) => {
881
+ const which = `requiredCredentials[${index}]`;
882
+ if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
883
+ list.forEach((name2, position) => {
884
+ if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
885
+ if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
886
+ });
887
+ });
888
+ const lists = required;
889
+ lists.forEach((list, index) => {
890
+ const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
891
+ if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
892
+ if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
893
+ problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
894
+ }
895
+ });
896
+ }
897
+ function isDotPath(value) {
898
+ return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
899
+ }
900
+ function assertAccountPickers(def, problem) {
901
+ const pickers = def.accountPickers;
902
+ if (pickers === void 0) return;
903
+ if (!Array.isArray(pickers)) problem("accountPickers must be a list");
904
+ const keys = /* @__PURE__ */ new Set();
905
+ for (const item of pickers) {
906
+ if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
907
+ const picker = item;
908
+ const key = picker["key"];
909
+ 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}$`);
910
+ if (keys.has(key)) problem(`account picker ${key} is defined twice`);
911
+ keys.add(key);
912
+ const fail = (message) => problem(`account picker ${key}: ${message}`);
913
+ const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
914
+ if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
915
+ const { label, description, multiple, legacyField } = picker;
916
+ if (typeof label !== "string" || !label.trim()) fail("label is required");
917
+ if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
918
+ fail("description, when given, must be a text of 1 to 1024 characters");
919
+ }
920
+ if (typeof multiple !== "boolean") fail("multiple must be true or false");
921
+ const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
922
+ if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
923
+ if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
924
+ for (const field of ["idField", "nameField"]) {
925
+ if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
926
+ }
927
+ if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
928
+ fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
929
+ }
930
+ }
931
+ }
932
+ function copyPicker(picker) {
933
+ return {
934
+ key: picker.key,
935
+ label: picker.label,
936
+ ...picker.description !== void 0 ? { description: picker.description } : {},
937
+ multiple: picker.multiple,
938
+ tool: picker.tool,
939
+ idField: picker.idField,
940
+ nameField: picker.nameField,
941
+ ...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
942
+ };
943
+ }
944
+ function result(payload, isError, files = []) {
945
+ return {
946
+ content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
947
+ ...isError ? { isError: true } : {}
948
+ };
949
+ }
950
+ function failure(message, details = {}) {
951
+ return result({ error: message, ...details }, true);
952
+ }
953
+ function trimmed(values) {
954
+ const out = {};
955
+ if (typeof values !== "object" || values === null) return out;
956
+ for (const [key, value] of Object.entries(values)) {
957
+ if (value === void 0 || value === null) continue;
958
+ const text = String(value).trim();
959
+ if (text) out[key] = text;
960
+ }
961
+ return out;
962
+ }
963
+ function defineConnector(def) {
964
+ assertDefinition(def);
965
+ const { label } = def;
966
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
967
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
968
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
969
+ const required = requiredAlternatives(def);
970
+ const notConnected = (unmet) => {
971
+ const [first] = unmet;
972
+ if (unmet.length === 1 && first) {
973
+ return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
974
+ }
975
+ return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
976
+ };
977
+ const descriptors = def.tools.map((tool) => ({
978
+ name: tool.name,
979
+ title: tool.title,
980
+ description: tool.description,
981
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
982
+ annotations: { ...ANNOTATIONS[tool.kind] }
983
+ }));
984
+ async function call(toolName, args, ctx) {
985
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
986
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
987
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
988
+ const log = (text) => {
989
+ try {
990
+ ctx.log?.(text);
991
+ } catch {
992
+ }
993
+ };
994
+ const given = trimmed(ctx.credentials);
995
+ const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
996
+ const has = (name2) => Boolean(credentials[name2]);
997
+ const unmet = unmetAlternatives(required, has);
998
+ if (unmet.length) return failure(notConnected(unmet));
999
+ const complete = required.filter((list) => list.every(has));
1000
+ const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
1001
+ const fieldOrigins = /* @__PURE__ */ new Map();
1002
+ for (const name2 of def.originFields ?? []) {
1003
+ if (!given[name2] && !inUse.includes(name2)) continue;
1004
+ const site = parseSiteUrl(given[name2] ?? "");
1005
+ if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
1006
+ fieldOrigins.set(name2, site.origin);
1007
+ }
1008
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
1009
+ const parsed = validateArguments(tool.inputSchema, args);
1010
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
1011
+ const frozenCredentials = Object.freeze({ ...credentials });
1012
+ let writeSent = false;
1013
+ const fileLimit = fileLimitOf(ctx);
1014
+ const files = [];
1015
+ let fileBytes = 0;
1016
+ const http = createHttp({
1017
+ vendor: def.vendor,
1018
+ label,
1019
+ tool: tool.name,
1020
+ readOnly: tool.kind === "read",
1021
+ origins,
1022
+ // A 401 names the credentials in use (for a module that needs none, the ones given).
1023
+ credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
1024
+ ctx,
1025
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
1026
+ log,
1027
+ onWriteSent: () => {
1028
+ writeSent = true;
1029
+ }
1030
+ });
1031
+ const helpers = {
1032
+ tool: tool.name,
1033
+ credentials: frozenCredentials,
1034
+ ctx,
1035
+ origins: Object.freeze([...origins]),
1036
+ originOf: (credential) => {
1037
+ const origin = fieldOrigins.get(credential);
1038
+ if (!origin) throw new Error(`${credential} gives no origin in this call`);
1039
+ return origin;
1040
+ },
1041
+ api: http.api,
1042
+ media: http.media,
1043
+ page: (input) => fitPage(input),
1044
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
1045
+ makeCursor: (state) => encodeCursor(tool.name, state),
1046
+ fileLimit: () => fileLimit,
1047
+ file: ({ name: name2, mimeType, bytes }) => {
1048
+ if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
1049
+ const total = fileBytes + bytes.byteLength;
1050
+ if (total > fileLimit) {
1051
+ 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.`);
1052
+ }
1053
+ fileBytes = total;
1054
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
1055
+ files.push({ ...info, bytes });
1056
+ return { ...info };
1057
+ },
1058
+ log
1059
+ };
1060
+ try {
1061
+ const data = await tool.run(parsed.value, helpers);
1062
+ const fitted = shrinkToFit(data ?? {});
1063
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
1064
+ const payload = fitted.value;
1065
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
1066
+ } catch (error) {
1067
+ if (error instanceof OutcomeUnknown) {
1068
+ return result({
1069
+ outcome: "unknown",
1070
+ check: tool.check,
1071
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
1072
+ }, true);
1073
+ }
1074
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
1075
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
1076
+ if (writeSent) {
1077
+ return result({
1078
+ outcome: "unknown",
1079
+ check: tool.check,
1080
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
1081
+ }, true);
1082
+ }
1083
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
1084
+ }
1085
+ }
1086
+ return deepFreeze({
1087
+ vendor: def.vendor,
1088
+ origins: [...def.origins],
1089
+ originFields: [...def.originFields ?? []],
1090
+ uploadHosts: [...def.uploadHosts ?? []],
1091
+ credentials: [...def.credentials],
1092
+ requiredCredentials: required.map((list) => [...list]),
1093
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
1094
+ tools: descriptors,
1095
+ call
1096
+ });
1097
+ }
1098
+
1099
+ // src/core/jwt.ts
1100
+ var KEY_ALGORITHMS = {
1101
+ RS256: { import: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, sign: { name: "RSASSA-PKCS1-v1_5" }, kind: "an RSA" },
1102
+ // WebCrypto returns ECDSA signatures as raw r||s, the form JWS (ES256) needs.
1103
+ ES256: { import: { name: "ECDSA", namedCurve: "P-256" }, sign: { name: "ECDSA", hash: "SHA-256" }, kind: "a P-256 (ES256)" }
1104
+ };
1105
+ function base64UrlJson(value) {
1106
+ return base64UrlEncode(utf8Bytes(JSON.stringify(value)));
1107
+ }
1108
+ function pkcs8Der(pem, keyName) {
1109
+ const text = String(pem).replace(/\\r\\n|\\n/g, "\n").trim();
1110
+ const block = /-----BEGIN ([A-Z0-9 ]+)-----([\s\S]*?)-----END \1-----/.exec(text);
1111
+ const whole = `it must be the whole PEM text, from -----BEGIN PRIVATE KEY----- to -----END PRIVATE KEY-----`;
1112
+ if (!block) throw new ToolFailure(`The ${keyName} could not be read: ${whole}. Nothing was sent.`);
1113
+ const type = block[1];
1114
+ if (type === "ENCRYPTED PRIVATE KEY") throw new ToolFailure(`The ${keyName} is encrypted with a passphrase: use the key without one. Nothing was sent.`);
1115
+ if (type !== "PRIVATE KEY") {
1116
+ throw new ToolFailure(`The ${keyName} is a "${type}" block, not a PKCS#8 "PRIVATE KEY": convert it with openssl pkcs8 -topk8 -nocrypt. Nothing was sent.`);
1117
+ }
1118
+ try {
1119
+ return base64Decode(block[2]);
1120
+ } catch {
1121
+ throw new ToolFailure(`The ${keyName} could not be read: ${whole}. Nothing was sent.`);
1122
+ }
1123
+ }
1124
+ async function signJwt(options) {
1125
+ const keyName = options.keyName ?? "private key";
1126
+ const algorithm = KEY_ALGORITHMS[options.algorithm];
1127
+ if (!algorithm) throw new Error(`unsupported JWT algorithm ${String(options.algorithm)}`);
1128
+ const der = pkcs8Der(options.privateKey, keyName);
1129
+ let key;
1130
+ try {
1131
+ key = await crypto.subtle.importKey("pkcs8", der, algorithm.import, false, ["sign"]);
1132
+ } catch {
1133
+ throw new ToolFailure(`The ${keyName} is not ${algorithm.kind} private key. Nothing was sent.`);
1134
+ }
1135
+ const header = { alg: options.algorithm, typ: "JWT", ...options.header };
1136
+ header.alg = options.algorithm;
1137
+ const signingInput = `${base64UrlJson(header)}.${base64UrlJson(options.payload)}`;
1138
+ const signature = new Uint8Array(await crypto.subtle.sign(algorithm.sign, key, utf8Bytes(signingInput)));
1139
+ return `${signingInput}.${base64UrlEncode(signature)}`;
1140
+ }
1141
+ var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
1142
+ var GOOGLE_TOKEN_ORIGIN = "https://oauth2.googleapis.com";
1143
+ var JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
1144
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
1145
+ var MAX_CACHED_TOKENS = 64;
1146
+ var SERVICE_ACCOUNT_HELP = 'The service account key is not a Google service account key file: paste the whole JSON file Google Cloud creates for the key (IAM and admin -> Service accounts -> Keys -> Add key -> JSON), with "client_email" and "private_key" in it. Nothing was sent.';
1147
+ var googleTokens = /* @__PURE__ */ new Map();
1148
+ var pendingGoogleTokens = /* @__PURE__ */ new Map();
1149
+ function readServiceAccount(json) {
1150
+ let data;
1151
+ try {
1152
+ data = JSON.parse(json);
1153
+ } catch {
1154
+ throw new ToolFailure(SERVICE_ACCOUNT_HELP);
1155
+ }
1156
+ if (typeof data !== "object" || data === null || typeof data.client_email !== "string" || typeof data.private_key !== "string") {
1157
+ throw new ToolFailure(SERVICE_ACCOUNT_HELP);
1158
+ }
1159
+ if (data.type !== void 0 && data.type !== "service_account") {
1160
+ throw new ToolFailure(`The Google key is a "${String(data.type).slice(0, 40)}" credential, not a service account key. ${SERVICE_ACCOUNT_HELP}`);
1161
+ }
1162
+ return { clientEmail: data.client_email, privateKey: data.private_key, ...typeof data.private_key_id === "string" ? { keyId: data.private_key_id } : {} };
1163
+ }
1164
+ async function exchangeGoogleToken(h, account, options) {
1165
+ const iat = Math.floor(Date.now() / 1e3);
1166
+ const assertion = await signJwt({
1167
+ algorithm: "RS256",
1168
+ privateKey: account.privateKey,
1169
+ header: account.keyId ? { kid: account.keyId } : {},
1170
+ payload: {
1171
+ iss: account.clientEmail,
1172
+ scope: options.scopes.join(" "),
1173
+ aud: GOOGLE_TOKEN_URL,
1174
+ iat,
1175
+ exp: iat + 3600,
1176
+ ...options.subject ? { sub: options.subject } : {}
1177
+ },
1178
+ keyName: "service account private key"
1179
+ });
1180
+ const { data } = await h.api({
1181
+ method: "POST",
1182
+ origin: GOOGLE_TOKEN_ORIGIN,
1183
+ path: "/token",
1184
+ body: utf8Bytes(new URLSearchParams({ grant_type: JWT_BEARER, assertion }).toString()),
1185
+ contentType: "application/x-www-form-urlencoded",
1186
+ // The assertion is the credential: no module auth header goes with it.
1187
+ auth: false,
1188
+ // A token exchange changes nothing, so read tools may make it.
1189
+ safe: true,
1190
+ errors: {
1191
+ 400: "Google did not accept the service account key",
1192
+ 401: "Google did not accept the service account key"
1193
+ }
1194
+ });
1195
+ if (typeof data?.access_token !== "string" || !data.access_token) throw new ToolFailure("Google sent no access token for the service account.");
1196
+ const expiresIn = typeof data.expires_in === "number" && data.expires_in > 0 ? data.expires_in : 3600;
1197
+ return { token: data.access_token, expiresIn };
1198
+ }
1199
+ async function googleServiceAccountToken(h, serviceAccountJson, options) {
1200
+ if (!h.origins.includes(GOOGLE_TOKEN_ORIGIN)) throw new Error(`a module that uses googleServiceAccountToken declares ${GOOGLE_TOKEN_ORIGIN} in its origins`);
1201
+ const account = readServiceAccount(serviceAccountJson);
1202
+ const key = await sha256Hex([account.clientEmail, account.privateKey, options.scopes.join(" "), options.subject ?? ""].join("\n"));
1203
+ const cached = googleTokens.get(key);
1204
+ if (cached && cached.expiresAt > Date.now()) return cached.token;
1205
+ googleTokens.delete(key);
1206
+ const inFlight = pendingGoogleTokens.get(key);
1207
+ if (inFlight) return inFlight;
1208
+ const started = exchangeGoogleToken(h, account, options).then(({ token, expiresIn }) => {
1209
+ const now = Date.now();
1210
+ for (const [other, entry] of googleTokens) if (entry.expiresAt <= now) googleTokens.delete(other);
1211
+ while (googleTokens.size >= MAX_CACHED_TOKENS) {
1212
+ const oldest = googleTokens.keys().next().value;
1213
+ if (oldest === void 0) break;
1214
+ googleTokens.delete(oldest);
1215
+ }
1216
+ googleTokens.set(key, { token, expiresAt: now + Math.min(expiresIn, 3600) * 1e3 - TOKEN_EARLY_MS });
1217
+ return token;
1218
+ }).finally(() => pendingGoogleTokens.delete(key));
1219
+ pendingGoogleTokens.set(key, started);
1220
+ return started;
1221
+ }
1222
+
1223
+ // src/vendors/google-drive/files.ts
1224
+ var FOLDER_TYPE = "application/vnd.google-apps.folder";
1225
+ var GOOGLE_TYPES = {
1226
+ document: "application/vnd.google-apps.document",
1227
+ spreadsheet: "application/vnd.google-apps.spreadsheet",
1228
+ presentation: "application/vnd.google-apps.presentation"
1229
+ };
1230
+ function compact(value) {
1231
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
1232
+ }
1233
+ function kindOf(mimeType) {
1234
+ if (typeof mimeType !== "string") return "file";
1235
+ const match = /^application\/vnd\.google-apps\.(folder|document|spreadsheet|presentation|form|shortcut|drawing|site)$/.exec(mimeType);
1236
+ return match ? match[1] : "file";
1237
+ }
1238
+ function person(value) {
1239
+ return typeof value?.displayName === "string" && value.displayName ? value.displayName : value?.emailAddress;
1240
+ }
1241
+ function trimFile(file) {
1242
+ const owners = Array.isArray(file?.owners) ? file.owners : [];
1243
+ return compact({
1244
+ id: file?.id,
1245
+ name: file?.name,
1246
+ kind: kindOf(file?.mimeType),
1247
+ mimeType: file?.mimeType,
1248
+ size: file?.size !== void 0 && Number.isFinite(Number(file.size)) ? Number(file.size) : void 0,
1249
+ modifiedTime: file?.modifiedTime,
1250
+ createdTime: file?.createdTime,
1251
+ parents: Array.isArray(file?.parents) ? file.parents : void 0,
1252
+ driveId: file?.driveId,
1253
+ description: typeof file?.description === "string" ? truncate(file.description, 500) : void 0,
1254
+ owner: owners.length ? person(owners[0]) : void 0,
1255
+ lastModifiedBy: file?.lastModifyingUser ? person(file.lastModifyingUser) : void 0,
1256
+ starred: file?.starred === true ? true : void 0,
1257
+ trashed: file?.trashed === true ? true : void 0,
1258
+ shortcutTarget: file?.shortcutDetails?.targetId,
1259
+ webViewLink: file?.webViewLink,
1260
+ webContentLink: file?.webContentLink
1261
+ });
1262
+ }
1263
+ function queryLiteral(value) {
1264
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
1265
+ }
1266
+ var PARENT_TERM = /^'([A-Za-z0-9_-]{1,200})'\s+in\s+parents$/;
1267
+ var PLAIN_TERMS = [/^trashed\s*=\s*(true|false)$/, /^mimeType\s*(=|!=)\s*'[A-Za-z0-9.+\/-]*'$/, /^mimeType\s+contains\s+'[A-Za-z0-9.+\/-]*'$/];
1268
+ function oneFolderQuery(values) {
1269
+ if (values?.length !== 1) return void 0;
1270
+ let folder;
1271
+ for (const term of values[0].trim().split(/\s+and\s+/i)) {
1272
+ const parent = PARENT_TERM.exec(term);
1273
+ if (parent) {
1274
+ if (folder !== void 0) return void 0;
1275
+ folder = parent[1];
1276
+ } else if (!PLAIN_TERMS.some((pattern) => pattern.test(term))) {
1277
+ return void 0;
1278
+ }
1279
+ }
1280
+ return folder;
1281
+ }
1282
+ function startsWith(bytes, signature, offset = 0) {
1283
+ return signature.every((byte, index) => bytes[offset + index] === byte);
1284
+ }
1285
+ function ascii(bytes, start, end) {
1286
+ return String.fromCharCode(...bytes.subarray(start, end));
1287
+ }
1288
+ function sniffType(bytes) {
1289
+ if (startsWith(bytes, [137, 80, 78, 71, 13, 10, 26, 10])) return "image/png";
1290
+ if (startsWith(bytes, [255, 216, 255])) return "image/jpeg";
1291
+ if (ascii(bytes, 0, 6) === "GIF87a" || ascii(bytes, 0, 6) === "GIF89a") return "image/gif";
1292
+ if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP") return "image/webp";
1293
+ if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WAVE") return "audio/wav";
1294
+ if (ascii(bytes, 0, 5) === "%PDF-") return "application/pdf";
1295
+ if (ascii(bytes, 4, 8) === "ftyp") {
1296
+ const brand = ascii(bytes, 8, 12);
1297
+ if (brand === "qt ") return "video/quicktime";
1298
+ if (/^(heic|heix|mif1|msf1)$/.test(brand)) return "image/heic";
1299
+ if (brand === "M4A ") return "audio/mp4";
1300
+ return "video/mp4";
1301
+ }
1302
+ if (startsWith(bytes, [26, 69, 223, 163])) return "video/webm";
1303
+ if (ascii(bytes, 0, 3) === "ID3") return "audio/mpeg";
1304
+ if (startsWith(bytes, [80, 75, 3, 4])) return "application/zip";
1305
+ return void 0;
1306
+ }
1307
+ var BY_EXTENSION = {
1308
+ txt: "text/plain",
1309
+ csv: "text/csv",
1310
+ tsv: "text/tab-separated-values",
1311
+ md: "text/markdown",
1312
+ json: "application/json",
1313
+ html: "text/html",
1314
+ htm: "text/html",
1315
+ xml: "application/xml",
1316
+ yaml: "application/yaml",
1317
+ yml: "application/yaml",
1318
+ svg: "image/svg+xml",
1319
+ pdf: "application/pdf",
1320
+ png: "image/png",
1321
+ jpg: "image/jpeg",
1322
+ jpeg: "image/jpeg",
1323
+ gif: "image/gif",
1324
+ webp: "image/webp",
1325
+ heic: "image/heic",
1326
+ mp4: "video/mp4",
1327
+ mov: "video/quicktime",
1328
+ webm: "video/webm",
1329
+ mp3: "audio/mpeg",
1330
+ m4a: "audio/mp4",
1331
+ wav: "audio/wav",
1332
+ zip: "application/zip",
1333
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1334
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1335
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
1336
+ };
1337
+ function typeByName(name2) {
1338
+ const match = /\.([A-Za-z0-9]{1,8})$/.exec(name2);
1339
+ return match ? BY_EXTENSION[match[1].toLowerCase()] : void 0;
1340
+ }
1341
+ function uploadType(bytes, name2, given, served) {
1342
+ if (given) return given;
1343
+ const byName = typeByName(name2);
1344
+ const sniffed = sniffType(bytes);
1345
+ if (sniffed === "application/zip" && byName && byName !== "application/zip") return byName;
1346
+ if (sniffed) return sniffed;
1347
+ const header = served?.split(";")[0]?.trim().toLowerCase();
1348
+ if (header && /^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(header) && header !== "application/octet-stream" && header !== "binary/octet-stream") return header;
1349
+ return byName ?? "application/octet-stream";
1350
+ }
1351
+ var TEXT_TYPES2 = /^(text\/|application\/(json|xml|javascript|x-javascript|ecmascript|x-yaml|yaml|x-ndjson|ld\+json|sql|x-sh|x-httpd-php|csv)\b|image\/svg\+xml)/i;
1352
+ function isTextType(mimeType) {
1353
+ return TEXT_TYPES2.test(mimeType) || /\+(json|xml)$/i.test(mimeType);
1354
+ }
1355
+ function hex(bytes) {
1356
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1357
+ }
1358
+ function multipartBody(metadata, bytes, mimeType) {
1359
+ const boundary = `upload_${hex(crypto.getRandomValues(new Uint8Array(16)))}`;
1360
+ const encoder2 = new TextEncoder();
1361
+ const head = encoder2.encode(
1362
+ `--${boundary}\r
1363
+ Content-Type: application/json; charset=UTF-8\r
1364
+ \r
1365
+ ${JSON.stringify(metadata)}\r
1366
+ --${boundary}\r
1367
+ Content-Type: ${mimeType}\r
1368
+ \r
1369
+ `
1370
+ );
1371
+ const tail = encoder2.encode(`\r
1372
+ --${boundary}--`);
1373
+ const body = new Uint8Array(head.length + bytes.length + tail.length);
1374
+ body.set(head, 0);
1375
+ body.set(bytes, head.length);
1376
+ body.set(tail, head.length + bytes.length);
1377
+ return { body, contentType: `multipart/related; boundary=${boundary}` };
1378
+ }
1379
+ function checkRows(rows, field) {
1380
+ const problem = new ToolFailure(`${field} must be a list of rows, each a list of cells: text, numbers, true/false or null. Nothing was sent.`);
1381
+ for (const row of rows) {
1382
+ if (!Array.isArray(row)) throw problem;
1383
+ for (const cell of row) {
1384
+ if (cell !== null && !["string", "number", "boolean"].includes(typeof cell)) throw problem;
1385
+ if (typeof cell === "number" && !Number.isFinite(cell)) throw problem;
1386
+ }
1387
+ }
1388
+ return rows;
1389
+ }
1390
+ function toCsv(rows) {
1391
+ return rows.map((row) => row.map((cell) => {
1392
+ const text = cell === null ? "" : typeof cell === "boolean" ? cell ? "TRUE" : "FALSE" : String(cell);
1393
+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
1394
+ }).join(",")).join("\r\n");
1395
+ }
1396
+ var TEXT_BUDGET = 26e3;
1397
+ function textPage(text, offset) {
1398
+ let low = offset;
1399
+ let high = Math.min(text.length, offset + TEXT_BUDGET);
1400
+ if (jsonSize(text.slice(offset, high)) <= TEXT_BUDGET) low = high;
1401
+ while (low < high) {
1402
+ const middle = Math.ceil((low + high) / 2);
1403
+ if (jsonSize(text.slice(offset, middle)) <= TEXT_BUDGET) low = middle;
1404
+ else high = middle - 1;
1405
+ }
1406
+ if (low > offset && low < text.length && /[\ud800-\udbff]/.test(text.charAt(low - 1))) low -= 1;
1407
+ return { piece: text.slice(offset, low), ...low < text.length ? { next: low } : {} };
1408
+ }
1409
+
1410
+ // src/vendors/google-drive/service-account.ts
1411
+ var KEY_CREDENTIAL = "serviceaccountjson";
1412
+ function keyFileText(value) {
1413
+ const text = (value ?? "").trim();
1414
+ if (text.startsWith("{")) return text;
1415
+ const raw = text.replace(/^data:[^,]*;base64,/i, "").replace(/-/g, "+").replace(/_/g, "/");
1416
+ try {
1417
+ const decoded = utf8Decode(base64Decode(raw)).trim();
1418
+ if (decoded.startsWith("{")) return decoded;
1419
+ } catch {
1420
+ }
1421
+ return text;
1422
+ }
1423
+ function serviceAccountEmail(h) {
1424
+ try {
1425
+ const data = JSON.parse(keyFileText(h.credentials[KEY_CREDENTIAL]));
1426
+ const email = data?.client_email;
1427
+ return typeof email === "string" && /^[^\s@]+@[^\s@]+$/.test(email) ? email : void 0;
1428
+ } catch {
1429
+ return void 0;
1430
+ }
1431
+ }
1432
+ function serviceAccountWords(h) {
1433
+ const email = serviceAccountEmail(h);
1434
+ return email ? `the service account ${email}` : "the service account";
1435
+ }
1436
+ async function googleApi(h, scopes, request) {
1437
+ const token = await googleServiceAccountToken(h, keyFileText(h.credentials[KEY_CREDENTIAL]), { scopes });
1438
+ return h.api({ ...request, headers: { ...request.headers, authorization: `Bearer ${token}` } });
1439
+ }
1440
+
1441
+ // src/vendors/google-drive/index.ts
1442
+ var LABEL2 = "Google Drive";
1443
+ var DRIVE_ORIGIN = "https://www.googleapis.com";
1444
+ var SHEETS_ORIGIN = "https://sheets.googleapis.com";
1445
+ var DOCS_ORIGIN = "https://docs.googleapis.com";
1446
+ var TOKEN_ORIGIN = "https://oauth2.googleapis.com";
1447
+ var SCOPES = [
1448
+ "https://www.googleapis.com/auth/drive",
1449
+ "https://www.googleapis.com/auth/spreadsheets",
1450
+ "https://www.googleapis.com/auth/documents"
1451
+ ];
1452
+ var PICKER = "folders";
1453
+ var SIMPLE_UPLOAD_MAX = 5 * 1024 * 1024;
1454
+ var MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
1455
+ var MAX_TEXT_BYTES = 4 * 1024 * 1024;
1456
+ var SCAN_LIMIT_BYTES = 1e8;
1457
+ var MAX_PARENT_LOOKUPS = 20;
1458
+ var FOLDER_PAGE_SIZE = 150;
1459
+ var MAX_NAME_LOOKUPS = 25;
1460
+ var LOOKUP_BATCH = 5;
1461
+ var FILE_FIELDS = "id,name,mimeType,size,parents,driveId,createdTime,modifiedTime,webViewLink,webContentLink";
1462
+ var LIST_FIELDS = "nextPageToken,incompleteSearch,files(id,name,mimeType,size,parents,createdTime,modifiedTime,webViewLink,shortcutDetails/targetId)";
1463
+ var ID_PATTERN = "^[A-Za-z0-9_-]{1,200}$";
1464
+ var NOTHING_CHANGED = " Nothing was changed.";
1465
+ var ID = { type: "string", pattern: ID_PATTERN, description: "A Drive file or folder id (the part after /d/ or /folders/ in its link)." };
1466
+ function enc(id) {
1467
+ return encodeURIComponent(id);
1468
+ }
1469
+ var UsageLimit = class extends ToolFailure {
1470
+ };
1471
+ var USAGE_LIMIT = /rate limit|usage limit|quota exceeded|too many requests/i;
1472
+ var STORAGE_FULL = /storage quota/i;
1473
+ var EMAIL_NOT_SENT = /successfully shared but (the )?emails? could not be sent/i;
1474
+ var USER_MESSAGE = /User message:/i;
1475
+ var EXPORT_TOO_LARGE = /too large to be exported/i;
1476
+ var SHARING_RIGHTS = 'in a shared drive it needs the Content manager or Manager role, elsewhere Editor access with "Editors can change permissions and share" on';
1477
+ var SHARING_SETTINGS = "(Admin console: Apps, Google Workspace, Drive and Docs, Sharing settings)";
1478
+ function sharingAdvice(h, type, status) {
1479
+ const forbids = type === "anyone" ? `a Google Workspace sharing setting, of the organization or of the shared drive, forbids sharing outside the organization or with anyone with the link: then this file cannot leave Google Drive by link until an administrator allows it ${SHARING_SETTINGS} or a manager of the shared drive does in its settings.` : `a Google Workspace sharing setting, of the organization or of the shared drive, forbids sharing outside the organization: then only an administrator ${SHARING_SETTINGS} or a manager of the shared drive can allow it.`;
1480
+ if (status === 400) return `Google Drive did not allow this sharing. Most likely ${forbids}`;
1481
+ return `Google Drive may not let ${serviceAccountWords(h)} share it: ${SHARING_RIGHTS}. Or ${forbids}`;
1482
+ }
1483
+ function explainRefusal(h, error, sharing) {
1484
+ if (!(error instanceof ToolFailure)) return error;
1485
+ const { status } = error.details;
1486
+ if (status !== 403 && !(sharing !== void 0 && status === 400)) return error;
1487
+ const ending = error.message.endsWith(NOTHING_CHANGED) ? NOTHING_CHANGED : "";
1488
+ const text = error.message.slice(0, error.message.length - ending.length);
1489
+ if (status === 403 && EXPORT_TOO_LARGE.test(text)) {
1490
+ return new ToolFailure(`${text} Google Drive exports up to 10 MB of a Google file: export another format (txt and csv are smaller), or open it with webViewLink.`, error.details);
1491
+ }
1492
+ if (status === 403 && STORAGE_FULL.test(text)) {
1493
+ return new ToolFailure(`${text} A service account has no Drive storage of its own: use a folder in a shared drive, where files belong to the drive.${ending}`, error.details);
1494
+ }
1495
+ if (status === 403 && USAGE_LIMIT.test(text)) {
1496
+ return new UsageLimit(`${text} That is a Google Drive usage limit, not a sharing problem: wait a minute and try again.${ending}`, error.details);
1497
+ }
1498
+ if (sharing !== void 0) {
1499
+ if (EMAIL_NOT_SENT.test(text)) return error;
1500
+ return new ToolFailure(`${text} ${sharingAdvice(h, sharing, status)}${ending}`, error.details);
1501
+ }
1502
+ return new ToolFailure(
1503
+ `${text} Share the file or folder with ${serviceAccountWords(h)} (Editor, or Content manager in a shared drive), and check that the Google Drive, Sheets and Docs APIs are enabled for the key's project.${ending}`,
1504
+ error.details
1505
+ );
1506
+ }
1507
+ async function drive(h, request, sharing) {
1508
+ try {
1509
+ return await googleApi(h, SCOPES, {
1510
+ ...request,
1511
+ errors: { 404: `Google Drive found no such file, or it is not shared with ${serviceAccountWords(h)}`, ...request.errors }
1512
+ });
1513
+ } catch (error) {
1514
+ throw explainRefusal(h, error, sharing);
1515
+ }
1516
+ }
1517
+ function chosenFolders(h) {
1518
+ return allowedAccounts(h.ctx.accounts, PICKER);
1519
+ }
1520
+ async function checkInside(h, allowed, id, data, what) {
1521
+ if (!allowed.length) throw new ToolFailure(`No folder is chosen for this ${LABEL2} connection yet, so it can reach no file. Nothing was changed.`);
1522
+ if (allowed.includes(id)) return;
1523
+ const refuse = () => {
1524
+ throw new ToolFailure(`The ${what} ${id} is not inside the folders chosen for this connection (${allowed.join(", ")}). Nothing was changed.`);
1525
+ };
1526
+ const seen = /* @__PURE__ */ new Set([id]);
1527
+ let item = data;
1528
+ const frontier = [];
1529
+ let lookups = 0;
1530
+ for (; ; ) {
1531
+ if (typeof item?.driveId === "string" && allowed.includes(item.driveId)) return;
1532
+ for (const parent of Array.isArray(item?.parents) ? item.parents : []) {
1533
+ if (typeof parent !== "string" || seen.has(parent)) continue;
1534
+ if (allowed.includes(parent)) return;
1535
+ seen.add(parent);
1536
+ frontier.push(parent);
1537
+ }
1538
+ const next = frontier.shift();
1539
+ if (next === void 0 || lookups >= MAX_PARENT_LOOKUPS) refuse();
1540
+ lookups++;
1541
+ try {
1542
+ item = (await drive(h, { path: `/drive/v3/files/${enc(next)}`, query: { fields: "id,parents,driveId", supportsAllDrives: true } })).data;
1543
+ } catch (error) {
1544
+ if (error instanceof ToolFailure && !(error instanceof UsageLimit) && (error.details.status === 403 || error.details.status === 404)) refuse();
1545
+ throw error;
1546
+ }
1547
+ }
1548
+ }
1549
+ async function getChecked(h, id, fields, what = "file") {
1550
+ const allowed = chosenFolders(h);
1551
+ if (allowed !== null && !allowed.length) throw new ToolFailure(`No folder is chosen for this ${LABEL2} connection yet, so it can reach no file. Nothing was changed.`);
1552
+ const missing = ["parents", "driveId"].filter((name2) => !new RegExp(`(^|,)${name2}(,|$)`).test(fields));
1553
+ const wanted = allowed === null || !missing.length ? fields : `${fields},${missing.join(",")}`;
1554
+ const { data } = await drive(h, { path: `/drive/v3/files/${enc(id)}`, query: { fields: wanted, supportsAllDrives: true } });
1555
+ if (allowed !== null) await checkInside(h, allowed, id, data, what);
1556
+ return data;
1557
+ }
1558
+ async function assertInside(h, id, what = "file") {
1559
+ const allowed = chosenFolders(h);
1560
+ if (allowed !== null && !allowed.includes(id)) await getChecked(h, id, "id", what);
1561
+ }
1562
+ async function targetFolder(h, folderId) {
1563
+ if (folderId === void 0) {
1564
+ const allowed = chosenFolders(h);
1565
+ if (allowed !== null) {
1566
+ throw new ToolFailure(`folder_id is required: this connection may only add files to its chosen folders${allowed.length ? ` (${allowed.join(", ")})` : ""}. Nothing was changed.`);
1567
+ }
1568
+ return void 0;
1569
+ }
1570
+ await assertInside(h, folderId, "folder");
1571
+ return [folderId];
1572
+ }
1573
+ async function sourceBytes(h, source) {
1574
+ if (source.url === void 0 === (source.content === void 0)) {
1575
+ throw new ToolFailure("Give url (a public https file) or content (text), one of the two. Nothing was changed.");
1576
+ }
1577
+ if (source.url !== void 0) {
1578
+ const { bytes, contentType } = await h.media(source.url, { what: "file", maxBytes: MAX_UPLOAD_BYTES });
1579
+ return { bytes, served: contentType };
1580
+ }
1581
+ return { bytes: utf8Bytes(source.content), served: null };
1582
+ }
1583
+ function sessionAddress(location) {
1584
+ let url;
1585
+ try {
1586
+ url = location ? new URL(location) : void 0;
1587
+ } catch {
1588
+ }
1589
+ if (!url || url.origin !== DRIVE_ORIGIN || !url.pathname.startsWith("/upload/drive/v3/files")) {
1590
+ throw new ToolFailure("Google Drive started the upload but sent no usable upload address. Nothing was changed.");
1591
+ }
1592
+ return url;
1593
+ }
1594
+ async function sendFile(h, options) {
1595
+ const method = options.fileId ? "PATCH" : "POST";
1596
+ const path = options.fileId ? `/upload/drive/v3/files/${enc(options.fileId)}` : "/upload/drive/v3/files";
1597
+ if (options.bytes.length <= SIMPLE_UPLOAD_MAX) {
1598
+ if (options.metadata) {
1599
+ const { body, contentType } = multipartBody(options.metadata, options.bytes, options.mimeType);
1600
+ return (await drive(h, { method, path, query: { uploadType: "multipart", supportsAllDrives: true, fields: FILE_FIELDS }, body, contentType, write: true })).data;
1601
+ }
1602
+ return (await drive(h, { method, path, query: { uploadType: "media", supportsAllDrives: true, fields: FILE_FIELDS }, body: options.bytes, contentType: options.mimeType, write: true })).data;
1603
+ }
1604
+ const started = await drive(h, {
1605
+ method,
1606
+ path,
1607
+ query: { uploadType: "resumable", supportsAllDrives: true, fields: FILE_FIELDS },
1608
+ json: options.metadata ?? {},
1609
+ headers: { "x-upload-content-type": options.mimeType, "x-upload-content-length": String(options.bytes.length) }
1610
+ });
1611
+ const session = sessionAddress(started.headers.get("location"));
1612
+ const query = Object.fromEntries(session.searchParams);
1613
+ return (await drive(h, {
1614
+ method: "PUT",
1615
+ path: session.pathname,
1616
+ query: { ...query, fields: query["fields"] ?? FILE_FIELDS },
1617
+ body: options.bytes,
1618
+ contentType: options.mimeType,
1619
+ write: true
1620
+ })).data;
1621
+ }
1622
+ async function createMetadata(h, metadata) {
1623
+ return (await drive(h, { method: "POST", path: "/drive/v3/files", query: { supportsAllDrives: true, fields: FILE_FIELDS }, json: metadata, write: true })).data;
1624
+ }
1625
+ async function listPage(h, query, cursor, key, trim, extra) {
1626
+ const state = h.cursor(cursor);
1627
+ const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
1628
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
1629
+ const { data } = await drive(h, { path: "/drive/v3/files", query: { ...query, pageToken, supportsAllDrives: true, includeItemsFromAllDrives: true } });
1630
+ const files = Array.isArray(data?.files) ? data.files : [];
1631
+ return h.page({
1632
+ key,
1633
+ items: files.map(trim).slice(skip),
1634
+ extra: compact({ ...extra, incompleteSearch: data?.incompleteSearch === true ? true : void 0 }),
1635
+ resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index }),
1636
+ ...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0 }) } : {}
1637
+ });
1638
+ }
1639
+ function trimFolder(folder) {
1640
+ const owners = Array.isArray(folder?.owners) ? folder.owners : [];
1641
+ return compact({
1642
+ id: folder?.id,
1643
+ name: folder?.name,
1644
+ type: "folder",
1645
+ owner: owners[0]?.displayName || owners[0]?.emailAddress,
1646
+ modifiedTime: folder?.modifiedTime
1647
+ });
1648
+ }
1649
+ function sharedDriveItem(id, name2) {
1650
+ const shown = typeof name2 === "string" && name2 ? name2 : id;
1651
+ return compact({ id, name: shown, label: `${String(shown)} (shared drive)`, type: "shared_drive" });
1652
+ }
1653
+ async function chosenFolderList(h, allowed, cursor) {
1654
+ const state = h.cursor(cursor);
1655
+ const offset = typeof state?.["c"] === "number" ? state["c"] : 0;
1656
+ const ids = allowed.slice(offset, offset + 25);
1657
+ const items = [];
1658
+ for (const id of ids) {
1659
+ try {
1660
+ const { data } = await drive(h, { path: `/drive/v3/files/${enc(id)}`, query: { fields: "id,name,mimeType,driveId,modifiedTime", supportsAllDrives: true } });
1661
+ if (data?.driveId === id) {
1662
+ const shared = await drive(h, { path: `/drive/v3/drives/${enc(id)}`, query: { fields: "id,name" } }).catch(() => null);
1663
+ items.push(sharedDriveItem(id, shared?.data?.name ?? data?.name));
1664
+ } else {
1665
+ const folder = trimFolder(data);
1666
+ items.push({ ...folder, id, label: folder["name"] ?? id });
1667
+ }
1668
+ } catch (error) {
1669
+ if (!(error instanceof ToolFailure)) throw error;
1670
+ items.push({ id, name: id, label: id, type: "folder", error: truncate(error.message, 300) });
1671
+ }
1672
+ }
1673
+ return h.page({
1674
+ key: "folders",
1675
+ items,
1676
+ extra: { chosen: true },
1677
+ resumeAt: (index) => h.makeCursor({ c: offset + index }),
1678
+ ...offset + ids.length < allowed.length ? { nextPage: h.makeCursor({ c: offset + ids.length }) } : {}
1679
+ });
1680
+ }
1681
+ async function parentNames(h, folders) {
1682
+ const names = /* @__PURE__ */ new Map();
1683
+ for (const folder of folders) if (typeof folder?.id === "string" && typeof folder?.name === "string") names.set(folder.id, folder.name);
1684
+ const driveIds = new Set(folders.map((folder) => folder?.driveId).filter((id) => typeof id === "string"));
1685
+ const missing = [...new Set(folders.map((folder) => Array.isArray(folder?.parents) ? folder.parents[0] : void 0))].filter((id) => typeof id === "string" && !names.has(id)).slice(0, MAX_NAME_LOOKUPS);
1686
+ for (let start = 0; start < missing.length; start += LOOKUP_BATCH) {
1687
+ const batch = missing.slice(start, start + LOOKUP_BATCH);
1688
+ const found = await Promise.all(batch.map(async (id) => {
1689
+ try {
1690
+ const { data } = driveIds.has(id) ? await drive(h, { path: `/drive/v3/drives/${enc(id)}`, query: { fields: "id,name" } }) : await drive(h, { path: `/drive/v3/files/${enc(id)}`, query: { fields: "id,name", supportsAllDrives: true } });
1691
+ return typeof data?.name === "string" && data.name ? data.name : void 0;
1692
+ } catch (error) {
1693
+ if (error instanceof ToolFailure) return void 0;
1694
+ throw error;
1695
+ }
1696
+ }));
1697
+ batch.forEach((id, index) => {
1698
+ const name2 = found[index];
1699
+ if (name2) names.set(id, name2);
1700
+ });
1701
+ }
1702
+ return names;
1703
+ }
1704
+ function reachableFolder(folder, names) {
1705
+ const parentId = Array.isArray(folder?.parents) && typeof folder.parents[0] === "string" ? folder.parents[0] : void 0;
1706
+ const parentName = parentId ? names.get(parentId) : void 0;
1707
+ const name2 = typeof folder?.name === "string" && folder.name ? folder.name : folder?.id;
1708
+ return compact({
1709
+ id: folder?.id,
1710
+ name: name2,
1711
+ label: parentName ? `${name2} (in ${parentName})` : name2,
1712
+ type: "folder",
1713
+ parentId,
1714
+ driveId: folder?.driveId,
1715
+ modifiedTime: folder?.modifiedTime
1716
+ });
1717
+ }
1718
+ async function reachableFolderList(h, cursor) {
1719
+ const state = h.cursor(cursor);
1720
+ const phase = state?.["ph"] === "d" ? "d" : "f";
1721
+ const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
1722
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
1723
+ const items = [];
1724
+ let nextPage;
1725
+ let incompleteSearch;
1726
+ let listDrives = phase === "d";
1727
+ if (phase === "f") {
1728
+ const { data } = await drive(h, {
1729
+ path: "/drive/v3/files",
1730
+ query: {
1731
+ q: `mimeType='${FOLDER_TYPE}' and trashed=false`,
1732
+ corpora: "allDrives",
1733
+ includeItemsFromAllDrives: true,
1734
+ supportsAllDrives: true,
1735
+ orderBy: "name",
1736
+ pageSize: FOLDER_PAGE_SIZE,
1737
+ pageToken,
1738
+ fields: "nextPageToken,incompleteSearch,files(id,name,parents,driveId,modifiedTime)"
1739
+ }
1740
+ });
1741
+ const folders = Array.isArray(data?.files) ? data.files : [];
1742
+ const names = await parentNames(h, folders);
1743
+ for (const folder of folders) items.push(reachableFolder(folder, names));
1744
+ if (data?.incompleteSearch === true) incompleteSearch = true;
1745
+ if (typeof data?.nextPageToken === "string" && data.nextPageToken) nextPage = h.makeCursor({ ph: "f", p: data.nextPageToken, o: 0 });
1746
+ else listDrives = true;
1747
+ }
1748
+ if (listDrives) {
1749
+ const { data } = await drive(h, {
1750
+ path: "/drive/v3/drives",
1751
+ query: { pageSize: 100, pageToken: phase === "d" ? pageToken : void 0, fields: "nextPageToken,drives(id,name)" }
1752
+ });
1753
+ for (const shared of Array.isArray(data?.drives) ? data.drives : []) items.push(sharedDriveItem(shared?.id, shared?.name));
1754
+ if (typeof data?.nextPageToken === "string" && data.nextPageToken) nextPage = h.makeCursor({ ph: "d", p: data.nextPageToken, o: 0 });
1755
+ }
1756
+ return h.page({
1757
+ key: "folders",
1758
+ items: items.slice(skip),
1759
+ extra: compact({ incompleteSearch }),
1760
+ resumeAt: (index) => h.makeCursor({ ph: phase, ...pageToken ? { p: pageToken } : {}, o: skip + index }),
1761
+ ...nextPage ? { nextPage } : {}
1762
+ });
1763
+ }
1764
+ function downloadBlocked(file, role) {
1765
+ const restrictions = file?.downloadRestrictions;
1766
+ const restriction = restrictions?.effectiveDownloadRestrictionWithContext ?? restrictions?.itemDownloadRestriction;
1767
+ if (restriction?.restrictedForWriters === true) return true;
1768
+ if (role === "writer") return false;
1769
+ return restriction?.restrictedForReaders === true || file?.copyRequiresWriterPermission === true;
1770
+ }
1771
+ function scanWarning(file) {
1772
+ const size = Number(file?.size);
1773
+ if (!Number.isFinite(size) || size <= SCAN_LIMIT_BYTES) return void 0;
1774
+ return "Google Drive does not scan files over 100 MB for viruses, so a download of this one by link gets Google's warning page instead of the file: a service that fetches the link gets that page, not the file (a person can still download it from there).";
1775
+ }
1776
+ function downloadLinks(file) {
1777
+ if (typeof file?.webContentLink === "string" && file.webContentLink) return { downloadUrl: file.webContentLink };
1778
+ const links = file?.exportLinks && typeof file.exportLinks === "object" ? file.exportLinks : {};
1779
+ const exportUrls = {};
1780
+ for (const [type, url] of Object.entries(links)) {
1781
+ if (typeof url !== "string") continue;
1782
+ let format = null;
1783
+ try {
1784
+ format = new URL(url).searchParams.get("exportFormat");
1785
+ } catch {
1786
+ }
1787
+ exportUrls[format || type] = url;
1788
+ }
1789
+ return Object.keys(exportUrls).length ? { exportUrls } : {};
1790
+ }
1791
+ var EXPORTS = {
1792
+ [GOOGLE_TYPES.document]: { markdown: "text/markdown", text: "text/plain", html: "text/html" },
1793
+ [GOOGLE_TYPES.spreadsheet]: { csv: "text/csv", tsv: "text/tab-separated-values" },
1794
+ [GOOGLE_TYPES.presentation]: { text: "text/plain" }
1795
+ };
1796
+ var KIND_NAMES = {
1797
+ document: "Google Doc",
1798
+ spreadsheet: "Google Sheet",
1799
+ presentation: "Google Slides file",
1800
+ drawing: "Google Drawing",
1801
+ form: "Google Form",
1802
+ site: "Google Site"
1803
+ };
1804
+ var FILE_EXPORTS = {
1805
+ document: ["pdf", "docx", "txt"],
1806
+ spreadsheet: ["pdf", "xlsx", "csv"],
1807
+ presentation: ["pdf", "pptx", "txt", "png"],
1808
+ drawing: ["pdf", "png"]
1809
+ };
1810
+ var EXPORT_FORMATS = ["pdf", "docx", "xlsx", "pptx", "csv", "txt", "png"];
1811
+ function filesTaken(h) {
1812
+ const limit = h.fileLimit();
1813
+ if (limit === null) {
1814
+ throw new ToolFailure(
1815
+ `This host takes no files, so ${h.tool} cannot hand one back. Open the file with get_file's webViewLink, or hand it to a service that downloads by URL with share_file. Nothing was sent to ${LABEL2}.`
1816
+ );
1817
+ }
1818
+ return limit;
1819
+ }
1820
+ var GOOGLE_APPS_TYPE = "application/vnd.google-apps.";
1821
+ function notStoredFile(mimeType) {
1822
+ const kind = kindOf(mimeType);
1823
+ if (kind === "file") {
1824
+ return typeof mimeType === "string" && mimeType.startsWith(GOOGLE_APPS_TYPE) ? "That is a Google file with no stored file to download, and export_file exports only Google Docs, Sheets, Slides files and Drawings." : void 0;
1825
+ }
1826
+ if (kind === "folder") return "That is a folder: list its files with list_files.";
1827
+ if (kind === "shortcut") return "That is a shortcut: use its target, whose id get_file returns as shortcutTarget.";
1828
+ if (FILE_EXPORTS[kind]) return `That is a ${KIND_NAMES[kind]}, which has no stored file: export it with export_file.`;
1829
+ return `A ${KIND_NAMES[kind] ?? "Google file of this kind"} cannot be downloaded or exported.`;
1830
+ }
1831
+ function assertDownloadable(h, file) {
1832
+ if (file?.capabilities?.canDownload === false) {
1833
+ throw new ToolFailure(`Google Drive does not let ${serviceAccountWords(h)} download this file: downloads are turned off for its role, on the file or in its shared drive.`);
1834
+ }
1835
+ }
1836
+ function exportName(name2, format) {
1837
+ return name2.toLowerCase().endsWith(`.${format}`) ? name2 : `${name2}.${format}`;
1838
+ }
1839
+ var CELL_ROWS = {
1840
+ type: "array",
1841
+ minItems: 1,
1842
+ maxItems: 1e4,
1843
+ items: { type: "array", maxItems: 1e3 },
1844
+ description: 'Rows of cells, e.g. [["2026-05-11", "Jane", 42], ["2026-05-12", "John", 17]]: text, numbers, true/false or null.'
1845
+ };
1846
+ var VALUE_INPUT = {
1847
+ type: "string",
1848
+ enum: ["USER_ENTERED", "RAW"],
1849
+ default: "USER_ENTERED",
1850
+ description: "USER_ENTERED (default) reads values as if typed in (formulas, dates, numbers); RAW stores them as given."
1851
+ };
1852
+ var RANGE = {
1853
+ type: "string",
1854
+ minLength: 1,
1855
+ maxLength: 500,
1856
+ // The range is one path segment: "." or ".." would change the path itself.
1857
+ pattern: "^(?!\\.{1,2}$)",
1858
+ description: "A range in A1 notation, e.g. Sheet1!A1:D50, Sheet1!A:A or Sheet1 (a sheet name with spaces in quotes: 'My sheet'!A1)."
1859
+ };
1860
+ function valuesPath(spreadsheetId, range, suffix = "") {
1861
+ return `/v4/spreadsheets/${enc(spreadsheetId)}/values/${encodeURIComponent(range)}${suffix}`;
1862
+ }
1863
+ function idOfSegment(segment) {
1864
+ const id = segment?.split(":")[0];
1865
+ return id ? id : void 0;
1866
+ }
1867
+ var LOCK_NOTE = "This connection is limited to its chosen folders:";
1868
+ async function assertParents(h, parents, problem) {
1869
+ if (!Array.isArray(parents) || !parents.length || !parents.every((parent) => typeof parent === "string" && parent)) {
1870
+ throw new ToolFailure(`${LOCK_NOTE} ${problem} Nothing was sent.`);
1871
+ }
1872
+ for (const parent of new Set(parents)) await assertInside(h, parent, "folder");
1873
+ }
1874
+ async function driveGuard(request, h) {
1875
+ const refuse = (sentence) => {
1876
+ throw new ToolFailure(`${sentence} Nothing was sent.`);
1877
+ };
1878
+ const { segments } = request;
1879
+ const [first, second, third] = segments;
1880
+ let area;
1881
+ if (request.origin === DRIVE_ORIGIN && first === "drive" && second === "v3") area = "drive";
1882
+ else if (request.origin === DRIVE_ORIGIN && first === "upload" && second === "drive" && third === "v3") area = "upload";
1883
+ else if (request.origin === SHEETS_ORIGIN && first === "v4" && second === "spreadsheets") area = "sheets";
1884
+ else if (request.origin === DOCS_ORIGIN && first === "v1" && second === "documents") area = "docs";
1885
+ else {
1886
+ return refuse("Paths start with /drive/v3/ (or /upload/drive/v3/) on https://www.googleapis.com, /v4/spreadsheets on https://sheets.googleapis.com, or /v1/documents on https://docs.googleapis.com.");
1887
+ }
1888
+ if (area === "upload" && request.method === "GET") refuse("Upload paths take POST, PUT or PATCH.");
1889
+ const allowed = chosenFolders(h);
1890
+ if (allowed === null) return;
1891
+ if (area === "sheets" || area === "docs") {
1892
+ const id = idOfSegment(third);
1893
+ if (!id) return refuse(`${LOCK_NOTE} create spreadsheets and documents with create_spreadsheet and create_document, in a chosen folder.`);
1894
+ await assertInside(h, id);
1895
+ if (area === "sheets" && segments.some((segment) => /:copyto$/i.test(segment))) {
1896
+ const destination = request.json?.["destinationSpreadsheetId"];
1897
+ if (typeof destination !== "string" || !destination) {
1898
+ return refuse(`${LOCK_NOTE} copyTo needs json with destinationSpreadsheetId naming a spreadsheet inside them.`);
1899
+ }
1900
+ if (destination !== id) await assertInside(h, destination, "spreadsheet");
1901
+ }
1902
+ return;
1903
+ }
1904
+ const shift = area === "upload" ? 1 : 0;
1905
+ const collection = segments[2 + shift];
1906
+ const fileId = segments[3 + shift];
1907
+ const action = area === "drive" ? segments[4]?.toLowerCase() : void 0;
1908
+ if (collection === "about" && request.method === "GET") return;
1909
+ if (collection !== "files") return refuse(`${LOCK_NOTE} only files paths (/drive/v3/files/...) and about are reachable.`);
1910
+ if (!fileId) {
1911
+ if (area === "upload") return refuse(`${LOCK_NOTE} upload new files with upload_file.`);
1912
+ if (request.method === "GET") {
1913
+ const folder = oneFolderQuery(request.query["q"]);
1914
+ if (!folder) {
1915
+ return refuse(`${LOCK_NOTE} list files with list_files, or with a q naming one chosen folder and nothing else but trashed and mimeType terms, such as "'FOLDER_ID' in parents and trashed=false".`);
1916
+ }
1917
+ await assertInside(h, folder, "folder");
1918
+ return;
1919
+ }
1920
+ if (request.method === "POST") return assertParents(h, request.json?.["parents"], "a new file needs json with parents naming a chosen folder.");
1921
+ return refuse(`${LOCK_NOTE} only file listings and new files go to /drive/v3/files itself.`);
1922
+ }
1923
+ if (fileId === "generateIds" && request.method === "GET") return;
1924
+ if (fileId === "trash") return refuse(`${LOCK_NOTE} emptying the trash is not available.`);
1925
+ await assertInside(h, fileId);
1926
+ const checked = /* @__PURE__ */ new Set();
1927
+ if (action === "copy") {
1928
+ await assertParents(h, request.json?.["parents"], "a copy needs json with parents naming a chosen folder.");
1929
+ for (const parent of request.json?.["parents"]) checked.add(parent);
1930
+ }
1931
+ const moved = [...(request.query["addParents"] ?? []).flatMap((value) => value.split(",")), ...Array.isArray(request.json?.["parents"]) ? request.json["parents"] : []];
1932
+ for (const parent of moved) {
1933
+ if (typeof parent !== "string" || !parent.trim()) refuse(`${LOCK_NOTE} parents must be folder ids.`);
1934
+ const id = parent.trim();
1935
+ if (checked.has(id)) continue;
1936
+ checked.add(id);
1937
+ await assertInside(h, id, "folder");
1938
+ }
1939
+ }
1940
+ var connector = defineConnector({
1941
+ vendor: "google-drive",
1942
+ label: LABEL2,
1943
+ origins: [DRIVE_ORIGIN, SHEETS_ORIGIN, DOCS_ORIGIN, TOKEN_ORIGIN],
1944
+ credentials: [KEY_CREDENTIAL],
1945
+ credentialLabels: { serviceaccountjson: "Google Drive service account key" },
1946
+ accountPickers: [
1947
+ {
1948
+ key: PICKER,
1949
+ label: "Google Drive folders",
1950
+ description: "The folders the agent may read and write, with their subfolders. Share each one with the service account first.",
1951
+ multiple: true,
1952
+ tool: "list_folders",
1953
+ idField: "id",
1954
+ nameField: "label",
1955
+ legacyField: "folders"
1956
+ }
1957
+ ],
1958
+ tools: [
1959
+ {
1960
+ name: "list_folders",
1961
+ kind: "read",
1962
+ title: "List Google Drive folders",
1963
+ description: "Lists folders: without parent_id, the folders chosen for this connection, or, with no choice made, every folder the service account can reach (folders shared with it, their subfolders and the folders of its shared drives, each labeled with its parent folder's name), then the shared drives it is a member of; with parent_id, the subfolders of that folder. Each has its id and name. Pass nextCursor back as cursor for more.",
1964
+ inputSchema: {
1965
+ type: "object",
1966
+ properties: {
1967
+ parent_id: { ...ID, description: "List the subfolders of this folder." },
1968
+ cursor: { type: "string", description: "nextCursor from the previous result." }
1969
+ },
1970
+ additionalProperties: false
1971
+ },
1972
+ async run(args, h) {
1973
+ if (args.parent_id !== void 0) {
1974
+ await assertInside(h, args.parent_id, "folder");
1975
+ return listPage(h, {
1976
+ q: `mimeType='${FOLDER_TYPE}' and trashed=false and ${queryLiteral(args.parent_id)} in parents`,
1977
+ fields: "nextPageToken,files(id,name,modifiedTime,owners(displayName,emailAddress))",
1978
+ pageSize: 100,
1979
+ orderBy: "name"
1980
+ }, args.cursor, "folders", trimFolder, { parentId: args.parent_id });
1981
+ }
1982
+ const allowed = chosenFolders(h);
1983
+ return allowed === null ? reachableFolderList(h, args.cursor) : chosenFolderList(h, allowed, args.cursor);
1984
+ }
1985
+ },
1986
+ {
1987
+ name: "list_files",
1988
+ kind: "read",
1989
+ title: "List Google Drive files",
1990
+ description: "Lists the files in a folder (or, without folder_id, in the chosen folders, or everything the service account can see), newest change first (full-text matches by relevance): id, name, kind (folder, document, spreadsheet, presentation or file), type, size, times and link. Filter by name, text, type, change time, or whether anyone with the link can open them. Subfolders are listed too; list one with its id for its files. Pass nextCursor back as cursor for more.",
1991
+ inputSchema: {
1992
+ type: "object",
1993
+ properties: {
1994
+ folder_id: { ...ID, description: "The folder to list." },
1995
+ name_contains: { type: "string", maxLength: 200, description: "Only names containing this text." },
1996
+ full_text: { type: "string", maxLength: 200, description: "Only files whose name or content contains this text; they come back by relevance." },
1997
+ mime_type: { type: "string", maxLength: 200, pattern: "^[A-Za-z0-9.+-]+/([A-Za-z0-9.+-]+|\\*)$", description: "Only this type, e.g. image/png, or a family such as image/* or video/*." },
1998
+ modified_after: { type: "string", maxLength: 40, description: "Only files changed after this time (RFC 3339), e.g. 2026-05-01T00:00:00Z." },
1999
+ shared_with_anyone: {
2000
+ type: "boolean",
2001
+ description: "true: only files anyone with the link can open (shared with anyone, as share_file does for a service), to find links still open and remove them with unshare_file; false: only files that are not."
2002
+ },
2003
+ include_folders: { type: "boolean", default: true, description: "List subfolders too (default true)." },
2004
+ order_by: {
2005
+ type: "string",
2006
+ enum: ["modifiedTime desc", "createdTime desc", "name", "folder,name"],
2007
+ description: "Order (default newest change first). Not with full_text or a fullText query: Google Drive sorts those by relevance."
2008
+ },
2009
+ query: { type: "string", maxLength: 1e3, description: 'A raw Drive search query, e.g. "starred = true"; not available while the connection is limited to chosen folders.' },
2010
+ page_size: { type: "integer", minimum: 1, maximum: 1e3, default: 100, description: "Files per page, 1 to 1000 (default 100)." },
2011
+ cursor: { type: "string", description: "nextCursor from the previous result." }
2012
+ },
2013
+ additionalProperties: false
2014
+ },
2015
+ async run(args, h) {
2016
+ const fullText = Boolean(args.full_text) || args.query !== void 0 && /\bfullText\s+contains\b/i.test(args.query);
2017
+ if (fullText && args.order_by !== void 0) {
2018
+ throw new ToolFailure("order_by does not go with full_text or a fullText query: Google Drive returns full-text matches by relevance. Leave order_by out.");
2019
+ }
2020
+ const allowed = chosenFolders(h);
2021
+ const clauses = ["trashed=false"];
2022
+ if (args.folder_id !== void 0) {
2023
+ await assertInside(h, args.folder_id, "folder");
2024
+ clauses.push(`${queryLiteral(args.folder_id)} in parents`);
2025
+ } else if (allowed !== null) {
2026
+ if (!allowed.length) throw new ToolFailure(`No folder is chosen for this ${LABEL2} connection yet, so it can list no file.`);
2027
+ clauses.push(`(${allowed.map((id) => `${queryLiteral(id)} in parents`).join(" or ")})`);
2028
+ }
2029
+ if (args.name_contains) clauses.push(`name contains ${queryLiteral(args.name_contains)}`);
2030
+ if (args.full_text) clauses.push(`fullText contains ${queryLiteral(args.full_text)}`);
2031
+ if (args.mime_type) {
2032
+ clauses.push(args.mime_type.endsWith("/*") ? `mimeType contains ${queryLiteral(args.mime_type.slice(0, -1))}` : `mimeType = ${queryLiteral(args.mime_type)}`);
2033
+ }
2034
+ if (!args.include_folders) clauses.push(`mimeType != '${FOLDER_TYPE}'`);
2035
+ if (args.shared_with_anyone === true) clauses.push(`(visibility = 'anyoneWithLink' or visibility = 'anyoneCanFind')`);
2036
+ if (args.shared_with_anyone === false) clauses.push(`visibility != 'anyoneWithLink' and visibility != 'anyoneCanFind'`);
2037
+ if (args.modified_after !== void 0) {
2038
+ const time = Date.parse(args.modified_after);
2039
+ if (!Number.isFinite(time)) throw new ToolFailure("modified_after is not a time such as 2026-05-01T00:00:00Z.");
2040
+ clauses.push(`modifiedTime > '${new Date(time).toISOString()}'`);
2041
+ }
2042
+ if (args.query !== void 0) {
2043
+ if (allowed !== null) throw new ToolFailure("query is not available while this connection is limited to its chosen folders: use the other filters.");
2044
+ clauses.push(`(${args.query})`);
2045
+ }
2046
+ return listPage(h, {
2047
+ q: clauses.join(" and "),
2048
+ fields: LIST_FIELDS,
2049
+ pageSize: args.page_size,
2050
+ orderBy: fullText ? void 0 : args.order_by ?? "modifiedTime desc"
2051
+ }, args.cursor, "files", trimFile, compact({ folderId: args.folder_id }));
2052
+ }
2053
+ },
2054
+ {
2055
+ name: "get_file",
2056
+ kind: "read",
2057
+ title: "Get a Google Drive file",
2058
+ description: "Returns a file's details: name, kind, type, size, folder, owner, times, description, links (webViewLink to open it; webContentLink to download it once it is shared publicly), the formats a Google Doc, Sheet or Slides file exports to, and who it is shared with.",
2059
+ inputSchema: { type: "object", properties: { file_id: ID }, required: ["file_id"], additionalProperties: false },
2060
+ async run(args, h) {
2061
+ const data = await getChecked(h, args.file_id, [
2062
+ "id,name,mimeType,size,parents,driveId,description,starred,trashed,createdTime,modifiedTime,webViewLink,webContentLink,md5Checksum",
2063
+ "owners(displayName,emailAddress),lastModifyingUser(displayName,emailAddress),shortcutDetails(targetId,targetMimeType),exportLinks",
2064
+ "permissions(id,type,role,emailAddress,domain),capabilities(canEdit,canShare)"
2065
+ ].join(","));
2066
+ const permissions = Array.isArray(data?.permissions) ? data.permissions : [];
2067
+ return compact({
2068
+ ...trimFile(data),
2069
+ md5Checksum: data?.md5Checksum,
2070
+ exportFormats: data?.exportLinks && typeof data.exportLinks === "object" ? Object.keys(data.exportLinks) : void 0,
2071
+ sharedWith: permissions.length ? permissions.slice(0, 30).map((permission) => compact({ id: permission?.id, type: permission?.type, role: permission?.role, email: permission?.emailAddress, domain: permission?.domain })) : void 0,
2072
+ canEdit: data?.capabilities?.canEdit,
2073
+ canShare: data?.capabilities?.canShare
2074
+ });
2075
+ }
2076
+ },
2077
+ {
2078
+ name: "read_file",
2079
+ kind: "read",
2080
+ title: "Read a Google Drive file as text",
2081
+ description: "Returns the text of a file, in pages of about 25 KB: a Google Doc as Markdown (or plain text or HTML), a Google Sheet's first sheet as CSV (read_sheet reads any sheet and range), a Slides file as plain text, and text files (TXT, CSV, JSON, HTML, XML and similar) as they are, up to 4 MB. A binary file (an image, a video, a PDF) is not read: its details and links come back instead, and download_file hands the file itself to the host (export_file a PDF, Word, Excel or PowerPoint copy of a Google file). To hand a file to a service that downloads by URL, use share_file (type anyone), then unshare_file in the same run. Pass nextCursor back as cursor for the next page.",
2082
+ inputSchema: {
2083
+ type: "object",
2084
+ properties: {
2085
+ file_id: ID,
2086
+ format: { type: "string", enum: ["markdown", "text", "html", "csv", "tsv"], description: "For a Google Doc: markdown (default), text or html. For a Google Sheet: csv (default) or tsv." },
2087
+ cursor: { type: "string", description: "nextCursor from the previous result." }
2088
+ },
2089
+ required: ["file_id"],
2090
+ additionalProperties: false
2091
+ },
2092
+ async run(args, h) {
2093
+ const state = h.cursor(args.cursor);
2094
+ const offset = typeof state?.["o"] === "number" ? state["o"] : 0;
2095
+ const file = await getChecked(h, args.file_id, "id,name,mimeType,size,webViewLink,webContentLink");
2096
+ const mimeType = typeof file?.mimeType === "string" ? file.mimeType : "application/octet-stream";
2097
+ const kind = kindOf(mimeType);
2098
+ let request;
2099
+ let format;
2100
+ const exports2 = EXPORTS[mimeType];
2101
+ if (exports2) {
2102
+ const name2 = args.format ?? Object.keys(exports2)[0];
2103
+ format = exports2[name2];
2104
+ if (!format) throw new ToolFailure(`A ${kind} reads as ${Object.keys(exports2).join(" or ")}, not ${name2}.`);
2105
+ request = { path: `/drive/v3/files/${enc(args.file_id)}/export`, query: { mimeType: format }, maxBytes: MAX_TEXT_BYTES };
2106
+ } else if (kind !== "file") {
2107
+ throw new ToolFailure(
2108
+ kind === "folder" ? "That is a folder: list its files with list_files." : kind === "shortcut" ? "That is a shortcut: read its target, whose id get_file returns as shortcutTarget." : `A Google ${kind} file has no text to read.`
2109
+ );
2110
+ } else if (isTextType(mimeType)) {
2111
+ if (Number(file?.size) > MAX_TEXT_BYTES) throw new ToolFailure(`The file has ${Number(file.size)} bytes; read_file reads text files up to ${MAX_TEXT_BYTES} bytes.`);
2112
+ request = { path: `/drive/v3/files/${enc(args.file_id)}`, query: { alt: "media", supportsAllDrives: true }, maxBytes: MAX_TEXT_BYTES, headers: { accept: "*/*" } };
2113
+ } else {
2114
+ return compact({
2115
+ ...trimFile(file),
2116
+ binary: true,
2117
+ note: "This is a binary file, which read_file does not read: download_file hands it to the host as a file, where the host takes files. Open it with webViewLink. For a service that downloads files by URL, share_file with type anyone and role reader returns its downloadUrl; in the same run, once the service has the file (or has failed), unshare_file with permission_id anyoneWithLink takes the link back.",
2118
+ warning: scanWarning(file)
2119
+ });
2120
+ }
2121
+ const { data } = await drive(h, request);
2122
+ const text = typeof data === "string" ? data : data === null || data === void 0 ? "" : JSON.stringify(data, null, 2);
2123
+ if (offset > text.length) throw new ToolFailure("The cursor points past the end of the file: the file changed. Start again without cursor.");
2124
+ const page = textPage(text, offset);
2125
+ return compact({
2126
+ id: file?.id,
2127
+ name: file?.name,
2128
+ mimeType,
2129
+ format,
2130
+ characters: text.length,
2131
+ offset: offset || void 0,
2132
+ text: page.piece,
2133
+ nextCursor: page.next !== void 0 ? h.makeCursor({ o: page.next }) : void 0
2134
+ });
2135
+ }
2136
+ },
2137
+ {
2138
+ name: "download_file",
2139
+ kind: "read",
2140
+ title: "Download a Google Drive file",
2141
+ description: "Hands a stored file (an image, a video, a PDF, an Office file or any other upload) to the host as a file, with its details, for the host to save or pass on. Its size is checked against the most the host takes before anything is downloaded. A Google Doc, Sheet, Slides file or Drawing has no stored file: export_file makes a PDF or Office copy of it. A host that takes no files gets a refusal; share_file (type anyone) then hands the file to a service that downloads by URL.",
2142
+ inputSchema: { type: "object", properties: { file_id: ID }, required: ["file_id"], additionalProperties: false },
2143
+ async run(args, h) {
2144
+ const limit = filesTaken(h);
2145
+ const file = await getChecked(h, args.file_id, "id,name,mimeType,size,md5Checksum,modifiedTime,webViewLink,capabilities(canDownload)");
2146
+ const problem = notStoredFile(file?.mimeType);
2147
+ if (problem) throw new ToolFailure(problem);
2148
+ assertDownloadable(h, file);
2149
+ const size = Number(file?.size);
2150
+ if (Number.isFinite(size) && size > limit) {
2151
+ throw new ToolFailure(
2152
+ `The file has ${formatNumber(size)} bytes, more than the ${formatNumber(limit)} bytes this host takes, so it was not downloaded. share_file (type anyone) hands it to a service that downloads by URL instead.`
2153
+ );
2154
+ }
2155
+ const { data } = await drive(h, {
2156
+ path: `/drive/v3/files/${enc(args.file_id)}`,
2157
+ query: { alt: "media", supportsAllDrives: true },
2158
+ headers: { accept: "*/*" },
2159
+ binary: true,
2160
+ maxBytes: limit
2161
+ });
2162
+ const name2 = typeof file?.name === "string" && file.name ? file.name : args.file_id;
2163
+ const mimeType = typeof file?.mimeType === "string" ? file.mimeType : "application/octet-stream";
2164
+ return compact({ ...trimFile(file), md5Checksum: file?.md5Checksum, file: h.file({ name: name2, mimeType, bytes: data }) });
2165
+ }
2166
+ },
2167
+ {
2168
+ name: "export_file",
2169
+ kind: "read",
2170
+ title: "Export a Google Doc, Sheet, Slides file or Drawing",
2171
+ description: "Exports a Google Doc, Sheet, Slides file or Drawing and hands the copy to the host as a file: a Doc as pdf, docx or txt; a Sheet as pdf, xlsx or csv (csv holds its first sheet only); a Slides file as pdf, pptx, txt or png (png shows its first slide only); a Drawing as pdf or png. Google Drive exports up to 10 MB. A host that takes no files gets a refusal; read_file reads the text of a Doc, Sheet or Slides file instead.",
2172
+ inputSchema: {
2173
+ type: "object",
2174
+ properties: {
2175
+ file_id: ID,
2176
+ format: {
2177
+ type: "string",
2178
+ enum: EXPORT_FORMATS,
2179
+ default: "pdf",
2180
+ description: "pdf (default, every kind), docx (Doc), xlsx (Sheet), pptx (Slides), csv (Sheet, its first sheet), txt (Doc or Slides) or png (Slides, its first slide; Drawing)."
2181
+ }
2182
+ },
2183
+ required: ["file_id"],
2184
+ additionalProperties: false
2185
+ },
2186
+ async run(args, h) {
2187
+ const limit = filesTaken(h);
2188
+ const file = await getChecked(h, args.file_id, "id,name,mimeType,modifiedTime,webViewLink,capabilities(canDownload)");
2189
+ const kind = kindOf(file?.mimeType);
2190
+ const formats = FILE_EXPORTS[kind];
2191
+ if (!formats) {
2192
+ throw new ToolFailure(notStoredFile(file?.mimeType) ?? "That is a stored file, not a Google Doc, Sheet, Slides file or Drawing: download it with download_file.");
2193
+ }
2194
+ if (!formats.includes(args.format)) throw new ToolFailure(`A ${KIND_NAMES[kind]} exports as ${orList(formats)}, not ${args.format}.`);
2195
+ assertDownloadable(h, file);
2196
+ const mimeType = typeByName(`export.${args.format}`) ?? "application/octet-stream";
2197
+ const { data } = await drive(h, {
2198
+ path: `/drive/v3/files/${enc(args.file_id)}/export`,
2199
+ query: { mimeType },
2200
+ headers: { accept: "*/*" },
2201
+ binary: true,
2202
+ maxBytes: limit
2203
+ });
2204
+ const note = kind === "spreadsheet" && args.format === "csv" ? "csv holds the first sheet only; read_sheet reads any sheet." : kind === "presentation" && args.format === "png" ? "png shows the first slide only." : void 0;
2205
+ const name2 = exportName(typeof file?.name === "string" && file.name ? file.name : args.file_id, args.format);
2206
+ return compact({ ...trimFile(file), format: args.format, note, file: h.file({ name: name2, mimeType, bytes: data }) });
2207
+ }
2208
+ },
2209
+ {
2210
+ name: "upload_file",
2211
+ kind: "create",
2212
+ check: "list_files",
2213
+ title: "Upload a file to Google Drive",
2214
+ description: "Uploads a file into a folder: from a public https URL (images, videos, PDFs and any other file, up to 50 MB) or from text given here (CSV, Markdown, JSON, HTML or plain text). A connector reads no local files: a file on a computer or in a workspace must first be reachable at a public https URL. The type comes from the file itself unless mime_type says otherwise; convert_to turns it into a Google Doc, Sheet or Slides file. Returns the new file with its id and link. A service account owns no storage of its own: upload into a shared drive, or Google may answer storageQuotaExceeded.",
2215
+ inputSchema: {
2216
+ type: "object",
2217
+ properties: {
2218
+ name: { type: "string", minLength: 1, maxLength: 500, description: "The file name, e.g. banner-1080x1080.jpg." },
2219
+ folder_id: { ...ID, description: "The folder to put it in (required when the connection is limited to chosen folders)." },
2220
+ url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "A public https URL of the file." },
2221
+ content: { type: "string", maxLength: 1e6, description: "The file's text, instead of url." },
2222
+ mime_type: { type: "string", maxLength: 200, pattern: "^[A-Za-z0-9.+-]+/[A-Za-z0-9.+-]+$", description: "The file type, e.g. text/csv. Default: from the file." },
2223
+ description: { type: "string", maxLength: 2e3, description: "A description shown in Drive." },
2224
+ convert_to: { type: "string", enum: ["document", "spreadsheet", "presentation"], description: "Convert into a Google Doc (from text, Markdown, HTML or a .docx file), Sheet (from CSV or a .xlsx file) or Slides file (from a .pptx file)." }
2225
+ },
2226
+ required: ["name"],
2227
+ additionalProperties: false
2228
+ },
2229
+ async run(args, h) {
2230
+ const parents = await targetFolder(h, args.folder_id);
2231
+ const { bytes, served } = await sourceBytes(h, args);
2232
+ const mimeType = args.content !== void 0 && !args.mime_type ? typeByName(args.name) ?? "text/plain" : uploadType(bytes, args.name, args.mime_type, served);
2233
+ const metadata = compact({ name: args.name, parents, description: args.description, mimeType: args.convert_to ? GOOGLE_TYPES[args.convert_to] : void 0 });
2234
+ return trimFile(await sendFile(h, { metadata, bytes, mimeType }));
2235
+ }
2236
+ },
2237
+ {
2238
+ name: "create_document",
2239
+ kind: "create",
2240
+ check: "list_files",
2241
+ title: "Create a Google Doc",
2242
+ description: "Creates a Google Doc in a folder, empty or with text: Markdown (default; headings, lists, links and tables become formatting), plain text or HTML. Returns its id and link. add_document_text adds more text later.",
2243
+ inputSchema: {
2244
+ type: "object",
2245
+ properties: {
2246
+ name: { type: "string", minLength: 1, maxLength: 500, description: "The document title." },
2247
+ folder_id: { ...ID, description: "The folder to put it in (required when the connection is limited to chosen folders)." },
2248
+ text: { type: "string", maxLength: 1e6, description: "The document's content." },
2249
+ format: { type: "string", enum: ["markdown", "text", "html"], default: "markdown", description: "How text is written: markdown (default), text or html." }
2250
+ },
2251
+ required: ["name"],
2252
+ additionalProperties: false
2253
+ },
2254
+ async run(args, h) {
2255
+ const parents = await targetFolder(h, args.folder_id);
2256
+ const metadata = compact({ name: args.name, parents, mimeType: GOOGLE_TYPES.document });
2257
+ if (args.text === void 0 || args.text === "") return trimFile(await createMetadata(h, metadata));
2258
+ const mimeType = { markdown: "text/markdown", text: "text/plain", html: "text/html" }[args.format];
2259
+ return trimFile(await sendFile(h, { metadata, bytes: utf8Bytes(args.text), mimeType }));
2260
+ }
2261
+ },
2262
+ {
2263
+ name: "create_spreadsheet",
2264
+ kind: "create",
2265
+ check: "list_files",
2266
+ title: "Create a Google Sheet",
2267
+ description: "Creates a Google Sheet in a folder, empty or filled with rows (or CSV text). Returns its id and link, for read_sheet, append_rows and update_range.",
2268
+ inputSchema: {
2269
+ type: "object",
2270
+ properties: {
2271
+ name: { type: "string", minLength: 1, maxLength: 500, description: "The spreadsheet title." },
2272
+ folder_id: { ...ID, description: "The folder to put it in (required when the connection is limited to chosen folders)." },
2273
+ rows: CELL_ROWS,
2274
+ csv: { type: "string", maxLength: 1e6, description: "CSV text, instead of rows." }
2275
+ },
2276
+ required: ["name"],
2277
+ additionalProperties: false
2278
+ },
2279
+ async run(args, h) {
2280
+ if (args.rows !== void 0 && args.csv !== void 0) throw new ToolFailure("Give rows or csv, not both. Nothing was changed.");
2281
+ const rows = args.rows !== void 0 ? checkRows(args.rows, "rows") : void 0;
2282
+ const parents = await targetFolder(h, args.folder_id);
2283
+ const metadata = compact({ name: args.name, parents, mimeType: GOOGLE_TYPES.spreadsheet });
2284
+ const csv = rows ? toCsv(rows) : args.csv;
2285
+ if (csv === void 0 || csv === "") return trimFile(await createMetadata(h, metadata));
2286
+ return trimFile(await sendFile(h, { metadata, bytes: utf8Bytes(csv), mimeType: "text/csv" }));
2287
+ }
2288
+ },
2289
+ {
2290
+ name: "update_file",
2291
+ kind: "update",
2292
+ check: "get_file",
2293
+ title: "Rename, move or trash a Google Drive file",
2294
+ description: "Changes a file's name, description or star, moves it to another folder, or moves it to the trash (trashed true) and back (trashed false). Only the fields given change.",
2295
+ inputSchema: {
2296
+ type: "object",
2297
+ properties: {
2298
+ file_id: ID,
2299
+ name: { type: "string", minLength: 1, maxLength: 500, description: "The new name." },
2300
+ description: { type: "string", maxLength: 2e3, description: "The new description." },
2301
+ starred: { type: "boolean", description: "Star or unstar it." },
2302
+ trashed: { type: "boolean", description: "true moves it to the trash; false restores it." },
2303
+ move_to_folder_id: { ...ID, description: "The folder to move it into (it leaves its current folder)." }
2304
+ },
2305
+ required: ["file_id"],
2306
+ additionalProperties: false
2307
+ },
2308
+ async run(args, h) {
2309
+ const body = compact({ name: args.name, description: args.description, starred: args.starred, trashed: args.trashed });
2310
+ if (!Object.keys(body).length && args.move_to_folder_id === void 0) throw new ToolFailure("Give at least one change. Nothing was changed.");
2311
+ let addParents;
2312
+ let removeParents;
2313
+ if (args.move_to_folder_id !== void 0 || chosenFolders(h) !== null) {
2314
+ const file = await getChecked(h, args.file_id, "id,parents");
2315
+ if (args.move_to_folder_id !== void 0) {
2316
+ await assertInside(h, args.move_to_folder_id, "folder");
2317
+ const current = Array.isArray(file?.parents) ? file.parents.filter((parent) => typeof parent === "string") : [];
2318
+ addParents = current.includes(args.move_to_folder_id) ? void 0 : args.move_to_folder_id;
2319
+ removeParents = current.filter((parent) => parent !== args.move_to_folder_id).join(",") || void 0;
2320
+ }
2321
+ }
2322
+ const { data } = await drive(h, {
2323
+ method: "PATCH",
2324
+ path: `/drive/v3/files/${enc(args.file_id)}`,
2325
+ query: { supportsAllDrives: true, fields: FILE_FIELDS, addParents, removeParents },
2326
+ json: body,
2327
+ write: true
2328
+ });
2329
+ return trimFile(data);
2330
+ }
2331
+ },
2332
+ {
2333
+ name: "replace_file_content",
2334
+ kind: "update",
2335
+ check: "get_file",
2336
+ title: "Replace a Google Drive file's content",
2337
+ description: "Replaces the content of an existing file and keeps its id, name and links: from a public https URL (up to 50 MB) or from text given here. New text, Markdown or HTML replaces a Google Doc's content, and CSV a Google Sheet's.",
2338
+ inputSchema: {
2339
+ type: "object",
2340
+ properties: {
2341
+ file_id: ID,
2342
+ url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "A public https URL of the new content." },
2343
+ content: { type: "string", maxLength: 1e6, description: "The new content as text, instead of url." },
2344
+ mime_type: { type: "string", maxLength: 200, pattern: "^[A-Za-z0-9.+-]+/[A-Za-z0-9.+-]+$", description: "The new content's type. Default: from the content, else the file's type." }
2345
+ },
2346
+ required: ["file_id"],
2347
+ additionalProperties: false
2348
+ },
2349
+ async run(args, h) {
2350
+ const file = await getChecked(h, args.file_id, "id,name,mimeType");
2351
+ const current = typeof file?.mimeType === "string" ? file.mimeType : "";
2352
+ if (current === FOLDER_TYPE) throw new ToolFailure("That is a folder, which has no content to replace. Nothing was changed.");
2353
+ const { bytes, served } = await sourceBytes(h, args);
2354
+ const ownType = current.startsWith("application/vnd.google-apps.") ? void 0 : current;
2355
+ const name2 = typeof file?.name === "string" ? file.name : "";
2356
+ const mimeType = args.mime_type ?? (args.content !== void 0 ? current === GOOGLE_TYPES.spreadsheet ? "text/csv" : ownType ?? typeByName(name2) ?? "text/plain" : uploadType(bytes, name2, void 0, served ?? ownType));
2357
+ return trimFile(await sendFile(h, { fileId: args.file_id, bytes, mimeType }));
2358
+ }
2359
+ },
2360
+ {
2361
+ name: "share_file",
2362
+ kind: "create",
2363
+ check: "get_file",
2364
+ title: "Share a Google Drive file",
2365
+ description: "Gives a person, a group, a whole domain or anyone with the link access to a file or folder, as reader, commenter or writer (Editor; Content manager in a shared drive). Files the service account creates belong to it: share them with the people who need to edit them. type anyone with role reader is how a file reaches a service that downloads by URL: the result then has downloadUrl (the file itself) or, for a Google Doc, Sheet or Slides file, exportUrls by format (pdf, docx, xlsx, pptx and more), and a warning when a service cannot fetch it (downloads off for viewers; over 100 MB, Google answers with a virus-scan page). Anyone with the link can open the file until unshare_file removes permission anyoneWithLink: do that in the same run, once the service has the file. A sharing setting of the organization or the shared drive can forbid links for anyone; the error then says so.",
2366
+ inputSchema: {
2367
+ type: "object",
2368
+ properties: {
2369
+ file_id: ID,
2370
+ role: { type: "string", enum: ["reader", "commenter", "writer"], description: "reader, commenter or writer." },
2371
+ type: { type: "string", enum: ["user", "group", "domain", "anyone"], description: "user or group (with email), domain (with domain), or anyone with the link." },
2372
+ email: { type: "string", pattern: "^[^\\s@]+@[^\\s@]+$", maxLength: 320, description: "The person's or group's email, for type user or group." },
2373
+ domain: { type: "string", pattern: "^[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$", maxLength: 253, description: "The domain, for type domain, e.g. example.com." },
2374
+ notify: { type: "boolean", description: "For user and group: send Google's notification email (default true)." },
2375
+ message: { type: "string", maxLength: 2e3, description: "A note for the notification email." }
2376
+ },
2377
+ required: ["file_id", "role", "type"],
2378
+ additionalProperties: false
2379
+ },
2380
+ async run(args, h) {
2381
+ const person2 = args.type === "user" || args.type === "group";
2382
+ if (person2 && !args.email) throw new ToolFailure(`email is required for type ${args.type}. Nothing was changed.`);
2383
+ if (args.type === "domain" && !args.domain) throw new ToolFailure("domain is required for type domain. Nothing was changed.");
2384
+ if (!person2 && (args.email || args.notify !== void 0 || args.message)) throw new ToolFailure("email, notify and message go with type user or group only. Nothing was changed.");
2385
+ const file = await getChecked(h, args.file_id, [
2386
+ "id,name,mimeType,size,webViewLink,webContentLink,exportLinks",
2387
+ "copyRequiresWriterPermission,downloadRestrictions,capabilities(canShare)"
2388
+ ].join(","));
2389
+ if (file?.capabilities?.canShare === false) {
2390
+ throw new ToolFailure(
2391
+ `Google Drive does not let ${serviceAccountWords(h)} change who can open this ${kindOf(file?.mimeType) === "folder" ? "folder" : "file"}: ${SHARING_RIGHTS}, unless a sharing setting of the organization or of the shared drive stops it anyway. Nothing was changed.`
2392
+ );
2393
+ }
2394
+ const details = trimFile(file);
2395
+ const about = { fileId: args.file_id, name: details["name"], mimeType: details["mimeType"], size: details["size"] };
2396
+ let data;
2397
+ try {
2398
+ ({ data } = await drive(h, {
2399
+ method: "POST",
2400
+ path: `/drive/v3/files/${enc(args.file_id)}/permissions`,
2401
+ query: {
2402
+ supportsAllDrives: true,
2403
+ fields: "id,type,role,emailAddress,domain",
2404
+ sendNotificationEmail: person2 ? args.notify : void 0,
2405
+ emailMessage: args.message
2406
+ },
2407
+ json: compact({ role: args.role, type: args.type, emailAddress: args.email, domain: args.domain }),
2408
+ write: true
2409
+ }, args.type));
2410
+ } catch (error) {
2411
+ if (!(error instanceof ToolFailure) || error.details.status !== 400) throw error;
2412
+ if (EMAIL_NOT_SENT.test(error.message)) {
2413
+ return compact({
2414
+ ...about,
2415
+ type: args.type,
2416
+ role: args.role,
2417
+ email: args.email,
2418
+ webViewLink: file?.webViewLink,
2419
+ warning: "Google Drive made the sharing but could not send its notification email: check the address. get_file lists the sharing with its permission id."
2420
+ });
2421
+ }
2422
+ if (person2 && args.notify !== false && !USER_MESSAGE.test(error.message)) {
2423
+ throw new OutcomeUnknown(
2424
+ "Google Drive answered HTTP 400 without a cause, as it does both when a sharing setting forbids the sharing and when it made the sharing but could not send the notification email, so it is not known whether the sharing was made."
2425
+ );
2426
+ }
2427
+ throw error;
2428
+ }
2429
+ const anyone = args.type === "anyone";
2430
+ let links = {};
2431
+ let warning;
2432
+ if (anyone && downloadBlocked(file, args.role)) {
2433
+ warning = `Downloads are turned off for ${args.role === "writer" ? "editors" : "viewers"} of this file (on the file, or in its shared drive), so the link opens it in Google Drive but gives no file to download: a service cannot fetch it.`;
2434
+ } else if (anyone) {
2435
+ links = downloadLinks(file);
2436
+ if (links["downloadUrl"]) warning = scanWarning(file);
2437
+ }
2438
+ return compact({
2439
+ ...about,
2440
+ permissionId: data?.id,
2441
+ type: data?.type,
2442
+ role: data?.role,
2443
+ email: data?.emailAddress,
2444
+ domain: data?.domain,
2445
+ webViewLink: file?.webViewLink,
2446
+ ...links,
2447
+ warning,
2448
+ note: anyone ? `Anyone with the link can open the file until unshare_file removes permission ${String(data?.id ?? "anyoneWithLink")}: do that in the same run, once the service has the file.` : void 0
2449
+ });
2450
+ }
2451
+ },
2452
+ {
2453
+ name: "unshare_file",
2454
+ kind: "delete",
2455
+ check: "get_file",
2456
+ title: "Remove a sharing from a Google Drive file",
2457
+ description: "Removes one sharing from a file or folder by its permission id: the permissionId share_file returned, or an id from get_file's sharedWith. anyoneWithLink takes back a link shared with anyone: call it in the same run, once the service that needed the file has it or has failed (list_files with shared_with_anyone finds links still open). Sharing inherited from a folder is removed on the folder, and the owner's cannot be removed.",
2458
+ inputSchema: {
2459
+ type: "object",
2460
+ properties: {
2461
+ file_id: ID,
2462
+ permission_id: { type: "string", pattern: ID_PATTERN, description: "The permission id, e.g. anyoneWithLink." }
2463
+ },
2464
+ required: ["file_id", "permission_id"],
2465
+ additionalProperties: false
2466
+ },
2467
+ async run(args, h) {
2468
+ await assertInside(h, args.file_id);
2469
+ await drive(h, {
2470
+ method: "DELETE",
2471
+ path: `/drive/v3/files/${enc(args.file_id)}/permissions/${enc(args.permission_id)}`,
2472
+ query: { supportsAllDrives: true },
2473
+ write: true,
2474
+ errors: { 404: "Google Drive found no such sharing on the file (it may be removed already), or no such file" }
2475
+ });
2476
+ return { removed: true, fileId: args.file_id, permissionId: args.permission_id };
2477
+ }
2478
+ },
2479
+ {
2480
+ name: "get_spreadsheet",
2481
+ kind: "read",
2482
+ title: "Get a Google Sheet's sheets",
2483
+ description: "Returns a Google Sheet's title, locale, time zone, link and its sheets (tabs) with their ids, names and sizes, to pick a range for read_sheet.",
2484
+ inputSchema: { type: "object", properties: { spreadsheet_id: { ...ID, description: "The spreadsheet id (the part after /d/ in its link)." } }, required: ["spreadsheet_id"], additionalProperties: false },
2485
+ async run(args, h) {
2486
+ await assertInside(h, args.spreadsheet_id, "spreadsheet");
2487
+ const { data } = await drive(h, {
2488
+ origin: SHEETS_ORIGIN,
2489
+ path: `/v4/spreadsheets/${enc(args.spreadsheet_id)}`,
2490
+ query: { fields: "spreadsheetId,spreadsheetUrl,properties(title,locale,timeZone),sheets(properties(sheetId,title,index,sheetType,gridProperties(rowCount,columnCount)))" }
2491
+ });
2492
+ const sheets = Array.isArray(data?.sheets) ? data.sheets : [];
2493
+ return compact({
2494
+ spreadsheetId: data?.spreadsheetId,
2495
+ title: data?.properties?.title,
2496
+ locale: data?.properties?.locale,
2497
+ timeZone: data?.properties?.timeZone,
2498
+ url: data?.spreadsheetUrl,
2499
+ sheets: sheets.slice(0, 200).map((sheet) => compact({
2500
+ sheetId: sheet?.properties?.sheetId,
2501
+ title: sheet?.properties?.title,
2502
+ index: sheet?.properties?.index,
2503
+ type: sheet?.properties?.sheetType,
2504
+ rows: sheet?.properties?.gridProperties?.rowCount,
2505
+ columns: sheet?.properties?.gridProperties?.columnCount
2506
+ }))
2507
+ });
2508
+ }
2509
+ },
2510
+ {
2511
+ name: "read_sheet",
2512
+ kind: "read",
2513
+ title: "Read a Google Sheet range",
2514
+ description: "Reads the cells of a range, row by row (trailing empty cells left out): as shown (default), as raw values, or with formulas. Pass nextCursor back as cursor for the next rows of a long range.",
2515
+ inputSchema: {
2516
+ type: "object",
2517
+ properties: {
2518
+ spreadsheet_id: { ...ID, description: "The spreadsheet id (the part after /d/ in its link)." },
2519
+ range: RANGE,
2520
+ render: { type: "string", enum: ["FORMATTED_VALUE", "UNFORMATTED_VALUE", "FORMULA"], default: "FORMATTED_VALUE", description: "FORMATTED_VALUE (as shown, default), UNFORMATTED_VALUE (raw numbers) or FORMULA." },
2521
+ cursor: { type: "string", description: "nextCursor from the previous result." }
2522
+ },
2523
+ required: ["spreadsheet_id", "range"],
2524
+ additionalProperties: false
2525
+ },
2526
+ async run(args, h) {
2527
+ const state = h.cursor(args.cursor);
2528
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
2529
+ await assertInside(h, args.spreadsheet_id, "spreadsheet");
2530
+ const { data } = await drive(h, {
2531
+ origin: SHEETS_ORIGIN,
2532
+ path: valuesPath(args.spreadsheet_id, args.range),
2533
+ query: { valueRenderOption: args.render, majorDimension: "ROWS" },
2534
+ errors: { 400: "Google Sheets did not accept the range: check the sheet name and the A1 notation" }
2535
+ });
2536
+ const rows = Array.isArray(data?.values) ? data.values : [];
2537
+ return h.page({
2538
+ key: "rows",
2539
+ items: rows.slice(skip),
2540
+ extra: compact({ range: data?.range, totalRows: rows.length, firstRow: skip || void 0 }),
2541
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
2542
+ });
2543
+ }
2544
+ },
2545
+ {
2546
+ name: "append_rows",
2547
+ kind: "create",
2548
+ check: "read_sheet",
2549
+ title: "Append rows to a Google Sheet",
2550
+ description: "Adds rows after the last row of the table in a range, e.g. Sheet1!A1 or Sheet1!A:D. Returns the range written and the counts.",
2551
+ inputSchema: {
2552
+ type: "object",
2553
+ properties: { spreadsheet_id: { ...ID, description: "The spreadsheet id." }, range: RANGE, rows: CELL_ROWS, value_input: VALUE_INPUT },
2554
+ required: ["spreadsheet_id", "range", "rows"],
2555
+ additionalProperties: false
2556
+ },
2557
+ async run(args, h) {
2558
+ const rows = checkRows(args.rows, "rows");
2559
+ await assertInside(h, args.spreadsheet_id, "spreadsheet");
2560
+ const { data } = await drive(h, {
2561
+ method: "POST",
2562
+ origin: SHEETS_ORIGIN,
2563
+ path: valuesPath(args.spreadsheet_id, args.range, ":append"),
2564
+ query: { valueInputOption: args.value_input, insertDataOption: "INSERT_ROWS" },
2565
+ json: { majorDimension: "ROWS", values: rows },
2566
+ write: true
2567
+ });
2568
+ const updates = data?.updates ?? {};
2569
+ return compact({ spreadsheetId: args.spreadsheet_id, updatedRange: updates.updatedRange, updatedRows: updates.updatedRows, updatedCells: updates.updatedCells });
2570
+ }
2571
+ },
2572
+ {
2573
+ name: "update_range",
2574
+ kind: "update",
2575
+ check: "read_sheet",
2576
+ title: "Write cells in a Google Sheet",
2577
+ description: "Overwrites the cells of a range with rows, starting at its top-left cell, e.g. Sheet1!B2:C3. Cells outside the rows given stay as they are.",
2578
+ inputSchema: {
2579
+ type: "object",
2580
+ properties: { spreadsheet_id: { ...ID, description: "The spreadsheet id." }, range: RANGE, rows: CELL_ROWS, value_input: VALUE_INPUT },
2581
+ required: ["spreadsheet_id", "range", "rows"],
2582
+ additionalProperties: false
2583
+ },
2584
+ async run(args, h) {
2585
+ const rows = checkRows(args.rows, "rows");
2586
+ await assertInside(h, args.spreadsheet_id, "spreadsheet");
2587
+ const { data } = await drive(h, {
2588
+ method: "PUT",
2589
+ origin: SHEETS_ORIGIN,
2590
+ path: valuesPath(args.spreadsheet_id, args.range),
2591
+ query: { valueInputOption: args.value_input },
2592
+ json: { majorDimension: "ROWS", values: rows },
2593
+ write: true
2594
+ });
2595
+ return compact({ spreadsheetId: args.spreadsheet_id, updatedRange: data?.updatedRange, updatedRows: data?.updatedRows, updatedCells: data?.updatedCells });
2596
+ }
2597
+ },
2598
+ {
2599
+ name: "clear_range",
2600
+ kind: "delete",
2601
+ check: "read_sheet",
2602
+ title: "Clear cells in a Google Sheet",
2603
+ description: "Clears the values of a range (formatting stays), e.g. Sheet1!A2:Z1000.",
2604
+ inputSchema: {
2605
+ type: "object",
2606
+ properties: { spreadsheet_id: { ...ID, description: "The spreadsheet id." }, range: RANGE },
2607
+ required: ["spreadsheet_id", "range"],
2608
+ additionalProperties: false
2609
+ },
2610
+ async run(args, h) {
2611
+ await assertInside(h, args.spreadsheet_id, "spreadsheet");
2612
+ const { data } = await drive(h, { method: "POST", origin: SHEETS_ORIGIN, path: valuesPath(args.spreadsheet_id, args.range, ":clear"), json: {}, write: true });
2613
+ return compact({ spreadsheetId: args.spreadsheet_id, clearedRange: data?.clearedRange });
2614
+ }
2615
+ },
2616
+ {
2617
+ name: "add_document_text",
2618
+ kind: "create",
2619
+ check: "read_file",
2620
+ title: "Add text to a Google Doc",
2621
+ description: "Inserts plain text at the end (default) or the start of a Google Doc. read_file shows the result; other edits go through api_request (the Docs batchUpdate method).",
2622
+ inputSchema: {
2623
+ type: "object",
2624
+ properties: {
2625
+ document_id: { ...ID, description: "The document id (the part after /d/ in its link)." },
2626
+ text: { type: "string", minLength: 1, maxLength: 2e5, description: "The text to insert; \\n starts a new paragraph." },
2627
+ position: { type: "string", enum: ["end", "start"], default: "end", description: "end (default) or start." }
2628
+ },
2629
+ required: ["document_id", "text"],
2630
+ additionalProperties: false
2631
+ },
2632
+ async run(args, h) {
2633
+ await assertInside(h, args.document_id, "document");
2634
+ const insertText = args.position === "start" ? { location: { index: 1 }, text: args.text } : { endOfSegmentLocation: {}, text: args.text };
2635
+ const { data } = await drive(h, {
2636
+ method: "POST",
2637
+ origin: DOCS_ORIGIN,
2638
+ path: `/v1/documents/${enc(args.document_id)}:batchUpdate`,
2639
+ json: { requests: [{ insertText }] },
2640
+ write: true
2641
+ });
2642
+ return compact({ documentId: data?.documentId ?? args.document_id, position: args.position, characters: args.text.length });
2643
+ }
2644
+ },
2645
+ ...apiTools({
2646
+ label: LABEL2,
2647
+ description: `The Google Drive API v3 (https://www.googleapis.com: /drive/v3/..., /upload/drive/v3/...), Sheets API v4 (https://sheets.googleapis.com: /v4/spreadsheets/...) and Docs API v1 (https://docs.googleapis.com: /v1/documents/...), as the service account; pass origin for Sheets or Docs, and supportsAllDrives=true for shared drives. While the connection is limited to chosen folders, paths must name a file inside them, and a file listing needs a q such as "'FOLDER_ID' in parents and trashed=false". Reference: https://developers.google.com/workspace/drive/api/reference/rest/v3 (Sheets and Docs: /workspace/sheets/api/reference/rest, /workspace/docs/api/reference/rest).`,
2648
+ originArgument: "https://www.googleapis.com for Drive (default), https://sheets.googleapis.com for Sheets, https://docs.googleapis.com for Docs.",
2649
+ guard: driveGuard,
2650
+ send: (request, h) => drive(h, request)
2651
+ })
2652
+ ]
2653
+ });
2654
+ module.exports = connector;