@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,1116 @@
1
+ /* calendarific connector module (MIT License). Built from src/vendors/calendarific; 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/text.ts
21
+ var encoder = new TextEncoder();
22
+ var decoder = new TextDecoder();
23
+ function utf8Bytes(text2) {
24
+ return encoder.encode(text2);
25
+ }
26
+ function utf8Length(text2) {
27
+ return encoder.encode(text2).length;
28
+ }
29
+ function utf8Decode(bytes) {
30
+ return decoder.decode(bytes);
31
+ }
32
+ function base64Encode(bytes) {
33
+ let binary = "";
34
+ for (let i = 0; i < bytes.length; i += 32768) {
35
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
36
+ }
37
+ return btoa(binary);
38
+ }
39
+ function base64UrlEncode(bytes) {
40
+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
41
+ }
42
+ function base64UrlDecode(text2) {
43
+ if (!/^[A-Za-z0-9_-]*$/.test(text2)) throw new Error("not base64url");
44
+ const padded = text2.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text2.length + 3) % 4);
45
+ const binary = atob(padded);
46
+ const bytes = new Uint8Array(binary.length);
47
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
48
+ return bytes;
49
+ }
50
+ function truncate(text2, max) {
51
+ if (text2.length <= max) return text2;
52
+ const points = Array.from(text2);
53
+ if (points.length <= max) return text2;
54
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
55
+ }
56
+ function cleanVendorText(text2, max = 300) {
57
+ if (typeof text2 !== "string") return void 0;
58
+ if (/^\s*</.test(text2)) return void 0;
59
+ const line = text2.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
60
+ return line ? truncate(line, max) : void 0;
61
+ }
62
+ function formatNumber(value) {
63
+ return value.toLocaleString("en-US");
64
+ }
65
+
66
+ // src/core/output.ts
67
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
68
+ function jsonSize(value) {
69
+ return utf8Length(JSON.stringify(value) ?? "");
70
+ }
71
+ function cutStrings(value, max) {
72
+ if (typeof value === "string") return truncate(value, max);
73
+ if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
74
+ if (typeof value === "object" && value !== null) {
75
+ const out = {};
76
+ for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
77
+ return out;
78
+ }
79
+ return value;
80
+ }
81
+ function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
82
+ if (jsonSize(value) <= limit) return { value, truncated: false };
83
+ for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
84
+ const cut = cutStrings(value, max);
85
+ if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
86
+ }
87
+ return void 0;
88
+ }
89
+ function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
90
+ const build = (count) => {
91
+ const cut = count < input.items.length;
92
+ const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
93
+ const next = cut ? input.resumeAt(count) : input.nextPage;
94
+ if (next) result2["nextCursor"] = next;
95
+ if (cut) result2["truncated"] = true;
96
+ return result2;
97
+ };
98
+ const all = build(input.items.length);
99
+ if (jsonSize(all) <= limit) return all;
100
+ let low = 1;
101
+ let high = input.items.length - 1;
102
+ while (low < high) {
103
+ const middle = Math.ceil((low + high) / 2);
104
+ if (jsonSize(build(middle)) <= limit) low = middle;
105
+ else high = middle - 1;
106
+ }
107
+ const best = build(low);
108
+ if (jsonSize(best) <= limit) return best;
109
+ const shrunk = shrinkToFit(best, limit);
110
+ if (shrunk) return { ...shrunk.value, truncated: true };
111
+ throw new ToolFailure("The result is too large to return, even one item at a time.");
112
+ }
113
+ function encodeCursor(tool, state) {
114
+ return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
115
+ }
116
+ function decodeCursor(tool, cursor) {
117
+ if (cursor === void 0 || cursor === "") return null;
118
+ try {
119
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
120
+ if (typeof state === "object" && state !== null && state.t === tool) {
121
+ return state;
122
+ }
123
+ } catch {
124
+ }
125
+ throw new ToolFailure(
126
+ "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."
127
+ );
128
+ }
129
+
130
+ // src/core/credentials.ts
131
+ function requiredAlternatives(module2) {
132
+ return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
133
+ }
134
+ function unmetAlternatives(alternatives, has) {
135
+ const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
136
+ if (lacking.some((list) => list.length === 0)) return [];
137
+ return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
138
+ }
139
+ function andList(items) {
140
+ if (items.length <= 2) return items.join(" and ");
141
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
142
+ }
143
+ function orList(items) {
144
+ if (items.length <= 1) return items.join("");
145
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
146
+ }
147
+
148
+ // src/core/files.ts
149
+ var ATTACHMENT_URI = "attachment:///";
150
+ var MAX_NAME = 200;
151
+ function fileLimitOf(ctx) {
152
+ const maxBytes = ctx.files?.maxBytes;
153
+ return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
154
+ }
155
+ function fileName(name2) {
156
+ const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
157
+ const points = Array.from(clean);
158
+ if (points.length <= MAX_NAME) return clean || "file";
159
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
160
+ return points.slice(0, MAX_NAME - extension.length).join("") + extension;
161
+ }
162
+ function fileType(mimeType) {
163
+ const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
164
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
165
+ }
166
+ function resourceBlock(file) {
167
+ return {
168
+ type: "resource",
169
+ resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
170
+ };
171
+ }
172
+
173
+ // src/core/http.ts
174
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
175
+ var USER_AGENT = "agent-connectors";
176
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
177
+ function errorCode(error) {
178
+ const code = error?.code;
179
+ return typeof code === "string" ? code : void 0;
180
+ }
181
+ function describe(error) {
182
+ const name2 = error?.name;
183
+ const code = errorCode(error);
184
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
185
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
186
+ if (code === "TOO_LARGE") return "the reply was too large";
187
+ return cleanVendorText(error?.message, 200) ?? "a network error";
188
+ }
189
+ function retryAfterSeconds(headers, now = Date.now()) {
190
+ const retryAfter = headers.get("retry-after");
191
+ if (retryAfter) {
192
+ const seconds = Number(retryAfter);
193
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
194
+ const date = Date.parse(retryAfter);
195
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
196
+ }
197
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
198
+ if (reset) {
199
+ const value = Number(reset);
200
+ if (Number.isFinite(value) && value >= 0) {
201
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
202
+ }
203
+ }
204
+ return void 0;
205
+ }
206
+ function vendorCode(data) {
207
+ if (typeof data !== "object" || data === null) return void 0;
208
+ for (const key of ["error", "code"]) {
209
+ const value = data[key];
210
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
211
+ }
212
+ return void 0;
213
+ }
214
+ function vendorMessage(data) {
215
+ if (typeof data === "string") return cleanVendorText(data);
216
+ if (typeof data !== "object" || data === null) return void 0;
217
+ const record = data;
218
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
219
+ const value = record[key];
220
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
221
+ const nested = value?.message;
222
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
223
+ }
224
+ if (Array.isArray(record["errors"])) {
225
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
226
+ if (messages.length) return cleanVendorText(messages.join("; "));
227
+ }
228
+ return void 0;
229
+ }
230
+ var TooLarge = class extends Error {
231
+ constructor(limit) {
232
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
233
+ this.limit = limit;
234
+ }
235
+ limit;
236
+ };
237
+ async function readCapped(response, maxBytes) {
238
+ const declared = Number(response.headers.get("content-length"));
239
+ if (Number.isFinite(declared) && declared > maxBytes) {
240
+ await response.body?.cancel().catch(() => {
241
+ });
242
+ throw new TooLarge(maxBytes);
243
+ }
244
+ if (!response.body) return new Uint8Array(0);
245
+ const reader = response.body.getReader();
246
+ const chunks = [];
247
+ let total = 0;
248
+ for (; ; ) {
249
+ const { done, value } = await reader.read();
250
+ if (done) break;
251
+ total += value.byteLength;
252
+ if (total > maxBytes) {
253
+ await reader.cancel().catch(() => {
254
+ });
255
+ throw new TooLarge(maxBytes);
256
+ }
257
+ chunks.push(value);
258
+ }
259
+ const bytes = new Uint8Array(total);
260
+ let offset = 0;
261
+ for (const chunk of chunks) {
262
+ bytes.set(chunk, offset);
263
+ offset += chunk.byteLength;
264
+ }
265
+ return bytes;
266
+ }
267
+ function parseBody(bytes, contentType) {
268
+ if (bytes.length === 0) return null;
269
+ const text2 = utf8Decode(bytes);
270
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text2)) {
271
+ try {
272
+ return JSON.parse(text2);
273
+ } catch {
274
+ }
275
+ }
276
+ return text2;
277
+ }
278
+ function createHttp(env) {
279
+ const { label, ctx } = env;
280
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
281
+ 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.`;
282
+ function failureFor(status, headers, data, request) {
283
+ const message = vendorMessage(data);
284
+ const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
285
+ const retryAfter = retryAfterSeconds(headers);
286
+ const code = vendorCode(data);
287
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
288
+ const custom = request.errors?.[status];
289
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
290
+ if (status >= 500) {
291
+ if (request.write) {
292
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
293
+ }
294
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
295
+ }
296
+ if (status === 429) {
297
+ return new ToolFailure(
298
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
299
+ { status, ...extra }
300
+ );
301
+ }
302
+ if (status === 401) {
303
+ return new ToolFailure(
304
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
305
+ { status, ...extra }
306
+ );
307
+ }
308
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
309
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
310
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
311
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
312
+ }
313
+ async function api(request) {
314
+ const method = request.method ?? "GET";
315
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
316
+ throw new Error(`read-only tool sent ${method}`);
317
+ }
318
+ const origin = request.origin ?? env.origins[0];
319
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
320
+ const url = new URL(request.path, origin);
321
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
322
+ for (const [key, value] of Object.entries(request.query ?? {})) {
323
+ if (value === void 0 || value === null) continue;
324
+ if (Array.isArray(value)) {
325
+ url.searchParams.delete(key);
326
+ for (const item of value) url.searchParams.append(key, String(item));
327
+ } else {
328
+ url.searchParams.set(key, String(value));
329
+ }
330
+ }
331
+ const headers = {
332
+ accept: "application/json",
333
+ "user-agent": USER_AGENT,
334
+ ...request.auth === false ? {} : env.authHeaders(),
335
+ ...request.headers
336
+ };
337
+ let body;
338
+ if (request.json !== void 0) {
339
+ body = JSON.stringify(request.json);
340
+ headers["content-type"] = "application/json";
341
+ } else if (request.body) {
342
+ body = request.body;
343
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
344
+ }
345
+ const started = Date.now();
346
+ if (request.write) env.onWriteSent();
347
+ let response;
348
+ try {
349
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
350
+ } catch (error) {
351
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
352
+ if (errorCode(error) === "URL_REFUSED") {
353
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
354
+ }
355
+ if (request.write) {
356
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
357
+ }
358
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
359
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
360
+ }
361
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
362
+ let bytes;
363
+ try {
364
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
365
+ } catch (error) {
366
+ if (request.write && (response.ok || response.status >= 500)) {
367
+ 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.`);
368
+ }
369
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
370
+ }
371
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
372
+ if (response.ok) return { status: response.status, headers: response.headers, data };
373
+ throw failureFor(response.status, response.headers, data, request);
374
+ }
375
+ async function media(rawUrl, options) {
376
+ const { what } = options;
377
+ let url;
378
+ try {
379
+ url = new URL(rawUrl);
380
+ } catch {
381
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
382
+ }
383
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
384
+ const started = Date.now();
385
+ let response;
386
+ try {
387
+ response = await ctx.fetch(url.toString(), {
388
+ method: "GET",
389
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
390
+ ...ctx.signal ? { signal: ctx.signal } : {}
391
+ });
392
+ } catch (error) {
393
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
394
+ if (errorCode(error) === "URL_REFUSED") {
395
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
396
+ }
397
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
398
+ }
399
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
400
+ if (!response.ok) {
401
+ await response.body?.cancel().catch(() => {
402
+ });
403
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
404
+ }
405
+ try {
406
+ const bytes = await readCapped(response, options.maxBytes);
407
+ return { bytes, contentType: response.headers.get("content-type") };
408
+ } catch (error) {
409
+ if (error instanceof TooLarge) {
410
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
411
+ }
412
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
413
+ }
414
+ }
415
+ return { api, media };
416
+ }
417
+
418
+ // src/core/origins.ts
419
+ function parseSiteUrl(value) {
420
+ const text2 = typeof value === "string" ? value.trim() : "";
421
+ if (!text2) return { ok: false, problem: "is empty" };
422
+ let url;
423
+ try {
424
+ url = new URL(text2.includes("://") ? text2 : `https://${text2}`);
425
+ } catch {
426
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
427
+ }
428
+ if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
429
+ if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
430
+ if (!url.hostname) return { ok: false, problem: "has no host name" };
431
+ return { ok: true, url, origin: url.origin };
432
+ }
433
+
434
+ // src/core/schema.ts
435
+ var patterns = /* @__PURE__ */ new Map();
436
+ function patternOf(source) {
437
+ let compiled = patterns.get(source);
438
+ if (!compiled) {
439
+ compiled = new RegExp(source, "u");
440
+ patterns.set(source, compiled);
441
+ }
442
+ return compiled;
443
+ }
444
+ function isPlainObject(value) {
445
+ return typeof value === "object" && value !== null && !Array.isArray(value);
446
+ }
447
+ function isHttpUrl(value) {
448
+ try {
449
+ const url = new URL(value);
450
+ return url.protocol === "https:" || url.protocol === "http:";
451
+ } catch {
452
+ return false;
453
+ }
454
+ }
455
+ function name(path) {
456
+ return `\`${path}\``;
457
+ }
458
+ function child(path, key) {
459
+ return path ? `${path}.${key}` : key;
460
+ }
461
+ function checkValue(schema, value, path, issues) {
462
+ switch (schema.type) {
463
+ case "object":
464
+ checkObject(schema, value, path, issues);
465
+ return;
466
+ case "array": {
467
+ if (!Array.isArray(value)) {
468
+ issues.push(`${name(path)} must be an array`);
469
+ return;
470
+ }
471
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
472
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
473
+ }
474
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
475
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
476
+ }
477
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
478
+ issues.push(`${name(path)} must not repeat an item`);
479
+ }
480
+ if (schema.items) {
481
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
482
+ }
483
+ break;
484
+ }
485
+ case "string": {
486
+ if (typeof value !== "string") {
487
+ issues.push(`${name(path)} must be a string`);
488
+ return;
489
+ }
490
+ const length = Array.from(value).length;
491
+ if (schema.minLength !== void 0 && length < schema.minLength) {
492
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
493
+ }
494
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
495
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
496
+ }
497
+ if (schema.format === "uri" && !isHttpUrl(value)) {
498
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
499
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
500
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
501
+ }
502
+ break;
503
+ }
504
+ case "integer":
505
+ case "number": {
506
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
507
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
508
+ return;
509
+ }
510
+ if (schema.minimum !== void 0 && value < schema.minimum) {
511
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
512
+ }
513
+ if (schema.maximum !== void 0 && value > schema.maximum) {
514
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
515
+ }
516
+ break;
517
+ }
518
+ case "boolean":
519
+ if (typeof value !== "boolean") {
520
+ issues.push(`${name(path)} must be true or false`);
521
+ return;
522
+ }
523
+ break;
524
+ default:
525
+ break;
526
+ }
527
+ if (schema.enum && !schema.enum.includes(value)) {
528
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
529
+ }
530
+ }
531
+ function checkObject(schema, value, path, issues) {
532
+ if (!isPlainObject(value)) {
533
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
534
+ return;
535
+ }
536
+ const properties = schema.properties ?? {};
537
+ for (const key of schema.required ?? []) {
538
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
539
+ }
540
+ const unknown = [];
541
+ for (const [key, item] of Object.entries(value)) {
542
+ const property = properties[key];
543
+ if (!property) {
544
+ if (schema.additionalProperties === false) unknown.push(key);
545
+ continue;
546
+ }
547
+ if (item === void 0 || item === null) continue;
548
+ checkValue(property, item, child(path, key), issues);
549
+ }
550
+ if (unknown.length) {
551
+ const known = Object.keys(properties);
552
+ 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(", ")})` : ""));
553
+ }
554
+ }
555
+ function copyDefault(value) {
556
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
557
+ }
558
+ function validateArguments(schema, args) {
559
+ const input = args === void 0 || args === null ? {} : args;
560
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
561
+ const value = { ...input };
562
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
563
+ const issues = [];
564
+ checkObject(schema, value, "", issues);
565
+ if (issues.length) return { ok: false, issues };
566
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
567
+ if (value[key] === null) delete value[key];
568
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
569
+ }
570
+ return { ok: true, value };
571
+ }
572
+
573
+ // src/core/upload-hosts.ts
574
+ var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
575
+ function uploadHostProblem(entry) {
576
+ if (typeof entry !== "string") return "must be a host name";
577
+ const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
578
+ const labels = name2.split(".");
579
+ if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
580
+ 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";
581
+ }
582
+ if (labels.length < 2) return "needs at least two labels, like example.com";
583
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
584
+ return void 0;
585
+ }
586
+
587
+ // src/core/connector.ts
588
+ var ANNOTATIONS = {
589
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
590
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
591
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
592
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
593
+ write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
594
+ };
595
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
596
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
597
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
598
+ var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
599
+ var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
600
+ var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
601
+ var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
602
+ function deepFreeze(value) {
603
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
604
+ Object.freeze(value);
605
+ for (const item of Object.values(value)) deepFreeze(item);
606
+ }
607
+ return value;
608
+ }
609
+ function assertDefinition(def) {
610
+ const problem = (message) => {
611
+ throw new Error(`connector "${def.vendor}": ${message}`);
612
+ };
613
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
614
+ if (!def.label?.trim()) problem("label is required");
615
+ const originFields = def.originFields ?? [];
616
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
617
+ for (const origin of def.origins) {
618
+ let url;
619
+ try {
620
+ url = new URL(origin);
621
+ } catch {
622
+ }
623
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
624
+ }
625
+ for (const name2 of def.credentials) {
626
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
627
+ }
628
+ for (const [index, name2] of originFields.entries()) {
629
+ if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
630
+ if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
631
+ }
632
+ const names = /* @__PURE__ */ new Set();
633
+ for (const tool of def.tools) {
634
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
635
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
636
+ names.add(tool.name);
637
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
638
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
639
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
640
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
641
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
642
+ }
643
+ }
644
+ for (const tool of def.tools) {
645
+ if (tool.kind === "read") continue;
646
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
647
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
648
+ }
649
+ assertUploadHosts(def, problem);
650
+ assertRequiredCredentials(def, problem);
651
+ assertAccountPickers(def, problem);
652
+ }
653
+ function assertUploadHosts(def, problem) {
654
+ const hosts = def.uploadHosts;
655
+ if (hosts === void 0) return;
656
+ if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
657
+ hosts.forEach((entry, index) => {
658
+ const wrong = uploadHostProblem(entry);
659
+ if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
660
+ if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
661
+ });
662
+ }
663
+ function assertRequiredCredentials(def, problem) {
664
+ const required = def.requiredCredentials;
665
+ if (required === void 0) return;
666
+ if (!Array.isArray(required) || !required.length) {
667
+ problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
668
+ }
669
+ required.forEach((list, index) => {
670
+ const which = `requiredCredentials[${index}]`;
671
+ if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
672
+ list.forEach((name2, position) => {
673
+ if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
674
+ if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
675
+ });
676
+ });
677
+ const lists = required;
678
+ lists.forEach((list, index) => {
679
+ const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
680
+ if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
681
+ if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
682
+ problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
683
+ }
684
+ });
685
+ }
686
+ function isDotPath(value) {
687
+ return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
688
+ }
689
+ function assertAccountPickers(def, problem) {
690
+ const pickers = def.accountPickers;
691
+ if (pickers === void 0) return;
692
+ if (!Array.isArray(pickers)) problem("accountPickers must be a list");
693
+ const keys = /* @__PURE__ */ new Set();
694
+ for (const item of pickers) {
695
+ if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
696
+ const picker = item;
697
+ const key = picker["key"];
698
+ 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}$`);
699
+ if (keys.has(key)) problem(`account picker ${key} is defined twice`);
700
+ keys.add(key);
701
+ const fail = (message) => problem(`account picker ${key}: ${message}`);
702
+ const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
703
+ if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
704
+ const { label, description, multiple, legacyField } = picker;
705
+ if (typeof label !== "string" || !label.trim()) fail("label is required");
706
+ if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
707
+ fail("description, when given, must be a text of 1 to 1024 characters");
708
+ }
709
+ if (typeof multiple !== "boolean") fail("multiple must be true or false");
710
+ const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
711
+ if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
712
+ if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
713
+ for (const field of ["idField", "nameField"]) {
714
+ if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
715
+ }
716
+ if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
717
+ fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
718
+ }
719
+ }
720
+ }
721
+ function copyPicker(picker) {
722
+ return {
723
+ key: picker.key,
724
+ label: picker.label,
725
+ ...picker.description !== void 0 ? { description: picker.description } : {},
726
+ multiple: picker.multiple,
727
+ tool: picker.tool,
728
+ idField: picker.idField,
729
+ nameField: picker.nameField,
730
+ ...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
731
+ };
732
+ }
733
+ function result(payload, isError, files = []) {
734
+ return {
735
+ content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
736
+ ...isError ? { isError: true } : {}
737
+ };
738
+ }
739
+ function failure(message, details = {}) {
740
+ return result({ error: message, ...details }, true);
741
+ }
742
+ function trimmed(values) {
743
+ const out = {};
744
+ if (typeof values !== "object" || values === null) return out;
745
+ for (const [key, value] of Object.entries(values)) {
746
+ if (value === void 0 || value === null) continue;
747
+ const text2 = String(value).trim();
748
+ if (text2) out[key] = text2;
749
+ }
750
+ return out;
751
+ }
752
+ function defineConnector(def) {
753
+ assertDefinition(def);
754
+ const { label } = def;
755
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
756
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
757
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
758
+ const required = requiredAlternatives(def);
759
+ const notConnected = (unmet) => {
760
+ const [first] = unmet;
761
+ if (unmet.length === 1 && first) {
762
+ return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
763
+ }
764
+ return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
765
+ };
766
+ const descriptors = def.tools.map((tool) => ({
767
+ name: tool.name,
768
+ title: tool.title,
769
+ description: tool.description,
770
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
771
+ annotations: { ...ANNOTATIONS[tool.kind] }
772
+ }));
773
+ async function call(toolName, args, ctx) {
774
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
775
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
776
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
777
+ const log = (text2) => {
778
+ try {
779
+ ctx.log?.(text2);
780
+ } catch {
781
+ }
782
+ };
783
+ const given = trimmed(ctx.credentials);
784
+ const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
785
+ const has = (name2) => Boolean(credentials[name2]);
786
+ const unmet = unmetAlternatives(required, has);
787
+ if (unmet.length) return failure(notConnected(unmet));
788
+ const complete = required.filter((list) => list.every(has));
789
+ const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
790
+ const fieldOrigins = /* @__PURE__ */ new Map();
791
+ for (const name2 of def.originFields ?? []) {
792
+ if (!given[name2] && !inUse.includes(name2)) continue;
793
+ const site = parseSiteUrl(given[name2] ?? "");
794
+ if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
795
+ fieldOrigins.set(name2, site.origin);
796
+ }
797
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
798
+ const parsed = validateArguments(tool.inputSchema, args);
799
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
800
+ const frozenCredentials = Object.freeze({ ...credentials });
801
+ let writeSent = false;
802
+ const fileLimit = fileLimitOf(ctx);
803
+ const files = [];
804
+ let fileBytes = 0;
805
+ const http = createHttp({
806
+ vendor: def.vendor,
807
+ label,
808
+ tool: tool.name,
809
+ readOnly: tool.kind === "read",
810
+ origins,
811
+ // A 401 names the credentials in use (for a module that needs none, the ones given).
812
+ credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
813
+ ctx,
814
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
815
+ log,
816
+ onWriteSent: () => {
817
+ writeSent = true;
818
+ }
819
+ });
820
+ const helpers = {
821
+ tool: tool.name,
822
+ credentials: frozenCredentials,
823
+ ctx,
824
+ origins: Object.freeze([...origins]),
825
+ originOf: (credential) => {
826
+ const origin = fieldOrigins.get(credential);
827
+ if (!origin) throw new Error(`${credential} gives no origin in this call`);
828
+ return origin;
829
+ },
830
+ api: http.api,
831
+ media: http.media,
832
+ page: (input) => fitPage(input),
833
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
834
+ makeCursor: (state) => encodeCursor(tool.name, state),
835
+ fileLimit: () => fileLimit,
836
+ file: ({ name: name2, mimeType, bytes }) => {
837
+ if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
838
+ const total = fileBytes + bytes.byteLength;
839
+ if (total > fileLimit) {
840
+ 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.`);
841
+ }
842
+ fileBytes = total;
843
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
844
+ files.push({ ...info, bytes });
845
+ return { ...info };
846
+ },
847
+ log
848
+ };
849
+ try {
850
+ const data = await tool.run(parsed.value, helpers);
851
+ const fitted = shrinkToFit(data ?? {});
852
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
853
+ const payload = fitted.value;
854
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
855
+ } catch (error) {
856
+ if (error instanceof OutcomeUnknown) {
857
+ return result({
858
+ outcome: "unknown",
859
+ check: tool.check,
860
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
861
+ }, true);
862
+ }
863
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
864
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
865
+ if (writeSent) {
866
+ return result({
867
+ outcome: "unknown",
868
+ check: tool.check,
869
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
870
+ }, true);
871
+ }
872
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
873
+ }
874
+ }
875
+ return deepFreeze({
876
+ vendor: def.vendor,
877
+ origins: [...def.origins],
878
+ originFields: [...def.originFields ?? []],
879
+ uploadHosts: [...def.uploadHosts ?? []],
880
+ credentials: [...def.credentials],
881
+ requiredCredentials: required.map((list) => [...list]),
882
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
883
+ tools: descriptors,
884
+ call
885
+ });
886
+ }
887
+
888
+ // src/core/jwt.ts
889
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
890
+
891
+ // src/vendors/calendarific/index.ts
892
+ var ORIGIN = "https://calendarific.com";
893
+ var DAY_MS = 864e5;
894
+ var ERRORS = {
895
+ 401: "Calendarific rejected the API key: check it on your Calendarific account dashboard",
896
+ 403: "The Calendarific subscription of this API key has expired: renew it on calendarific.com",
897
+ 503: "Calendarific is down for planned maintenance: try again later"
898
+ };
899
+ var TYPES = ["national", "local", "religious", "observance"];
900
+ var COUNTRY = { type: "string", pattern: "^[A-Za-z]{2}$", description: 'The ISO 3166-1 alpha-2 country code, e.g. "US", "TR", "DE" or "JP" (list_countries has them all).' };
901
+ var LOCATION = {
902
+ type: "string",
903
+ pattern: "^[A-Za-z]{2}-[A-Za-z0-9]{1,3}$",
904
+ description: 'Only holidays of one state or region, as its ISO 3166-2 code, e.g. "us-ny" for New York.'
905
+ };
906
+ var HOLIDAY_TYPES = {
907
+ type: "array",
908
+ items: { type: "string", enum: [...TYPES] },
909
+ minItems: 1,
910
+ maxItems: 4,
911
+ uniqueItems: true,
912
+ description: "Only these kinds: national (public and bank holidays), local (regional), religious, observance (awareness days, seasons, cultural days). Default: all of them."
913
+ };
914
+ var LANGUAGE = {
915
+ type: "string",
916
+ pattern: "^[A-Za-z]{2}$",
917
+ description: 'The ISO 639-1 language of names and descriptions, e.g. "fr" (list_languages). Paid plans only: the free plan answers in English.'
918
+ };
919
+ var CURSOR = { type: "string", description: "nextCursor from the previous result." };
920
+ function apiKey(h) {
921
+ return h.credentials["apikey"];
922
+ }
923
+ async function calendarificGet(h, endpoint, query) {
924
+ let data;
925
+ try {
926
+ ({ data } = await h.api({ origin: ORIGIN, path: `/api/v2/${endpoint}`, query: { ...query, api_key: apiKey(h) }, errors: ERRORS }));
927
+ } catch (error) {
928
+ if (error instanceof ToolFailure && error.details.status === 429) {
929
+ throw new ToolFailure(
930
+ "The Calendarific request limit of this API key is used up for the month (HTTP 429). It resets when the plan's month starts again; a larger plan raises it. Every request counts, errors included.",
931
+ error.details
932
+ );
933
+ }
934
+ throw error;
935
+ }
936
+ const meta = data?.["meta"];
937
+ if (typeof meta?.["code"] === "number" && meta["code"] !== 200) {
938
+ const detail = typeof meta["error_detail"] === "string" ? truncate(meta["error_detail"].replace(/\s+/g, " ").trim(), 300) : void 0;
939
+ throw new ToolFailure(`Calendarific refused the request (code ${meta["code"]})${detail ? `: ${detail}` : "."}`, { status: meta["code"] });
940
+ }
941
+ const response = data?.["response"];
942
+ return typeof response === "object" && response !== null && !Array.isArray(response) ? response : {};
943
+ }
944
+ function compact(value) {
945
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
946
+ }
947
+ function text(value, max) {
948
+ return typeof value === "string" && value.trim() ? truncate(value.trim(), max) : void 0;
949
+ }
950
+ function regions(value) {
951
+ if (typeof value === "string") return text(value, 300);
952
+ if (!Array.isArray(value)) return void 0;
953
+ const list = value.map((state) => text(state?.["iso"], 20) ?? text(state?.["name"], 80)).filter((item) => item !== void 0);
954
+ return list.length ? list.length > 80 ? [...list.slice(0, 80), `and ${list.length - 80} more`] : list : void 0;
955
+ }
956
+ function trimHoliday(holiday) {
957
+ const types = Array.isArray(holiday["type"]) ? holiday["type"].map((type) => text(type, 60)).filter(Boolean) : [];
958
+ return compact({
959
+ name: text(holiday["name"], 200),
960
+ date: text(holiday["date"]?.["iso"], 40),
961
+ description: text(holiday["description"], 400),
962
+ types: types.length ? types : void 0,
963
+ primaryType: text(holiday["primary_type"], 80),
964
+ locations: text(holiday["locations"], 300),
965
+ states: regions(holiday["states"]),
966
+ url: text(holiday["canonical_url"], 300),
967
+ id: holiday["id"] ?? void 0,
968
+ uuid: text(holiday["uuid"], 80)
969
+ });
970
+ }
971
+ function holidaysOf(response) {
972
+ return Array.isArray(response["holidays"]) ? response["holidays"].filter((item) => typeof item === "object" && item !== null) : [];
973
+ }
974
+ function filterQuery(args) {
975
+ return {
976
+ country: args.country.toUpperCase(),
977
+ location: args.location?.toLowerCase(),
978
+ type: args.types?.join(","),
979
+ language: args.language?.toLowerCase()
980
+ };
981
+ }
982
+ function skipOf(h, cursor) {
983
+ const state = h.cursor(cursor);
984
+ return typeof state?.["o"] === "number" ? state["o"] : 0;
985
+ }
986
+ var listHolidays = {
987
+ name: "list_holidays",
988
+ kind: "read",
989
+ title: "List the holidays of a country from Calendarific",
990
+ description: "The holidays and observances of one country in a year, a month or on a day: name, date (YYYY-MM-DD, with a time for astronomical events), description, kinds (national, religious, observance, local), where it applies (all of the country, or its states as ISO 3166-2 codes) and its Calendarific page. Filter by kind, region and language. One request of the plan's monthly limit; a long list comes in parts, and nextCursor asks again (another request).",
991
+ inputSchema: {
992
+ type: "object",
993
+ properties: {
994
+ country: COUNTRY,
995
+ year: { type: "integer", minimum: 1900, maximum: 2100, description: "The year, e.g. 2026." },
996
+ month: { type: "integer", minimum: 1, maximum: 12, description: "Only this month, 1 to 12." },
997
+ day: { type: "integer", minimum: 1, maximum: 31, description: "Only this day of the month, 1 to 31 (with month: one date)." },
998
+ location: LOCATION,
999
+ types: HOLIDAY_TYPES,
1000
+ language: LANGUAGE,
1001
+ cursor: CURSOR
1002
+ },
1003
+ required: ["country", "year"],
1004
+ additionalProperties: false
1005
+ },
1006
+ async run(args, h) {
1007
+ const skip = skipOf(h, args.cursor);
1008
+ const response = await calendarificGet(h, "holidays", { ...filterQuery(args), year: args.year, month: args.month, day: args.day });
1009
+ const holidays = holidaysOf(response).map(trimHoliday);
1010
+ return h.page({
1011
+ key: "holidays",
1012
+ items: holidays.slice(skip),
1013
+ extra: compact({ country: args.country.toUpperCase(), year: args.year, month: args.month, day: args.day, count: holidays.length }),
1014
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
1015
+ });
1016
+ }
1017
+ };
1018
+ var isoDay = (ms) => new Date(ms).toISOString().slice(0, 10);
1019
+ var listUpcomingHolidays = {
1020
+ name: "list_upcoming_holidays",
1021
+ kind: "read",
1022
+ title: "List the coming holidays of a country from Calendarific",
1023
+ description: "The holidays and observances of one country in a window of days, by date: from a day (today in UTC by default) for up to 366 days, with the same fields and filters as list_holidays. Made for planning ahead, e.g. the next 21 days. It asks for whole months, or whole years when the window spans more than a month of a year: one or two requests of the plan's monthly limit, twice that when nextCursor asks again.",
1024
+ inputSchema: {
1025
+ type: "object",
1026
+ properties: {
1027
+ country: COUNTRY,
1028
+ from: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "The first day, YYYY-MM-DD (default today, UTC)." },
1029
+ days: { type: "integer", minimum: 1, maximum: 366, default: 30, description: "How many days, 1 to 366 (default 30), the first day included." },
1030
+ location: LOCATION,
1031
+ types: HOLIDAY_TYPES,
1032
+ language: LANGUAGE,
1033
+ cursor: CURSOR
1034
+ },
1035
+ required: ["country"],
1036
+ additionalProperties: false
1037
+ },
1038
+ async run(args, h) {
1039
+ const start = args.from ? Date.parse(`${args.from}T00:00:00Z`) : Math.floor(Date.now() / DAY_MS) * DAY_MS;
1040
+ if (Number.isNaN(start) || args.from !== void 0 && isoDay(start) !== args.from) {
1041
+ throw new ToolFailure(`from must be a real date as YYYY-MM-DD, such as 2026-12-01. Nothing was sent to Calendarific.`);
1042
+ }
1043
+ const end = start + (args.days - 1) * DAY_MS;
1044
+ const [first, last] = [isoDay(start), isoDay(end)];
1045
+ const months = /* @__PURE__ */ new Map();
1046
+ for (let day = start; day <= end; day += DAY_MS) {
1047
+ const date = new Date(day);
1048
+ const year = date.getUTCFullYear();
1049
+ months.set(year, (months.get(year) ?? /* @__PURE__ */ new Set()).add(date.getUTCMonth() + 1));
1050
+ }
1051
+ const holidays = [];
1052
+ for (const [year, inYear] of months) {
1053
+ const month = inYear.size === 1 ? [...inYear][0] : void 0;
1054
+ holidays.push(...holidaysOf(await calendarificGet(h, "holidays", { ...filterQuery(args), year, month })));
1055
+ }
1056
+ const skip = skipOf(h, args.cursor);
1057
+ const inWindow = holidays.map(trimHoliday).filter((holiday) => {
1058
+ const day = String(holiday["date"] ?? "").slice(0, 10);
1059
+ return day >= first && day <= last;
1060
+ }).sort((a, b) => String(a["date"]).localeCompare(String(b["date"])));
1061
+ return h.page({
1062
+ key: "holidays",
1063
+ items: inWindow.slice(skip),
1064
+ extra: { country: args.country.toUpperCase(), from: first, to: last, count: inWindow.length },
1065
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
1066
+ });
1067
+ }
1068
+ };
1069
+ var listCountries = {
1070
+ name: "list_countries",
1071
+ kind: "read",
1072
+ title: "List the countries Calendarific covers",
1073
+ description: "Every country Calendarific has holidays for, with its ISO 3166-1 alpha-2 code (the country of the holiday tools), name, number of holidays and number of supported languages. One request of the plan's monthly limit.",
1074
+ inputSchema: { type: "object", properties: { cursor: CURSOR }, additionalProperties: false },
1075
+ async run(args, h) {
1076
+ const skip = skipOf(h, args.cursor);
1077
+ const response = await calendarificGet(h, "countries", {});
1078
+ const countries = (Array.isArray(response["countries"]) ? response["countries"] : []).filter((item) => typeof item === "object" && item !== null).map((country) => compact({
1079
+ code: text(country["iso-3166"] ?? country["iso_3166"] ?? country["code"], 10),
1080
+ name: text(country["country_name"] ?? country["name"], 120),
1081
+ holidays: typeof country["total_holidays"] === "number" ? country["total_holidays"] : void 0,
1082
+ languages: typeof country["supported_languages"] === "number" ? country["supported_languages"] : void 0
1083
+ }));
1084
+ return h.page({
1085
+ key: "countries",
1086
+ items: countries.slice(skip),
1087
+ extra: { count: countries.length },
1088
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
1089
+ });
1090
+ }
1091
+ };
1092
+ var listLanguages = {
1093
+ name: "list_languages",
1094
+ kind: "read",
1095
+ title: "List the languages Calendarific translates holidays into",
1096
+ description: "The languages the language option of the holiday tools takes: ISO 639-1 code, English name and native name. Translations need a paid plan. One request of the plan's monthly limit.",
1097
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1098
+ async run(_args, h) {
1099
+ const response = await calendarificGet(h, "languages", {});
1100
+ const languages = (Array.isArray(response["languages"]) ? response["languages"] : []).filter((item) => typeof item === "object" && item !== null).map((language) => compact({
1101
+ code: text(language["code"] ?? language["iso-639"] ?? language["iso_639"], 10),
1102
+ name: text(language["name"], 80),
1103
+ nativeName: text(language["nativeName"] ?? language["native_name"], 80)
1104
+ }));
1105
+ return { count: languages.length, languages };
1106
+ }
1107
+ };
1108
+ var connector = defineConnector({
1109
+ vendor: "calendarific",
1110
+ label: "Calendarific",
1111
+ origins: [ORIGIN],
1112
+ credentials: ["apikey"],
1113
+ credentialLabels: { apikey: "Calendarific API key" },
1114
+ tools: [listHolidays, listUpcomingHolidays, listCountries, listLanguages]
1115
+ });
1116
+ module.exports = connector;