@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,1303 @@
1
+ /* adapty connector module (MIT License). Built from src/vendors/adapty; 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(text) {
24
+ return encoder.encode(text);
25
+ }
26
+ function utf8Length(text) {
27
+ return encoder.encode(text).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(text) {
43
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
44
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.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(text, max) {
51
+ if (text.length <= max) return text;
52
+ const points = Array.from(text);
53
+ if (points.length <= max) return text;
54
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
55
+ }
56
+ function cleanVendorText(text, max = 300) {
57
+ if (typeof text !== "string") return void 0;
58
+ if (/^\s*</.test(text)) return void 0;
59
+ const line = text.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 text = utf8Decode(bytes);
270
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
271
+ try {
272
+ return JSON.parse(text);
273
+ } catch {
274
+ }
275
+ }
276
+ return text;
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 text = typeof value === "string" ? value.trim() : "";
421
+ if (!text) return { ok: false, problem: "is empty" };
422
+ let url;
423
+ try {
424
+ url = new URL(text.includes("://") ? text : `https://${text}`);
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 text = String(value).trim();
748
+ if (text) out[key] = text;
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 = (text) => {
778
+ try {
779
+ ctx.log?.(text);
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/adapty/index.ts
892
+ var ORIGIN = "https://api-admin.adapty.io";
893
+ var BASE = "/api/v1/client-api/metrics";
894
+ var DAY_MS = 24 * 60 * 60 * 1e3;
895
+ var ROOM = 600;
896
+ var CHARTS = [
897
+ "revenue",
898
+ "mrr",
899
+ "arr",
900
+ "arpu",
901
+ "arppu",
902
+ "subscriptions_active",
903
+ "subscriptions_new",
904
+ "subscriptions_renewal_cancelled",
905
+ "subscriptions_expired",
906
+ "trials_active",
907
+ "trials_new",
908
+ "trials_renewal_cancelled",
909
+ "trials_expired",
910
+ "grace_period",
911
+ "billing_issue",
912
+ "refund_events",
913
+ "refund_money",
914
+ "non_subscriptions",
915
+ "installs"
916
+ ];
917
+ var SEGMENTATIONS = [
918
+ "period",
919
+ "renewal_status",
920
+ "cancellation_reason",
921
+ "store_product_id",
922
+ "country",
923
+ "store",
924
+ "paywall_id",
925
+ "audience_id",
926
+ "placement_id",
927
+ "flow_id",
928
+ "flow_screen_id",
929
+ "segment_id",
930
+ "duration",
931
+ "offer_category",
932
+ "offer_type",
933
+ "offer_id",
934
+ "attribution_source",
935
+ "attribution_status",
936
+ "attribution_channel",
937
+ "attribution_campaign",
938
+ "attribution_adgroup",
939
+ "attribution_adset",
940
+ "attribution_creative",
941
+ "day",
942
+ "week",
943
+ "month",
944
+ "year"
945
+ ];
946
+ var PERIOD_UNITS = ["day", "week", "month", "quarter", "year"];
947
+ var ERRORS = {
948
+ 400: "Adapty did not accept the request: a field, value or date it does not know. For a filter value you are not sure of, run the same call with that field as segmentation and use the exact values it shows",
949
+ 401: "Adapty rejected the API key: it was replaced or mistyped. Paste the app's current secret key (App settings, General tab)"
950
+ };
951
+ var DATE = { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$" };
952
+ var UUID_LIST = (what) => ({
953
+ type: "array",
954
+ items: { type: "string", pattern: "^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$" },
955
+ minItems: 1,
956
+ maxItems: 100,
957
+ description: `Adapty ${what} ids (UUIDs, from the item's URL in the Adapty Dashboard). Never guess one.`
958
+ });
959
+ var TEXT_LIST = (description, pattern = "^.{1,200}$") => ({
960
+ type: "array",
961
+ items: { type: "string", pattern },
962
+ minItems: 1,
963
+ maxItems: 100,
964
+ description
965
+ });
966
+ var FILTERS = {
967
+ type: "object",
968
+ description: "Filters; each is a list of values, and values in one list are ORed.",
969
+ properties: {
970
+ country: TEXT_LIST('Two-letter country codes, e.g. ["us", "de"].', "^[A-Za-z]{2}$"),
971
+ store: TEXT_LIST('Stores, e.g. ["app_store", "play_store"].'),
972
+ store_product_id: TEXT_LIST('Store-qualified product ids, "<store>:<product_id>", e.g. ["app_store:premium_monthly"]. A bare product id is refused.', "^[a-z_]+:.{1,200}$"),
973
+ duration: TEXT_LIST("Subscription durations."),
974
+ offer_category: TEXT_LIST('Offer categories, e.g. ["introductory"] or ["promotional"].'),
975
+ offer_type: TEXT_LIST("Offer types."),
976
+ offer_id: TEXT_LIST("Offer ids."),
977
+ attribution_source: TEXT_LIST("Attribution sources (integrations)."),
978
+ attribution_status: TEXT_LIST('"organic" or "non-organic".'),
979
+ attribution_channel: TEXT_LIST("Attribution channels."),
980
+ attribution_campaign: TEXT_LIST("Attribution campaigns."),
981
+ attribution_adgroup: TEXT_LIST("Attribution ad groups."),
982
+ attribution_adset: TEXT_LIST("Attribution ad sets."),
983
+ attribution_creative: TEXT_LIST("Attribution creatives."),
984
+ segment_id: UUID_LIST("segment"),
985
+ audience_id: UUID_LIST("audience"),
986
+ paywall_id: UUID_LIST("paywall"),
987
+ placement_id: UUID_LIST("placement"),
988
+ flow_id: UUID_LIST("flow"),
989
+ flow_screen_id: TEXT_LIST('Flow screens, "<flow_id>:<screen_id>".', "^[^:]{1,100}:.{1,100}$"),
990
+ virtual_currency: TEXT_LIST('Virtual currency codes, or "no-virtual-currency".')
991
+ },
992
+ additionalProperties: false
993
+ };
994
+ var COMMON = {
995
+ date_from: { ...DATE, description: "The first day, YYYY-MM-DD. With date_to; default: the last 28 full days, ending yesterday (UTC)." },
996
+ date_to: { ...DATE, description: "The last day, YYYY-MM-DD; both ends are included." },
997
+ compare_from: { ...DATE, description: "A period to compare with: its first day (with compare_to)." },
998
+ compare_to: { ...DATE, description: "The comparison period's last day." },
999
+ filters: FILTERS,
1000
+ timezone: {
1001
+ type: "string",
1002
+ pattern: "^(UTC|[A-Za-z]+(/[A-Za-z0-9_+-]+){1,2})$",
1003
+ description: "The time zone Adapty groups days in, an IANA name such as Europe/Berlin. Name it in the report."
1004
+ }
1005
+ };
1006
+ var SEGMENTATION = { type: "string", enum: SEGMENTATIONS, description: "One grouping, e.g. country, store, store_product_id, attribution_channel, or week." };
1007
+ var CURSOR = { type: "string", description: "nextCursor from the previous result, with the same other arguments." };
1008
+ var PERIOD_UNIT = { type: "string", enum: PERIOD_UNITS, description: "The interval of the points: day, week, month, quarter or year." };
1009
+ var DATE_TYPE = {
1010
+ type: "string",
1011
+ enum: ["purchase_date", "profile_install_date"],
1012
+ description: "Which date counts: purchase_date (the purchase, default) or profile_install_date (the install)."
1013
+ };
1014
+ function compact(value) {
1015
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
1016
+ }
1017
+ function day(time) {
1018
+ return new Date(time).toISOString().slice(0, 10);
1019
+ }
1020
+ function definition(value) {
1021
+ if (typeof value !== "string" || !value.trim()) return void 0;
1022
+ const plain = value.replace(/<br\s*\/?>/gi, " ").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
1023
+ return plain ? truncate(plain, 400) : void 0;
1024
+ }
1025
+ function filtersOf(args) {
1026
+ let from = args.date_from;
1027
+ let to = args.date_to;
1028
+ if (from === void 0 !== (to === void 0)) throw new ToolFailure("Give date_from and date_to together, or neither for the last 28 days. Nothing was sent to Adapty.");
1029
+ if (from === void 0 || to === void 0) {
1030
+ const yesterday = Date.now() - DAY_MS;
1031
+ from = day(yesterday - 27 * DAY_MS);
1032
+ to = day(yesterday);
1033
+ }
1034
+ if (from > to) throw new ToolFailure("date_from must not be after date_to. Nothing was sent to Adapty.");
1035
+ const filters = { date: [from, to] };
1036
+ if (args.compare_from === void 0 !== (args.compare_to === void 0)) {
1037
+ throw new ToolFailure("Give compare_from and compare_to together. Nothing was sent to Adapty.");
1038
+ }
1039
+ if (args.compare_from !== void 0 && args.compare_to !== void 0) {
1040
+ if (args.compare_from > args.compare_to) throw new ToolFailure("compare_from must not be after compare_to. Nothing was sent to Adapty.");
1041
+ filters["compare_date"] = [args.compare_from, args.compare_to];
1042
+ }
1043
+ for (const [key, values] of Object.entries(args.filters ?? {})) filters[key] = values;
1044
+ return filters;
1045
+ }
1046
+ async function metrics(h, endpoint, body, timezone) {
1047
+ const { data } = await h.api({
1048
+ method: "POST",
1049
+ path: `${BASE}/${endpoint}/`,
1050
+ json: { ...body, format: "json" },
1051
+ safe: true,
1052
+ errors: ERRORS,
1053
+ ...timezone ? { headers: { "adapty-tz": timezone } } : {}
1054
+ });
1055
+ if (data === null || typeof data !== "object") throw new ToolFailure("Adapty answered with something other than JSON.");
1056
+ return data;
1057
+ }
1058
+ function rangeOf(body) {
1059
+ const filters = body["filters"];
1060
+ return compact({ dateRange: filters["date"], compareRange: filters["compare_date"] });
1061
+ }
1062
+ function fitParallel(h, base, lists, skip, key) {
1063
+ const longest = Math.max(0, ...lists.map((list) => list.items.length));
1064
+ const build = (count) => ({
1065
+ ...base,
1066
+ [key]: Object.fromEntries(lists.map((list) => [list.name, { ...list.meta, points: list.items.slice(skip, skip + count) }]))
1067
+ });
1068
+ const remaining = Math.max(0, longest - skip);
1069
+ const whole = build(remaining);
1070
+ if (jsonSize(whole) <= OUTPUT_LIMIT_BYTES - ROOM) return whole;
1071
+ let low = 1;
1072
+ let high = remaining - 1;
1073
+ while (low < high) {
1074
+ const middle = Math.ceil((low + high) / 2);
1075
+ if (jsonSize(build(middle)) <= OUTPUT_LIMIT_BYTES - ROOM) low = middle;
1076
+ else high = middle - 1;
1077
+ }
1078
+ const more = skip + low < longest;
1079
+ return {
1080
+ ...build(low),
1081
+ truncated: true,
1082
+ note: `Points ${skip + 1} to ${skip + low} of ${longest} are shown${more ? ": pass nextCursor back as cursor for the rest, or ask for a longer period_unit" : ""}.`,
1083
+ ...more ? { nextCursor: h.makeCursor({ o: skip + low }) } : {}
1084
+ };
1085
+ }
1086
+ function skipOf(h, cursor) {
1087
+ const state = h.cursor(cursor);
1088
+ return typeof state?.["o"] === "number" ? state["o"] : 0;
1089
+ }
1090
+ function trimMetric(metric) {
1091
+ return compact({
1092
+ title: metric?.title,
1093
+ metricName: metric?.metric_name,
1094
+ value: metric?.value,
1095
+ valueFrom: metric?.value_from,
1096
+ valueTo: metric?.value_to,
1097
+ compareValueFrom: metric?.compare_value_from,
1098
+ compareValueTo: metric?.compare_value_to,
1099
+ unit: metric?.unit,
1100
+ aggregation: metric?.default_aggregation,
1101
+ recommendedPeriod: metric?.recommended_period,
1102
+ definition: definition(metric?.description)
1103
+ });
1104
+ }
1105
+ var connector = defineConnector({
1106
+ vendor: "adapty",
1107
+ label: "Adapty",
1108
+ origins: [ORIGIN],
1109
+ credentials: ["apikey"],
1110
+ credentialLabels: { apikey: "Adapty secret API key" },
1111
+ authHeaders: (credentials) => ({ authorization: `Api-Key ${credentials["apikey"]}` }),
1112
+ tools: [
1113
+ {
1114
+ name: "get_chart",
1115
+ kind: "read",
1116
+ title: "Get an Adapty analytics chart",
1117
+ description: "One of the app's analytics charts over a date range: revenue (with revenue, proceeds after store commission, and net revenue after taxes), MRR, ARR, ARPU, ARPPU, active and new subscriptions and trials, cancellations, expirations, grace period, billing issues, refunds, one-time purchases or installs. Each metric has its total for the period (value; never add up points of an average metric), its points by period or group, the comparison values when compare dates are given, its unit and Adapty's definition. Revenue counts on the purchase day; for revenue by install date use get_cohorts.",
1118
+ inputSchema: {
1119
+ type: "object",
1120
+ properties: {
1121
+ chart_id: { type: "string", enum: CHARTS, default: "revenue", description: "The chart (default revenue)." },
1122
+ ...COMMON,
1123
+ period_unit: { ...PERIOD_UNIT, default: "month" },
1124
+ date_type: DATE_TYPE,
1125
+ segmentation: SEGMENTATION,
1126
+ cursor: CURSOR
1127
+ },
1128
+ additionalProperties: false
1129
+ },
1130
+ async run(args, h) {
1131
+ const skip = skipOf(h, args.cursor);
1132
+ const body = compact({ chart_id: args.chart_id, filters: filtersOf(args), period_unit: args.period_unit, date_type: args.date_type, segmentation: args.segmentation });
1133
+ const data = await metrics(h, "analytics", body, args.timezone);
1134
+ const metricsData = data?.data && typeof data.data === "object" ? data.data : {};
1135
+ const lists = Object.entries(metricsData).map(([name2, metric]) => ({
1136
+ name: name2,
1137
+ meta: trimMetric(metric),
1138
+ items: Array.isArray(metric?.data) ? metric.data : []
1139
+ }));
1140
+ return fitParallel(h, compact({ chart: args.chart_id, ...rangeOf(body), periodUnit: args.period_unit, segmentation: args.segmentation, timezone: args.timezone }), lists, skip, "metrics");
1141
+ }
1142
+ },
1143
+ {
1144
+ name: "get_conversion",
1145
+ kind: "read",
1146
+ title: "Get an Adapty conversion rate",
1147
+ description: 'A conversion rate between two subscription periods, such as from the first paid period (from_period 1) to more than 6 months (to_period "6+"), the pair Adapty documents. value is the rate in percent and title names the conversion: report another pair only when title names it.',
1148
+ inputSchema: {
1149
+ type: "object",
1150
+ properties: {
1151
+ from_period: { type: "string", pattern: "^[A-Za-z0-9+_-]{1,20}$", description: 'The starting period, e.g. "1"; leave out to send none (null), as Adapty allows.' },
1152
+ to_period: { type: "string", pattern: "^[A-Za-z0-9+_-]{1,20}$", description: 'The period converted to, e.g. "6+".' },
1153
+ ...COMMON,
1154
+ period_unit: { ...PERIOD_UNIT, default: "day" },
1155
+ date_type: DATE_TYPE,
1156
+ segmentation: SEGMENTATION,
1157
+ cursor: CURSOR
1158
+ },
1159
+ required: ["to_period"],
1160
+ additionalProperties: false
1161
+ },
1162
+ async run(args, h) {
1163
+ const skip = skipOf(h, args.cursor);
1164
+ const body = {
1165
+ ...compact({ filters: filtersOf(args), to_period: args.to_period, period_unit: args.period_unit, date_type: args.date_type, segmentation: args.segmentation }),
1166
+ // Adapty takes null for no starting period, and its own example sends a number for a numeric one.
1167
+ from_period: args.from_period === void 0 ? null : /^\d+$/.test(args.from_period) ? Number(args.from_period) : args.from_period
1168
+ };
1169
+ const data = await metrics(h, "conversion", body, args.timezone);
1170
+ return h.page({
1171
+ key: "points",
1172
+ items: (Array.isArray(data?.data) ? data.data : []).slice(skip),
1173
+ extra: compact({ ...rangeOf(body), ...trimMetric(data), timezone: args.timezone }),
1174
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
1175
+ });
1176
+ }
1177
+ },
1178
+ {
1179
+ name: "get_funnel",
1180
+ kind: "read",
1181
+ title: "Get the Adapty funnel",
1182
+ description: "Where users drop off, from install to paywall shown, trial and paid periods: each stage with the users who reached it (value), their share of the first stage (value_relative) and the users lost before the next stage. The segment of type total is the whole app.",
1183
+ inputSchema: {
1184
+ type: "object",
1185
+ properties: {
1186
+ ...COMMON,
1187
+ show_value_as: { type: "string", enum: ["absolute", "relative", "both"], default: "both", description: "absolute, relative or both (default)." },
1188
+ segmentation: SEGMENTATION,
1189
+ cursor: CURSOR
1190
+ },
1191
+ additionalProperties: false
1192
+ },
1193
+ async run(args, h) {
1194
+ const skip = skipOf(h, args.cursor);
1195
+ const body = compact({ filters: filtersOf(args), show_value_as: args.show_value_as, segmentation: args.segmentation });
1196
+ const data = await metrics(h, "funnel", body, args.timezone);
1197
+ return h.page({
1198
+ key: "segments",
1199
+ items: (Array.isArray(data?.data) ? data.data : []).slice(skip),
1200
+ extra: compact({ ...rangeOf(body), timezone: args.timezone }),
1201
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
1202
+ });
1203
+ }
1204
+ },
1205
+ {
1206
+ name: "get_retention",
1207
+ kind: "read",
1208
+ title: "Get Adapty subscription retention",
1209
+ description: "How many subscribers stay, period by period, counted from the first paid period or, with use_trial, from the trial.",
1210
+ inputSchema: {
1211
+ type: "object",
1212
+ properties: {
1213
+ ...COMMON,
1214
+ use_trial: { type: "boolean", default: false, description: "true counts from the trial." },
1215
+ segmentation: SEGMENTATION,
1216
+ cursor: CURSOR
1217
+ },
1218
+ additionalProperties: false
1219
+ },
1220
+ async run(args, h) {
1221
+ const skip = skipOf(h, args.cursor);
1222
+ const body = compact({ filters: filtersOf(args), use_trial: args.use_trial, segmentation: args.segmentation });
1223
+ const data = await metrics(h, "retention", body, args.timezone);
1224
+ return h.page({
1225
+ key: "rows",
1226
+ items: (Array.isArray(data?.data) ? data.data : []).slice(skip),
1227
+ extra: compact({ ...rangeOf(body), title: data?.title, metricName: data?.metric_name, valueType: data?.value_type, definition: definition(data?.description), timezone: args.timezone }),
1228
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
1229
+ });
1230
+ }
1231
+ },
1232
+ {
1233
+ name: "get_ltv",
1234
+ kind: "read",
1235
+ title: "Get Adapty lifetime value",
1236
+ description: "Realized lifetime value (revenue for the period divided by the subscribers at its start, not a prediction) on three bases: revenue, proceeds and net revenue, each with its total and rows (the total row first) with cohort sizes and values per period. Say which basis you quote.",
1237
+ inputSchema: {
1238
+ type: "object",
1239
+ properties: {
1240
+ ...COMMON,
1241
+ period_unit: PERIOD_UNIT,
1242
+ period_type: { type: "string", enum: ["renewals", "days"], description: "Count periods by renewals or by days." },
1243
+ segmentation: SEGMENTATION,
1244
+ cursor: CURSOR
1245
+ },
1246
+ additionalProperties: false
1247
+ },
1248
+ async run(args, h) {
1249
+ const skip = skipOf(h, args.cursor);
1250
+ const body = compact({ filters: filtersOf(args), period_unit: args.period_unit, period_type: args.period_type, segmentation: args.segmentation });
1251
+ const data = await metrics(h, "ltv", body, args.timezone);
1252
+ const lists = ["revenue", "proceeds", "net_revenue"].filter((name2) => data?.[name2] && typeof data[name2] === "object").map((name2) => ({
1253
+ name: name2,
1254
+ meta: compact({ title: data[name2].title, value: data[name2].value, unit: data[name2].unit, definition: definition(data[name2].description) }),
1255
+ items: Array.isArray(data[name2].data) ? data[name2].data : []
1256
+ }));
1257
+ return fitParallel(h, compact({ ...rangeOf(body), periodUnit: args.period_unit, periodType: args.period_type, segmentation: args.segmentation, timezone: args.timezone }), lists, skip, "bases");
1258
+ }
1259
+ },
1260
+ {
1261
+ name: "get_cohorts",
1262
+ kind: "read",
1263
+ title: "Get Adapty install cohorts",
1264
+ description: "Install cohorts: per install period, the installs, subscribers, subscriptions, revenue, proceeds and net revenue in USD, ARPU and ARPPU, with values per period and predictions. Revenue counts on each user's install date, as ad reports do. A period with currently_active_period true is still running and will grow. Takes no segmentation.",
1265
+ inputSchema: {
1266
+ type: "object",
1267
+ properties: {
1268
+ ...COMMON,
1269
+ period_unit: { ...PERIOD_UNIT, default: "month" },
1270
+ period_type: { type: "string", enum: ["renewals", "days"], default: "renewals", description: "Count periods by renewals (default) or by days." },
1271
+ value_type: { type: "string", enum: ["absolute", "relative"], default: "absolute", description: "absolute (default) or relative values." },
1272
+ value_field: { type: "string", enum: ["revenue", "arppu", "arpu", "arpas", "subscribers", "subscriptions"], default: "revenue", description: "The value shown per period (default revenue)." },
1273
+ accounting_type: { type: "string", enum: ["revenue", "proceeds", "net_revenue"], default: "revenue", description: "revenue (default), proceeds or net_revenue." },
1274
+ renewal_days: { type: "array", items: { type: "integer", minimum: 0, maximum: 3650 }, maxItems: 50, uniqueItems: true, description: "Days since install, with period_type days." },
1275
+ prediction_months: { type: "integer", enum: [3, 6, 9, 12, 18, 24], default: 12, description: "Months of prediction: 3, 6, 9, 12 (default), 18 or 24." },
1276
+ cursor: CURSOR
1277
+ },
1278
+ additionalProperties: false
1279
+ },
1280
+ async run(args, h) {
1281
+ const skip = skipOf(h, args.cursor);
1282
+ const body = compact({
1283
+ filters: filtersOf(args),
1284
+ period_unit: args.period_unit,
1285
+ period_type: args.period_type,
1286
+ value_type: args.value_type,
1287
+ value_field: args.value_field,
1288
+ accounting_type: args.accounting_type,
1289
+ renewal_days: args.renewal_days,
1290
+ prediction_months: args.prediction_months
1291
+ });
1292
+ const data = await metrics(h, "cohort", body, args.timezone);
1293
+ return h.page({
1294
+ key: "cohorts",
1295
+ items: (Array.isArray(data?.data) ? data.data : []).slice(skip),
1296
+ extra: compact({ ...rangeOf(body), periodUnit: args.period_unit, valueField: args.value_field, accountingType: args.accounting_type, timezone: args.timezone }),
1297
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
1298
+ });
1299
+ }
1300
+ }
1301
+ ]
1302
+ });
1303
+ module.exports = connector;