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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1185 -34
  3. package/dist/cli.js +15 -12
  4. package/dist/core/credentials.d.ts +21 -0
  5. package/dist/core/credentials.js +45 -0
  6. package/dist/core/origins.d.ts +18 -0
  7. package/dist/core/origins.js +40 -0
  8. package/dist/core/upload-hosts.d.ts +15 -0
  9. package/dist/core/upload-hosts.js +43 -0
  10. package/dist/host/describe.d.ts +10 -0
  11. package/dist/host/describe.js +38 -0
  12. package/dist/host/env.d.ts +25 -2
  13. package/dist/host/env.js +24 -7
  14. package/dist/host/guarded-fetch.d.ts +36 -9
  15. package/dist/host/guarded-fetch.js +175 -52
  16. package/dist/host/index.d.ts +8 -5
  17. package/dist/host/index.js +12 -1
  18. package/dist/host/load.js +31 -1
  19. package/dist/host/server.d.ts +13 -2
  20. package/dist/host/server.js +15 -2
  21. package/dist/types.d.ts +96 -5
  22. package/dist/vendors/adapty.js +1303 -0
  23. package/dist/vendors/adjust.js +1372 -0
  24. package/dist/vendors/apollo.js +2499 -0
  25. package/dist/vendors/apple-appstore.js +2798 -0
  26. package/dist/vendors/beehiiv.js +1965 -0
  27. package/dist/vendors/blogger.js +1687 -0
  28. package/dist/vendors/bluesky.js +850 -127
  29. package/dist/vendors/brevo.js +2195 -0
  30. package/dist/vendors/calendarific.js +1116 -0
  31. package/dist/vendors/devto.js +685 -92
  32. package/dist/vendors/facebook-pages.js +2185 -0
  33. package/dist/vendors/firebase.js +1333 -0
  34. package/dist/vendors/ga4.js +1585 -0
  35. package/dist/vendors/gmail.js +1962 -0
  36. package/dist/vendors/google-ads.js +2201 -0
  37. package/dist/vendors/google-business.js +1621 -0
  38. package/dist/vendors/google-calendar.js +1936 -0
  39. package/dist/vendors/google-drive.js +2654 -0
  40. package/dist/vendors/google-merchant-center.js +1742 -0
  41. package/dist/vendors/google-play.js +1856 -0
  42. package/dist/vendors/google-search-console.js +1572 -0
  43. package/dist/vendors/hashnode.js +1722 -0
  44. package/dist/vendors/instagram.js +2249 -0
  45. package/dist/vendors/kaggle.js +2043 -0
  46. package/dist/vendors/keepa.js +2087 -0
  47. package/dist/vendors/linkedin.js +1588 -0
  48. package/dist/vendors/mailchimp.js +2402 -0
  49. package/dist/vendors/mastodon.js +1836 -0
  50. package/dist/vendors/meta-ads.js +2375 -0
  51. package/dist/vendors/notion.js +1950 -0
  52. package/dist/vendors/pinterest.js +1744 -0
  53. package/dist/vendors/qiita.js +1552 -0
  54. package/dist/vendors/reddit.js +1791 -0
  55. package/dist/vendors/revenuecat.js +1593 -0
  56. package/dist/vendors/roasit.js +1460 -0
  57. package/dist/vendors/sendgrid.js +2188 -0
  58. package/dist/vendors/serper.js +901 -179
  59. package/dist/vendors/shopify.js +2511 -0
  60. package/dist/vendors/threads.js +1869 -0
  61. package/dist/vendors/tiktok.js +2199 -0
  62. package/dist/vendors/tumblr.js +1793 -0
  63. package/dist/vendors/twitter.js +1650 -0
  64. package/dist/vendors/woocommerce.js +2258 -0
  65. package/dist/vendors/wordpress.js +1904 -0
  66. package/dist/vendors/youtube.js +2542 -0
  67. package/package.json +12 -1
@@ -0,0 +1,1936 @@
1
+ /* google-calendar connector module (MIT License). Built from src/vendors/google-calendar; 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-calendar/service-account.ts
1224
+ var KEY_CREDENTIAL = "serviceaccountjson";
1225
+ function keyFileText(value) {
1226
+ const text = (value ?? "").trim();
1227
+ if (text.startsWith("{")) return text;
1228
+ const raw = text.replace(/^data:[^,]*;base64,/i, "").replace(/-/g, "+").replace(/_/g, "/");
1229
+ try {
1230
+ const decoded = utf8Decode(base64Decode(raw)).trim();
1231
+ if (decoded.startsWith("{")) return decoded;
1232
+ } catch {
1233
+ }
1234
+ return text;
1235
+ }
1236
+ function serviceAccountEmail(h) {
1237
+ try {
1238
+ const data = JSON.parse(keyFileText(h.credentials[KEY_CREDENTIAL]));
1239
+ const email = data?.client_email;
1240
+ return typeof email === "string" && /^[^\s@]+@[^\s@]+$/.test(email) ? email : void 0;
1241
+ } catch {
1242
+ return void 0;
1243
+ }
1244
+ }
1245
+ function serviceAccountWords(h) {
1246
+ const email = serviceAccountEmail(h);
1247
+ return email ? `the service account ${email}` : "the service account";
1248
+ }
1249
+ async function googleApi(h, scopes, request) {
1250
+ const token = await googleServiceAccountToken(h, keyFileText(h.credentials[KEY_CREDENTIAL]), { scopes });
1251
+ return h.api({ ...request, headers: { ...request.headers, authorization: `Bearer ${token}` } });
1252
+ }
1253
+
1254
+ // src/vendors/google-calendar/time.ts
1255
+ var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
1256
+ var MINUTE = 6e4;
1257
+ var DAY = 24 * 60 * MINUTE;
1258
+ var MAX_FORMATTERS = 32;
1259
+ var formatters = /* @__PURE__ */ new Map();
1260
+ function isTimeZone(zone) {
1261
+ if (!/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/.test(zone)) return false;
1262
+ try {
1263
+ new Intl.DateTimeFormat("en-US", { timeZone: zone });
1264
+ return true;
1265
+ } catch {
1266
+ return false;
1267
+ }
1268
+ }
1269
+ function formatter(zone) {
1270
+ let found = formatters.get(zone);
1271
+ if (!found) {
1272
+ found = new Intl.DateTimeFormat("en-US", {
1273
+ timeZone: zone,
1274
+ hourCycle: "h23",
1275
+ year: "numeric",
1276
+ month: "2-digit",
1277
+ day: "2-digit",
1278
+ hour: "2-digit",
1279
+ minute: "2-digit",
1280
+ second: "2-digit"
1281
+ });
1282
+ if (formatters.size >= MAX_FORMATTERS) formatters.clear();
1283
+ formatters.set(zone, found);
1284
+ }
1285
+ return found;
1286
+ }
1287
+ function wallTime(ms, zone) {
1288
+ const parts = formatter(zone).formatToParts(new Date(ms));
1289
+ const get = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0);
1290
+ return { year: get("year"), month: get("month"), day: get("day"), hour: get("hour") % 24, minute: get("minute"), second: get("second") };
1291
+ }
1292
+ function offsetAt(ms, zone) {
1293
+ const wall = wallTime(ms, zone);
1294
+ return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(ms / 1e3) * 1e3;
1295
+ }
1296
+ function instantOf(year, month, day, hour, minute, second, zone) {
1297
+ const guess = Date.UTC(year, month - 1, day, hour, minute, second);
1298
+ const first = offsetAt(guess, zone);
1299
+ const instant = guess - first;
1300
+ const second2 = offsetAt(instant, zone);
1301
+ return second2 === first ? instant : guess - second2;
1302
+ }
1303
+ function pad(value, width = 2) {
1304
+ return String(value).padStart(width, "0");
1305
+ }
1306
+ function formatInZone(ms, zone) {
1307
+ const wall = wallTime(ms, zone);
1308
+ const offset = Math.round(offsetAt(ms, zone) / MINUTE);
1309
+ const abs = Math.abs(offset);
1310
+ return `${pad(wall.year, 4)}-${pad(wall.month)}-${pad(wall.day)}T${pad(wall.hour)}:${pad(wall.minute)}:${pad(wall.second)}${offset < 0 ? "-" : "+"}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
1311
+ }
1312
+ function formatUtc(ms) {
1313
+ return new Date(Math.floor(ms / 1e3) * 1e3).toISOString().replace(".000Z", "Z");
1314
+ }
1315
+ var TIME_PATTERN = "^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?(Z|[+-]\\d{2}:\\d{2})?)?$";
1316
+ var DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})?)?$/;
1317
+ function realDate(year, month, day) {
1318
+ const date = new Date(Date.UTC(year, month - 1, day));
1319
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
1320
+ }
1321
+ function parseTime(text) {
1322
+ const match = DATE_TIME.exec(text);
1323
+ if (!match) return null;
1324
+ const [, y, mo, d, hh, mi, ss, , zone] = match;
1325
+ const year = Number(y);
1326
+ const month = Number(mo);
1327
+ const day = Number(d);
1328
+ if (!realDate(year, month, day)) return null;
1329
+ if (hh === void 0) return { kind: "date", year, month, day };
1330
+ const hour = Number(hh);
1331
+ const minute = Number(mi);
1332
+ const second = ss === void 0 ? 0 : Number(ss);
1333
+ if (hour > 23 || minute > 59 || second > 59) return null;
1334
+ if (zone !== void 0) {
1335
+ const ms = Date.parse(text);
1336
+ return Number.isFinite(ms) ? { kind: "instant", ms, text } : null;
1337
+ }
1338
+ return { kind: "local", year, month, day, hour, minute, second, text };
1339
+ }
1340
+ function toInstant(time, zone) {
1341
+ if (time.kind === "instant") return time.ms;
1342
+ if (time.kind === "date") return instantOf(time.year, time.month, time.day, 0, 0, 0, zone);
1343
+ return instantOf(time.year, time.month, time.day, time.hour, time.minute, time.second, zone);
1344
+ }
1345
+ function addDays(date, days) {
1346
+ const next = new Date(Date.UTC(date.year, date.month - 1, date.day + days));
1347
+ return { year: next.getUTCFullYear(), month: next.getUTCMonth() + 1, day: next.getUTCDate() };
1348
+ }
1349
+ function addMinutesToLocal(time, minutes) {
1350
+ const moved = new Date(Date.UTC(time.year, time.month - 1, time.day, time.hour, time.minute + minutes, time.second));
1351
+ return `${pad(moved.getUTCFullYear(), 4)}-${pad(moved.getUTCMonth() + 1)}-${pad(moved.getUTCDate())}T${pad(moved.getUTCHours())}:${pad(moved.getUTCMinutes())}:${pad(moved.getUTCSeconds())}`;
1352
+ }
1353
+ function minutesOfDay(text) {
1354
+ const [hours, minutes] = text.split(":").map(Number);
1355
+ return hours * 60 + minutes;
1356
+ }
1357
+ function mergeIntervals(intervals) {
1358
+ const sorted = intervals.filter(([start, end]) => end > start).sort((a, b) => a[0] - b[0]);
1359
+ const merged = [];
1360
+ for (const [start, end] of sorted) {
1361
+ const last = merged[merged.length - 1];
1362
+ if (last && start <= last[1]) last[1] = Math.max(last[1], end);
1363
+ else merged.push([start, end]);
1364
+ }
1365
+ return merged;
1366
+ }
1367
+ function findFreeSlots(search) {
1368
+ const busy = mergeIntervals(search.busy.map(([start, end]) => [start - search.bufferMs, end + search.bufferMs]));
1369
+ const slots = [];
1370
+ const lowest = Math.max(search.from, search.earliest);
1371
+ const first = wallTime(search.from, search.zone);
1372
+ let date = { year: first.year, month: first.month, day: first.day };
1373
+ date = addDays(date, -1);
1374
+ for (let guard = 0; guard < 400; guard++) {
1375
+ const midnight = instantOf(date.year, date.month, date.day, 0, 0, 0, search.zone);
1376
+ if (midnight >= search.to) break;
1377
+ const weekday = new Date(Date.UTC(date.year, date.month - 1, date.day)).getUTCDay();
1378
+ const starts = /* @__PURE__ */ new Set();
1379
+ const candidates = [];
1380
+ for (const rule of search.rules) {
1381
+ if (!rule.days.includes(weekday)) continue;
1382
+ const open = instantOf(date.year, date.month, date.day, Math.floor(rule.start / 60), rule.start % 60, 0, search.zone);
1383
+ const nextDay = addDays(date, 1);
1384
+ const close = rule.end >= 1440 ? instantOf(nextDay.year, nextDay.month, nextDay.day, 0, 0, 0, search.zone) : instantOf(date.year, date.month, date.day, Math.floor(rule.end / 60), rule.end % 60, 0, search.zone);
1385
+ for (let start = open; start + search.slotMs <= close; start += search.stepMs) {
1386
+ const end = start + search.slotMs;
1387
+ if (start < lowest || end > search.to || starts.has(start)) continue;
1388
+ starts.add(start);
1389
+ candidates.push([start, end]);
1390
+ }
1391
+ }
1392
+ candidates.sort((a, b) => a[0] - b[0]);
1393
+ for (const [start, end] of candidates) {
1394
+ if (busy.some(([busyStart, busyEnd]) => start < busyEnd && end > busyStart)) continue;
1395
+ if (slots.length >= search.max) return { slots, next: start };
1396
+ slots.push([start, end]);
1397
+ }
1398
+ date = addDays(date, 1);
1399
+ }
1400
+ return { slots };
1401
+ }
1402
+ var DAY_MS = DAY;
1403
+ var MINUTE_MS = MINUTE;
1404
+
1405
+ // src/vendors/google-calendar/index.ts
1406
+ var LABEL2 = "Google Calendar";
1407
+ var API_ORIGIN = "https://www.googleapis.com";
1408
+ var TOKEN_ORIGIN = "https://oauth2.googleapis.com";
1409
+ var SCOPES = ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.events"];
1410
+ var DEFAULT_SLOT_MINUTES = 30;
1411
+ var MAX_RANGE_DAYS = 62;
1412
+ var DEFAULT_HOURS = [{ days: [1, 2, 3, 4, 5], start: 9 * 60, end: 18 * 60 }];
1413
+ var BASE32HEX = "0123456789abcdefghijklmnopqrstuv";
1414
+ var MAX_BUSY_RETURNED = 100;
1415
+ var EVENT_ID_PATTERN = "^[A-Za-z0-9_-]{1,1024}$";
1416
+ var NO_EVENT = { 404: "Google Calendar found no such event on the connected calendar" };
1417
+ var NOTHING_CHANGED = " Nothing was changed.";
1418
+ function compact(value) {
1419
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
1420
+ }
1421
+ function calendarIdOf(h) {
1422
+ const id = h.credentials["calendarid"];
1423
+ if (id === "." || id === "..") throw new ToolFailure("The Google Calendar calendar ID is not a calendar ID: copy it from the calendar's settings, under Integrate calendar. Nothing was sent.");
1424
+ return id;
1425
+ }
1426
+ function calendarPath(h, rest = "") {
1427
+ return `/calendar/v3/calendars/${encodeURIComponent(calendarIdOf(h))}${rest}`;
1428
+ }
1429
+ function eventPath(h, eventId) {
1430
+ return calendarPath(h, `/events/${encodeURIComponent(eventId)}`);
1431
+ }
1432
+ function defaultSlotMinutes(h) {
1433
+ const value = Number(h.credentials["slotdurationminutes"]);
1434
+ return Number.isInteger(value) && value >= 5 && value <= 480 ? value : DEFAULT_SLOT_MINUTES;
1435
+ }
1436
+ var USAGE_LIMIT = /rate limit|usage limit|quota exceeded|too many requests/i;
1437
+ var NO_GUESTS = /domain-wide delegation|forbiddenForServiceAccounts/i;
1438
+ function explainRefusal(h, error) {
1439
+ if (!(error instanceof ToolFailure) || error.details.status !== 403) return error;
1440
+ const ending = error.message.endsWith(NOTHING_CHANGED) ? NOTHING_CHANGED : "";
1441
+ const text = error.message.slice(0, error.message.length - ending.length);
1442
+ const advice = NO_GUESTS.test(text) ? "Google Calendar does not let a service account invite guests: add guests in Google Calendar itself." : USAGE_LIMIT.test(text) ? "That is a Google Calendar usage limit, not a sharing problem: wait a minute and try again." : `Share the calendar with ${serviceAccountWords(h)} (Settings and sharing -> Share with specific people, "Make changes to events"), and check that the Google Calendar API is enabled for the key's project.`;
1443
+ return new ToolFailure(`${text} ${advice}${ending}`, error.details);
1444
+ }
1445
+ async function calendar(h, request) {
1446
+ try {
1447
+ return await googleApi(h, SCOPES, {
1448
+ ...request,
1449
+ errors: {
1450
+ 404: `Google Calendar found nothing there: check the calendar ID and that the calendar is shared with ${serviceAccountWords(h)}`,
1451
+ ...request.errors
1452
+ }
1453
+ });
1454
+ } catch (error) {
1455
+ throw explainRefusal(h, error);
1456
+ }
1457
+ }
1458
+ async function zoneFor(h, given) {
1459
+ const zone = given || h.credentials["timezone"];
1460
+ if (zone) {
1461
+ if (!isTimeZone(zone)) {
1462
+ throw new ToolFailure(
1463
+ `"${truncate(zone, 64)}" is not an IANA time zone such as Europe/Istanbul or America/New_York${given ? "" : " (it is the connection's time zone setting)"}. Nothing was sent.`
1464
+ );
1465
+ }
1466
+ return zone;
1467
+ }
1468
+ const { data } = await calendar(h, { path: calendarPath(h), query: { fields: "timeZone" } });
1469
+ return typeof data?.timeZone === "string" && isTimeZone(data.timeZone) ? data.timeZone : "UTC";
1470
+ }
1471
+ function timeOf(text, field) {
1472
+ const parsed = parseTime(text);
1473
+ if (!parsed) throw new ToolFailure(`${field} is not a valid date or date-time, such as 2026-05-11 or 2026-05-11T09:00:00. Nothing was sent.`);
1474
+ return parsed;
1475
+ }
1476
+ function trimEvent(event) {
1477
+ const attendees = Array.isArray(event?.attendees) ? event.attendees : [];
1478
+ const overrides = Array.isArray(event?.reminders?.overrides) ? event.reminders.overrides : [];
1479
+ return compact({
1480
+ id: event?.id,
1481
+ status: event?.status,
1482
+ summary: event?.summary,
1483
+ description: typeof event?.description === "string" ? truncate(event.description, 2e3) : void 0,
1484
+ location: event?.location,
1485
+ start: event?.start?.dateTime ?? event?.start?.date,
1486
+ end: event?.end?.dateTime ?? event?.end?.date,
1487
+ allDay: event?.start?.date ? true : void 0,
1488
+ timeZone: event?.start?.timeZone,
1489
+ recurrence: Array.isArray(event?.recurrence) ? event.recurrence : void 0,
1490
+ recurringEventId: event?.recurringEventId,
1491
+ attendees: attendees.length ? attendees.slice(0, 50).map((attendee) => compact({
1492
+ email: attendee?.email,
1493
+ name: attendee?.displayName,
1494
+ responseStatus: attendee?.responseStatus,
1495
+ organizer: attendee?.organizer === true ? true : void 0,
1496
+ optional: attendee?.optional === true ? true : void 0
1497
+ })) : void 0,
1498
+ attendeeCount: attendees.length > 50 ? attendees.length : void 0,
1499
+ organizer: event?.organizer?.email,
1500
+ reminders: event?.reminders?.useDefault === true ? "default" : overrides.length ? overrides.map((item) => compact({ method: item?.method, minutes: item?.minutes })) : void 0,
1501
+ transparency: event?.transparency,
1502
+ visibility: event?.visibility,
1503
+ colorId: event?.colorId,
1504
+ privateProperties: event?.extendedProperties?.private,
1505
+ htmlLink: event?.htmlLink,
1506
+ hangoutLink: event?.hangoutLink,
1507
+ created: event?.created,
1508
+ updated: event?.updated
1509
+ });
1510
+ }
1511
+ function newEventId() {
1512
+ const bytes = crypto.getRandomValues(new Uint8Array(26));
1513
+ return Array.from(bytes, (byte) => BASE32HEX[byte & 31]).join("");
1514
+ }
1515
+ var EVENT_FIELDS = {
1516
+ summary: { type: "string", minLength: 1, maxLength: 1024, description: "The event title." },
1517
+ description: { type: "string", maxLength: 8e3, description: "The event description (plain text or simple HTML)." },
1518
+ location: { type: "string", maxLength: 1024, description: "A place or an address." },
1519
+ start: {
1520
+ type: "string",
1521
+ pattern: TIME_PATTERN,
1522
+ description: "When it starts: 2026-05-11T09:00:00 (in timezone), 2026-05-11T09:00:00+03:00, or a date such as 2026-05-11 for an all-day event."
1523
+ },
1524
+ end: {
1525
+ type: "string",
1526
+ pattern: TIME_PATTERN,
1527
+ description: "When it ends, in the same form as start (for an all-day event, the day after the last day)."
1528
+ },
1529
+ timezone: { type: "string", maxLength: 64, description: "An IANA time zone such as Europe/Istanbul for times without an offset. Default: the connection's time zone, else the calendar's." },
1530
+ reminder_minutes: {
1531
+ type: "array",
1532
+ items: { type: "integer", minimum: 0, maximum: 40320 },
1533
+ maxItems: 5,
1534
+ description: "Pop-up reminders, in minutes before the start, e.g. [10, 60]. Default: the calendar's own reminders."
1535
+ },
1536
+ recurrence: {
1537
+ type: "array",
1538
+ items: { type: "string", pattern: "^(RRULE|EXRULE|RDATE|EXDATE)[:;]", maxLength: 500 },
1539
+ maxItems: 10,
1540
+ description: 'Repeat rules, e.g. ["RRULE:FREQ=WEEKLY;COUNT=4"] (needs a time zone).'
1541
+ },
1542
+ color_id: { type: "string", pattern: "^([1-9]|1[01])$", description: 'An event color, "1" to "11".' },
1543
+ visibility: { type: "string", enum: ["default", "public", "private", "confidential"], description: "Who can see the details." },
1544
+ transparency: { type: "string", enum: ["opaque", "transparent"], description: "opaque blocks the time (busy); transparent shows it as free." },
1545
+ private_properties: { type: "object", description: 'Up to 20 private key-value tags on the event, values as text, e.g. {"source": "phone"}.' },
1546
+ send_updates: {
1547
+ type: "string",
1548
+ enum: ["all", "externalOnly", "none"],
1549
+ description: "Who gets an email about the change: it only matters for an event whose guests were added in Google Calendar itself. Default: Google Calendar's default, none."
1550
+ }
1551
+ };
1552
+ function checkProperties(value) {
1553
+ if (value === void 0) return void 0;
1554
+ const entries = Object.entries(value);
1555
+ if (entries.length > 20) throw new ToolFailure("private_properties takes at most 20 entries. Nothing was sent.");
1556
+ for (const [key, item] of entries) {
1557
+ if (typeof item !== "string" || key.length > 44 || item.length > 1024) {
1558
+ throw new ToolFailure("private_properties values must be text (keys up to 44 characters, values up to 1024). Nothing was sent.");
1559
+ }
1560
+ }
1561
+ return value;
1562
+ }
1563
+ function eventTime(time, zone, patch) {
1564
+ if (time.kind === "date") {
1565
+ const text2 = `${String(time.year).padStart(4, "0")}-${String(time.month).padStart(2, "0")}-${String(time.day).padStart(2, "0")}`;
1566
+ return patch ? { date: text2, dateTime: null, timeZone: null } : { date: text2 };
1567
+ }
1568
+ const text = time.text.length === 16 ? `${time.text}:00` : time.text;
1569
+ return { ...patch ? { date: null } : {}, dateTime: text, ...zone ? { timeZone: zone } : {} };
1570
+ }
1571
+ async function eventBody(h, args, patch) {
1572
+ const body = {};
1573
+ if (args.summary !== void 0) body["summary"] = args.summary;
1574
+ if (args.description !== void 0) body["description"] = args.description;
1575
+ if (args.location !== void 0) body["location"] = args.location;
1576
+ if (args.reminder_minutes !== void 0) {
1577
+ body["reminders"] = { useDefault: false, overrides: args.reminder_minutes.map((minutes) => ({ method: "popup", minutes })) };
1578
+ } else if (!patch) {
1579
+ body["reminders"] = { useDefault: true };
1580
+ }
1581
+ if (args.recurrence !== void 0) body["recurrence"] = args.recurrence;
1582
+ if (args.color_id !== void 0) body["colorId"] = args.color_id;
1583
+ if (args.visibility !== void 0) body["visibility"] = args.visibility;
1584
+ if (args.transparency !== void 0) body["transparency"] = args.transparency;
1585
+ if (args.status !== void 0) body["status"] = args.status;
1586
+ const properties = checkProperties(args.private_properties);
1587
+ if (properties) body["extendedProperties"] = { private: properties };
1588
+ const start = args.start !== void 0 ? timeOf(args.start, "start") : void 0;
1589
+ let end = args.end !== void 0 ? timeOf(args.end, "end") : void 0;
1590
+ if (args.duration_minutes !== void 0) {
1591
+ if (end) throw new ToolFailure("Give end or duration_minutes, not both. Nothing was sent.");
1592
+ if (!start || start.kind === "date") throw new ToolFailure("duration_minutes needs a start with a time of day. Nothing was sent.");
1593
+ }
1594
+ if (!patch && start && !end) {
1595
+ if (start.kind === "date") throw new ToolFailure("An all-day event needs an end date (the day after its last day). Nothing was sent.");
1596
+ const minutes = args.duration_minutes ?? defaultSlotMinutes(h);
1597
+ end = start.kind === "instant" ? { kind: "instant", ms: start.ms + minutes * MINUTE_MS, text: new Date(start.ms + minutes * MINUTE_MS).toISOString() } : timeOf(addMinutesToLocal(start, minutes), "end");
1598
+ } else if (patch && start && args.duration_minutes !== void 0) {
1599
+ end = start.kind === "instant" ? { kind: "instant", ms: start.ms + args.duration_minutes * MINUTE_MS, text: new Date(start.ms + args.duration_minutes * MINUTE_MS).toISOString() } : timeOf(addMinutesToLocal(start, args.duration_minutes), "end");
1600
+ }
1601
+ if (start && end && start.kind === "date" !== (end.kind === "date")) {
1602
+ throw new ToolFailure("start and end must both be dates (an all-day event) or both have a time of day. Nothing was sent.");
1603
+ }
1604
+ const needsZone = [start, end].some((time) => time?.kind === "local") || args.recurrence !== void 0 && start?.kind !== "date";
1605
+ const named = args.timezone || h.credentials["timezone"];
1606
+ const zone = (start || end) && (needsZone || named) ? await zoneFor(h, args.timezone) : void 0;
1607
+ if (start && end) {
1608
+ const zoneForCheck = zone ?? "UTC";
1609
+ if (toInstant(end, zoneForCheck) <= toInstant(start, zoneForCheck)) throw new ToolFailure("end must be after start. Nothing was sent.");
1610
+ }
1611
+ if (start) body["start"] = eventTime(start, zone, patch);
1612
+ if (end) body["end"] = eventTime(end, zone, patch);
1613
+ return body;
1614
+ }
1615
+ function calendarGuard(request, h) {
1616
+ const calendarId = calendarIdOf(h);
1617
+ const [, , collection, id, sub, subId, action] = request.segments;
1618
+ const refuse = (what) => {
1619
+ throw new ToolFailure(`${what} This connection works on the calendar ${calendarId} only. Nothing was sent.`);
1620
+ };
1621
+ if (collection === "calendars") {
1622
+ if (id === void 0 && request.method !== "GET") refuse("Creating calendars is not available here.");
1623
+ if (id !== void 0 && id !== calendarId) refuse(`The path names the calendar ${truncate(id, 100)}.`);
1624
+ if (sub === "events" && subId !== void 0 && action === "move") {
1625
+ const destination = request.query["destination"] ?? [];
1626
+ if (destination.length !== 1 || destination[0] !== calendarId) refuse("Moving an event to another calendar is not available here.");
1627
+ }
1628
+ }
1629
+ if (collection === "users" && id === "me" && sub === "calendarList") {
1630
+ if (subId === void 0) refuse("The calendar list names other calendars, so it is not available here.");
1631
+ if (subId !== calendarId) refuse(`The path names the calendar ${truncate(subId, 100)}.`);
1632
+ }
1633
+ if (collection === "freeBusy") {
1634
+ const items = request.json?.["items"];
1635
+ const onlyThis = Array.isArray(items) && items.length > 0 && items.every((item) => typeof item === "object" && item !== null && item.id === calendarId);
1636
+ if (!onlyThis) refuse("A free/busy query must name the connected calendar alone, in json (find_free_slots reads it).");
1637
+ }
1638
+ }
1639
+ var connector = defineConnector({
1640
+ vendor: "google-calendar",
1641
+ label: LABEL2,
1642
+ origins: [API_ORIGIN, TOKEN_ORIGIN],
1643
+ credentials: [KEY_CREDENTIAL, "calendarid", "timezone", "slotdurationminutes"],
1644
+ requiredCredentials: [[KEY_CREDENTIAL, "calendarid"]],
1645
+ credentialLabels: {
1646
+ serviceaccountjson: "Google Calendar service account key",
1647
+ calendarid: "Google Calendar calendar ID",
1648
+ timezone: "Google Calendar time zone",
1649
+ slotdurationminutes: "Google Calendar default slot length"
1650
+ },
1651
+ tools: [
1652
+ {
1653
+ name: "get_calendar",
1654
+ kind: "read",
1655
+ title: "Get the Google Calendar calendar",
1656
+ description: "Returns the connected calendar: its ID, name, description and time zone, with the connection's time zone and default slot length. A quick check that the key works and the calendar is shared with the service account.",
1657
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1658
+ async run(_args, h) {
1659
+ const { data } = await calendar(h, { path: calendarPath(h) });
1660
+ return compact({
1661
+ calendarId: calendarIdOf(h),
1662
+ summary: data?.summary,
1663
+ description: typeof data?.description === "string" ? truncate(data.description, 1e3) : void 0,
1664
+ timeZone: data?.timeZone,
1665
+ location: data?.location,
1666
+ connectionTimeZone: h.credentials["timezone"],
1667
+ slotMinutes: defaultSlotMinutes(h)
1668
+ });
1669
+ }
1670
+ },
1671
+ {
1672
+ name: "find_free_slots",
1673
+ kind: "read",
1674
+ title: "Find free Google Calendar slots",
1675
+ description: `Finds open appointment slots on the connected calendar: it reads the busy times (free/busy) between start and end and returns the slots of slot_minutes inside the opening hours that are free, in the calendar's time zone, plus the busy blocks. Opening hours default to Monday to Friday 09:00-18:00; pass hours for others. Past slots are left out. Up to ${MAX_RANGE_DAYS} days per call; pass nextCursor back as cursor for more slots.`,
1676
+ inputSchema: {
1677
+ type: "object",
1678
+ properties: {
1679
+ start: { type: "string", pattern: TIME_PATTERN, description: "Search from: a date (its midnight), a time, or an instant. Default: now." },
1680
+ end: { type: "string", pattern: TIME_PATTERN, description: "Search until (a date means the end of that day). Default: start plus days." },
1681
+ days: { type: "integer", minimum: 1, maximum: MAX_RANGE_DAYS, default: 7, description: "Days to search when end is not given (default 7)." },
1682
+ slot_minutes: { type: "integer", minimum: 5, maximum: 480, description: "Slot length in minutes. Default: the connection's slot length, else 30." },
1683
+ step_minutes: { type: "integer", minimum: 5, maximum: 480, description: "Minutes between slot starts, counted from the opening time. Default: the slot length." },
1684
+ buffer_minutes: { type: "integer", minimum: 0, maximum: 240, default: 0, description: "Free minutes to keep before and after each busy block (default 0)." },
1685
+ min_notice_minutes: { type: "integer", minimum: 0, maximum: 43200, default: 0, description: "Leave out slots starting sooner than this many minutes from now (default 0)." },
1686
+ hours: {
1687
+ type: "array",
1688
+ minItems: 1,
1689
+ maxItems: 14,
1690
+ items: {
1691
+ type: "object",
1692
+ properties: {
1693
+ days: { type: "array", items: { type: "string", enum: [...WEEKDAYS] }, minItems: 1, uniqueItems: true, description: "Weekdays: mon, tue, wed, thu, fri, sat, sun." },
1694
+ start: { type: "string", pattern: "^([01]\\d|2[0-3]):[0-5]\\d$", description: "Opening time, HH:MM." },
1695
+ end: { type: "string", pattern: "^(([01]\\d|2[0-3]):[0-5]\\d|24:00)$", description: "Closing time, HH:MM (24:00 for midnight)." }
1696
+ },
1697
+ required: ["days", "start", "end"],
1698
+ additionalProperties: false
1699
+ },
1700
+ description: 'Opening hours, e.g. [{"days": ["mon","tue","wed","thu","fri"], "start": "09:00", "end": "18:00"}, {"days": ["sat"], "start": "10:00", "end": "14:00"}].'
1701
+ },
1702
+ timezone: { type: "string", maxLength: 64, description: "An IANA time zone for the hours and the results. Default: the connection's, else the calendar's." },
1703
+ max_slots: { type: "integer", minimum: 1, maximum: 200, default: 50, description: "Slots to return, 1 to 200 (default 50)." },
1704
+ cursor: { type: "string", description: "nextCursor from the previous result." }
1705
+ },
1706
+ additionalProperties: false
1707
+ },
1708
+ async run(args, h) {
1709
+ const state = h.cursor(args.cursor);
1710
+ const zone = await zoneFor(h, args.timezone);
1711
+ const now = Date.now();
1712
+ let from;
1713
+ let to;
1714
+ if (typeof state?.["s"] === "number" && typeof state?.["e"] === "number") {
1715
+ from = state["s"];
1716
+ to = state["e"];
1717
+ } else {
1718
+ const start = args.start !== void 0 ? timeOf(args.start, "start") : void 0;
1719
+ from = start ? toInstant(start, zone) : now;
1720
+ if (args.end !== void 0) {
1721
+ const end = timeOf(args.end, "end");
1722
+ to = toInstant(end, zone) + (end.kind === "date" ? DAY_MS : 0);
1723
+ } else {
1724
+ to = from + args.days * DAY_MS;
1725
+ }
1726
+ }
1727
+ if (to <= from) throw new ToolFailure("end must be after start. Nothing was sent.");
1728
+ if (to - from > MAX_RANGE_DAYS * DAY_MS) throw new ToolFailure(`The search can cover at most ${MAX_RANGE_DAYS} days per call. Nothing was sent.`);
1729
+ const slotMinutes = args.slot_minutes ?? defaultSlotMinutes(h);
1730
+ const rules = args.hours ? args.hours.map((rule) => ({ days: rule.days.map((day) => WEEKDAYS.indexOf(day)), start: minutesOfDay(rule.start), end: minutesOfDay(rule.end) })) : DEFAULT_HOURS;
1731
+ for (const rule of rules) if (rule.end <= rule.start) throw new ToolFailure("Each opening hours entry must close after it opens. Nothing was sent.");
1732
+ const calendarId = calendarIdOf(h);
1733
+ const { data } = await calendar(h, {
1734
+ method: "POST",
1735
+ path: "/calendar/v3/freeBusy",
1736
+ json: { timeMin: formatUtc(from), timeMax: formatUtc(to), timeZone: zone, items: [{ id: calendarId }] },
1737
+ // A free/busy query reads and changes nothing.
1738
+ safe: true
1739
+ });
1740
+ const calendars = data?.calendars && typeof data.calendars === "object" ? data.calendars : {};
1741
+ const entry = calendars[calendarId] ?? Object.values(calendars)[0];
1742
+ const errors = Array.isArray(entry?.errors) ? entry.errors : [];
1743
+ if (!entry || errors.length) {
1744
+ const reason = typeof errors[0]?.reason === "string" ? ` (${truncate(errors[0].reason, 60)})` : "";
1745
+ throw new ToolFailure(
1746
+ `Google Calendar could not read the busy times of the calendar ${calendarId}${reason}: check the calendar ID and share the calendar with ${serviceAccountWords(h)}.`
1747
+ );
1748
+ }
1749
+ const busy = (Array.isArray(entry.busy) ? entry.busy : []).map((block) => [Date.parse(block?.start), Date.parse(block?.end)]).filter(([start, end]) => Number.isFinite(start) && Number.isFinite(end) && end > start);
1750
+ const found = findFreeSlots({
1751
+ from,
1752
+ to,
1753
+ earliest: now + args.min_notice_minutes * MINUTE_MS,
1754
+ busy,
1755
+ rules,
1756
+ zone,
1757
+ slotMs: slotMinutes * MINUTE_MS,
1758
+ stepMs: (args.step_minutes ?? slotMinutes) * MINUTE_MS,
1759
+ bufferMs: args.buffer_minutes * MINUTE_MS,
1760
+ max: args.max_slots
1761
+ });
1762
+ const clipped = busy.filter(([start, end]) => end > from && start < to).map(([start, end]) => ({ start: formatInZone(Math.max(start, from), zone), end: formatInZone(Math.min(end, to), zone) }));
1763
+ return compact({
1764
+ calendarId,
1765
+ timeZone: zone,
1766
+ slotMinutes,
1767
+ from: formatInZone(from, zone),
1768
+ to: formatInZone(to, zone),
1769
+ busy: clipped.slice(0, MAX_BUSY_RETURNED),
1770
+ busyCount: clipped.length > MAX_BUSY_RETURNED ? clipped.length : void 0,
1771
+ slots: found.slots.map(([start, end]) => ({ start: formatInZone(start, zone), end: formatInZone(end, zone) })),
1772
+ nextCursor: found.next !== void 0 ? h.makeCursor({ s: found.next, e: to }) : void 0
1773
+ });
1774
+ }
1775
+ },
1776
+ {
1777
+ name: "list_events",
1778
+ kind: "read",
1779
+ title: "List Google Calendar events",
1780
+ description: "Lists the events on the connected calendar from time_min (default now) on, in start order, with recurring events expanded: id, title, times, location, guests, status and link. Filter by text with query. Pass nextCursor back as cursor for more.",
1781
+ inputSchema: {
1782
+ type: "object",
1783
+ properties: {
1784
+ time_min: { type: "string", pattern: TIME_PATTERN, description: "Events ending after this time. Default: now." },
1785
+ time_max: { type: "string", pattern: TIME_PATTERN, description: "Events starting before this time." },
1786
+ query: { type: "string", maxLength: 500, description: "Free text to match in the title, description, location or guests." },
1787
+ updated_min: { type: "string", pattern: TIME_PATTERN, description: "Only events changed after this time (deleted ones are then included, status cancelled)." },
1788
+ timezone: { type: "string", maxLength: 64, description: "An IANA time zone for times without an offset. Default: the connection's, else the calendar's." },
1789
+ max_results: { type: "integer", minimum: 1, maximum: 250, default: 50, description: "Events per page, 1 to 250 (default 50)." },
1790
+ cursor: { type: "string", description: "nextCursor from the previous result." }
1791
+ },
1792
+ additionalProperties: false
1793
+ },
1794
+ async run(args, h) {
1795
+ const state = h.cursor(args.cursor);
1796
+ const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
1797
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
1798
+ const needsZone = [args.time_min, args.time_max, args.updated_min].some((text) => text !== void 0 && parseTime(text)?.kind !== "instant");
1799
+ const zone = needsZone ? await zoneFor(h, args.timezone) : "UTC";
1800
+ const instant = (text, field) => formatUtc(toInstant(timeOf(text, field), zone));
1801
+ const query = {
1802
+ singleEvents: true,
1803
+ orderBy: "startTime",
1804
+ timeMin: args.time_min !== void 0 ? instant(args.time_min, "time_min") : formatUtc(Date.now()),
1805
+ timeMax: args.time_max !== void 0 ? instant(args.time_max, "time_max") : void 0,
1806
+ updatedMin: args.updated_min !== void 0 ? instant(args.updated_min, "updated_min") : void 0,
1807
+ q: args.query,
1808
+ maxResults: args.max_results,
1809
+ pageToken
1810
+ };
1811
+ const { data } = await calendar(h, { path: calendarPath(h, "/events"), query });
1812
+ const events = Array.isArray(data?.items) ? data.items : [];
1813
+ return h.page({
1814
+ key: "events",
1815
+ items: events.map(trimEvent).slice(skip),
1816
+ extra: compact({ calendarId: calendarIdOf(h), timeZone: data?.timeZone }),
1817
+ resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index }),
1818
+ ...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0 }) } : {}
1819
+ });
1820
+ }
1821
+ },
1822
+ {
1823
+ name: "get_event",
1824
+ kind: "read",
1825
+ title: "Get a Google Calendar event",
1826
+ description: "Returns one event of the connected calendar by its id: title, times, description, location, guests and their answers, reminders, status and link. A deleted event comes back with status cancelled.",
1827
+ inputSchema: {
1828
+ type: "object",
1829
+ properties: { event_id: { type: "string", minLength: 1, maxLength: 1024, pattern: EVENT_ID_PATTERN, description: "The event id." } },
1830
+ required: ["event_id"],
1831
+ additionalProperties: false
1832
+ },
1833
+ async run(args, h) {
1834
+ const { data } = await calendar(h, { path: eventPath(h, args.event_id), errors: NO_EVENT });
1835
+ return trimEvent(data);
1836
+ }
1837
+ },
1838
+ {
1839
+ name: "create_event",
1840
+ kind: "create",
1841
+ check: "get_event",
1842
+ title: "Create a Google Calendar event",
1843
+ description: "Creates an event on the connected calendar, such as a booked appointment: title, start and end (or duration_minutes, by default the connection's slot length), description, location, reminders (default: the calendar's), repeat rules, color and private tags. Times without an offset are in the connection's time zone. Returns the event with its id and link.",
1844
+ inputSchema: {
1845
+ type: "object",
1846
+ properties: {
1847
+ ...EVENT_FIELDS,
1848
+ duration_minutes: { type: "integer", minimum: 5, maximum: 1440, description: "Length in minutes when end is not given. Default: the connection's slot length, else 30." }
1849
+ },
1850
+ required: ["summary", "start"],
1851
+ additionalProperties: false
1852
+ },
1853
+ async run(args, h) {
1854
+ const body = await eventBody(h, args, false);
1855
+ const id = newEventId();
1856
+ try {
1857
+ const { data } = await calendar(h, {
1858
+ method: "POST",
1859
+ path: calendarPath(h, "/events"),
1860
+ query: { sendUpdates: args.send_updates },
1861
+ json: { id, ...body },
1862
+ write: true
1863
+ });
1864
+ return trimEvent(data);
1865
+ } catch (error) {
1866
+ if (error instanceof OutcomeUnknown) throw new OutcomeUnknown(`${error.message} The new event's id is "${id}".`);
1867
+ throw error;
1868
+ }
1869
+ }
1870
+ },
1871
+ {
1872
+ name: "update_event",
1873
+ kind: "update",
1874
+ check: "get_event",
1875
+ title: "Update a Google Calendar event",
1876
+ description: "Changes an event of the connected calendar: only the fields given change (reminder_minutes and recurrence replace the whole list), and guests added in Google Calendar stay. status cancelled cancels it. Returns the updated event.",
1877
+ inputSchema: {
1878
+ type: "object",
1879
+ properties: {
1880
+ event_id: { type: "string", minLength: 1, maxLength: 1024, pattern: EVENT_ID_PATTERN, description: "The event id." },
1881
+ ...EVENT_FIELDS,
1882
+ duration_minutes: { type: "integer", minimum: 5, maximum: 1440, description: "With start: the new length in minutes, instead of end." },
1883
+ status: { type: "string", enum: ["confirmed", "tentative", "cancelled"], description: "The event status." }
1884
+ },
1885
+ required: ["event_id"],
1886
+ additionalProperties: false
1887
+ },
1888
+ async run(args, h) {
1889
+ const body = await eventBody(h, args, true);
1890
+ if (!Object.keys(body).length) throw new ToolFailure("Give at least one field to change. Nothing was changed.");
1891
+ const { data } = await calendar(h, {
1892
+ method: "PATCH",
1893
+ path: eventPath(h, args.event_id),
1894
+ query: { sendUpdates: args.send_updates },
1895
+ json: body,
1896
+ write: true,
1897
+ errors: NO_EVENT
1898
+ });
1899
+ return trimEvent(data);
1900
+ }
1901
+ },
1902
+ {
1903
+ name: "delete_event",
1904
+ kind: "delete",
1905
+ check: "get_event",
1906
+ title: "Delete a Google Calendar event",
1907
+ description: "Deletes an event from the connected calendar (for a repeating event, the whole series; to drop one occurrence, pass that occurrence's id from list_events). Deleting an event that is already deleted succeeds.",
1908
+ inputSchema: {
1909
+ type: "object",
1910
+ properties: {
1911
+ event_id: { type: "string", minLength: 1, maxLength: 1024, pattern: EVENT_ID_PATTERN, description: "The event id." },
1912
+ send_updates: EVENT_FIELDS["send_updates"]
1913
+ },
1914
+ required: ["event_id"],
1915
+ additionalProperties: false
1916
+ },
1917
+ async run(args, h) {
1918
+ try {
1919
+ await calendar(h, { method: "DELETE", path: eventPath(h, args.event_id), query: { sendUpdates: args.send_updates }, write: true, errors: NO_EVENT });
1920
+ } catch (error) {
1921
+ if (error instanceof ToolFailure && error.details.status === 410) return { deleted: true, eventId: args.event_id, note: "The event was already deleted." };
1922
+ throw error;
1923
+ }
1924
+ return { deleted: true, eventId: args.event_id };
1925
+ }
1926
+ },
1927
+ ...apiTools({
1928
+ label: LABEL2,
1929
+ description: "The Google Calendar API v3 at https://www.googleapis.com/calendar/v3, as the service account: paths start with /calendar/v3/, such as /calendar/v3/calendars/{calendarId}/events/{eventId}/instances, /calendar/v3/calendars/{calendarId}/acl or /calendar/v3/colors, and calendar paths must name the connected calendar (URL-encoded); other calendars are out of reach. Reference: https://developers.google.com/workspace/calendar/api/v3/reference.",
1930
+ basePath: "/calendar/v3/",
1931
+ guard: calendarGuard,
1932
+ send: (request, h) => calendar(h, request)
1933
+ })
1934
+ ]
1935
+ });
1936
+ module.exports = connector;