@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,2043 @@
1
+ /* kaggle connector module (MIT License). Built from src/vendors/kaggle; do not edit. */
2
+ "use strict";
3
+
4
+ // src/core/errors.ts
5
+ var ToolFailure = class extends Error {
6
+ details;
7
+ constructor(message, details = {}) {
8
+ super(message);
9
+ this.name = "ToolFailure";
10
+ this.details = details;
11
+ }
12
+ };
13
+ var OutcomeUnknown = class extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "OutcomeUnknown";
17
+ }
18
+ };
19
+
20
+ // src/core/accounts.ts
21
+ function allowedAccounts(accounts, key) {
22
+ if (accounts === null) return null;
23
+ const list = accounts?.[key];
24
+ return Array.isArray(list) ? list.map(String) : [];
25
+ }
26
+ function requireAccounts(accounts, key, ids, label = "account") {
27
+ const allowed = allowedAccounts(accounts, key);
28
+ if (allowed === null) return;
29
+ const requested = (Array.isArray(ids) ? ids : [ids]).map(String);
30
+ const refused2 = requested.filter((id) => !allowed.includes(id));
31
+ if (!refused2.length) return;
32
+ throw new ToolFailure(
33
+ `The ${label} ${refused2.join(", ")} ${refused2.length > 1 ? "are" : "is"} not among the ${label}s chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`) + " Nothing was sent."
34
+ );
35
+ }
36
+
37
+ // src/core/text.ts
38
+ var encoder = new TextEncoder();
39
+ var decoder = new TextDecoder();
40
+ function utf8Bytes(text) {
41
+ return encoder.encode(text);
42
+ }
43
+ function utf8Length(text) {
44
+ return encoder.encode(text).length;
45
+ }
46
+ function utf8Decode(bytes) {
47
+ return decoder.decode(bytes);
48
+ }
49
+ function base64Encode(bytes) {
50
+ let binary = "";
51
+ for (let i = 0; i < bytes.length; i += 32768) {
52
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
53
+ }
54
+ return btoa(binary);
55
+ }
56
+ function base64UrlEncode(bytes) {
57
+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
58
+ }
59
+ function base64UrlDecode(text) {
60
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
61
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
62
+ const binary = atob(padded);
63
+ const bytes = new Uint8Array(binary.length);
64
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
65
+ return bytes;
66
+ }
67
+ function truncate(text, max) {
68
+ if (text.length <= max) return text;
69
+ const points = Array.from(text);
70
+ if (points.length <= max) return text;
71
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
72
+ }
73
+ function cleanVendorText(text, max = 300) {
74
+ if (typeof text !== "string") return void 0;
75
+ if (/^\s*</.test(text)) return void 0;
76
+ const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
77
+ return line ? truncate(line, max) : void 0;
78
+ }
79
+ function formatNumber(value) {
80
+ return value.toLocaleString("en-US");
81
+ }
82
+
83
+ // src/core/output.ts
84
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
85
+ function jsonSize(value) {
86
+ return utf8Length(JSON.stringify(value) ?? "");
87
+ }
88
+ function cutStrings(value, max) {
89
+ if (typeof value === "string") return truncate(value, max);
90
+ if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
91
+ if (typeof value === "object" && value !== null) {
92
+ const out = {};
93
+ for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
94
+ return out;
95
+ }
96
+ return value;
97
+ }
98
+ function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
99
+ if (jsonSize(value) <= limit) return { value, truncated: false };
100
+ for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
101
+ const cut = cutStrings(value, max);
102
+ if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
103
+ }
104
+ return void 0;
105
+ }
106
+ function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
107
+ const build = (count) => {
108
+ const cut = count < input.items.length;
109
+ const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
110
+ const next = cut ? input.resumeAt(count) : input.nextPage;
111
+ if (next) result2["nextCursor"] = next;
112
+ if (cut) result2["truncated"] = true;
113
+ return result2;
114
+ };
115
+ const all = build(input.items.length);
116
+ if (jsonSize(all) <= limit) return all;
117
+ let low = 1;
118
+ let high = input.items.length - 1;
119
+ while (low < high) {
120
+ const middle = Math.ceil((low + high) / 2);
121
+ if (jsonSize(build(middle)) <= limit) low = middle;
122
+ else high = middle - 1;
123
+ }
124
+ const best = build(low);
125
+ if (jsonSize(best) <= limit) return best;
126
+ const shrunk = shrinkToFit(best, limit);
127
+ if (shrunk) return { ...shrunk.value, truncated: true };
128
+ throw new ToolFailure("The result is too large to return, even one item at a time.");
129
+ }
130
+ function encodeCursor(tool, state) {
131
+ return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
132
+ }
133
+ function decodeCursor(tool, cursor) {
134
+ if (cursor === void 0 || cursor === "") return null;
135
+ try {
136
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
137
+ if (typeof state === "object" && state !== null && state.t === tool) {
138
+ return state;
139
+ }
140
+ } catch {
141
+ }
142
+ throw new ToolFailure(
143
+ "The cursor is not valid for this tool. Pass the nextCursor value of the previous result unchanged, or leave cursor out to start from the beginning."
144
+ );
145
+ }
146
+
147
+ // src/core/api-tools.ts
148
+ var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
149
+ var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
150
+ var NOTE_ROOM = 400;
151
+ var MAX_CUT_POINTS = 4e4;
152
+ function isQueryValue(value) {
153
+ return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
154
+ }
155
+ function nothingSent(sentence) {
156
+ return new ToolFailure(`${sentence} Nothing was sent.`);
157
+ }
158
+ function fitReply(reply) {
159
+ if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
160
+ const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
161
+ if (shrunk) {
162
+ return {
163
+ ...shrunk.value,
164
+ truncated: true,
165
+ note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
166
+ };
167
+ }
168
+ const text = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
169
+ const points = Array.from(text.length > MAX_CUT_POINTS ? text.slice(0, MAX_CUT_POINTS) : text);
170
+ if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
171
+ const cut = (count) => ({
172
+ status: reply["status"],
173
+ ...reply["headers"] ? { headers: reply["headers"] } : {},
174
+ truncated: true,
175
+ note: `The reply has ${formatNumber(utf8Length(text))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
176
+ text: points.slice(0, count).join("")
177
+ });
178
+ let low = 0;
179
+ let high = points.length;
180
+ while (low < high) {
181
+ const middle = Math.ceil((low + high) / 2);
182
+ if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
183
+ else high = middle - 1;
184
+ }
185
+ return cut(low);
186
+ }
187
+ function shapeReply(response, headerNames) {
188
+ const reply = { status: response.status };
189
+ const headers = {};
190
+ for (const name2 of headerNames) {
191
+ const value = response.headers.get(name2);
192
+ if (value) headers[name2] = truncate(value, 2e3);
193
+ }
194
+ if (Object.keys(headers).length) reply["headers"] = headers;
195
+ const type = response.headers.get("content-type") ?? "";
196
+ if (type && !TEXT_TYPES.test(type)) {
197
+ reply["contentType"] = truncate(type, 200);
198
+ reply["note"] = "The reply is a binary file and is not shown.";
199
+ return reply;
200
+ }
201
+ if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
202
+ return fitReply(reply);
203
+ }
204
+ function checkAccounts(rule, request, h) {
205
+ const label = rule.label ?? "account";
206
+ const allowed = allowedAccounts(h.ctx.accounts, rule.key);
207
+ if (allowed === null) return;
208
+ const namesNone = nothingSent(
209
+ `This request names none of the ${label}s chosen for this connection. ` + (allowed.length ? `It must name one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`)
210
+ );
211
+ if (rule.ids) {
212
+ const ids = rule.ids(request).map(String);
213
+ if (!ids.length) throw namesNone;
214
+ requireAccounts(h.ctx.accounts, rule.key, ids, label);
215
+ return;
216
+ }
217
+ if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
218
+ }
219
+ function apiTools(options) {
220
+ const { label, basePath } = options;
221
+ const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
222
+ const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
223
+ const base = basePath?.replace(/\/+$/, "");
224
+ const pathSchema = {
225
+ type: "string",
226
+ minLength: 1,
227
+ maxLength: 2e3,
228
+ pattern: "^(?!.*//)/[^?#]*$",
229
+ description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
230
+ };
231
+ const querySchema = {
232
+ type: "object",
233
+ description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
234
+ };
235
+ const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
236
+ async function run(method, args, h) {
237
+ let origin = h.origins[0];
238
+ if (args.origin !== void 0) {
239
+ let wanted;
240
+ try {
241
+ wanted = new URL(args.origin).origin;
242
+ } catch {
243
+ }
244
+ if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
245
+ origin = wanted;
246
+ }
247
+ const url = new URL(args.path, origin);
248
+ if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
249
+ const path = url.pathname;
250
+ if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
251
+ let segments;
252
+ try {
253
+ segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
254
+ } catch {
255
+ throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
256
+ }
257
+ if (segments[segments.length - 1] === "") segments.pop();
258
+ const query = {};
259
+ const queryLists = {};
260
+ for (const [key, value] of Object.entries(args.query ?? {})) {
261
+ if (value === void 0 || value === null) continue;
262
+ const list = Array.isArray(value) ? value : [value];
263
+ if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
264
+ query[key] = Array.isArray(value) ? list : value;
265
+ queryLists[key] = list.map(String);
266
+ }
267
+ const request = { method, origin, path, query };
268
+ if (method !== "GET") {
269
+ if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
270
+ if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
271
+ if (args.json !== void 0 && !args.content_type) {
272
+ request.json = args.json;
273
+ } else if (args.json !== void 0 || args.body !== void 0) {
274
+ request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
275
+ request.contentType = args.content_type;
276
+ }
277
+ request.write = true;
278
+ }
279
+ const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
280
+ if (options.accounts) checkAccounts(options.accounts, info, h);
281
+ await options.guard?.(info, h);
282
+ const response = options.send ? await options.send(request, h) : await h.api(request);
283
+ return shapeReply(response, headerNames);
284
+ }
285
+ return [
286
+ {
287
+ name: "api_get",
288
+ kind: "read",
289
+ title: `Call the ${label} API (GET)`,
290
+ description: `${options.description} Sends one GET request with the connection's credentials and returns the HTTP status and the reply, JSON or text, cut to fit 32 KB (use the API's own paging and field parameters for long lists). It changes nothing.`,
291
+ inputSchema: {
292
+ type: "object",
293
+ properties: { path: pathSchema, query: querySchema, ...originSchema },
294
+ required: ["path"],
295
+ additionalProperties: false
296
+ },
297
+ run: (args, h) => run("GET", args, h)
298
+ },
299
+ {
300
+ name: "api_request",
301
+ kind: "write",
302
+ check: "api_get",
303
+ title: `Send a request to the ${label} API`,
304
+ description: `${options.description} Sends one ${methods.join(", ")} request with the connection's credentials, with a JSON body (json) or another body (body and content_type), and returns the HTTP status and the reply. It can create, change or delete data. It is never retried: when the outcome is unclear, check with api_get before sending it again.`,
305
+ inputSchema: {
306
+ type: "object",
307
+ properties: {
308
+ method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
309
+ path: pathSchema,
310
+ query: querySchema,
311
+ json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
312
+ body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
313
+ content_type: {
314
+ type: "string",
315
+ pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
316
+ maxLength: 200,
317
+ description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
318
+ },
319
+ ...originSchema
320
+ },
321
+ required: ["method", "path"],
322
+ additionalProperties: false
323
+ },
324
+ run: (args, h) => run(args.method, args, h)
325
+ }
326
+ ];
327
+ }
328
+
329
+ // src/core/credentials.ts
330
+ function requiredAlternatives(module2) {
331
+ return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
332
+ }
333
+ function unmetAlternatives(alternatives, has) {
334
+ const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
335
+ if (lacking.some((list) => list.length === 0)) return [];
336
+ return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
337
+ }
338
+ function andList(items) {
339
+ if (items.length <= 2) return items.join(" and ");
340
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
341
+ }
342
+ function orList(items) {
343
+ if (items.length <= 1) return items.join("");
344
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
345
+ }
346
+
347
+ // src/core/files.ts
348
+ var ATTACHMENT_URI = "attachment:///";
349
+ var MAX_NAME = 200;
350
+ function fileLimitOf(ctx) {
351
+ const maxBytes = ctx.files?.maxBytes;
352
+ return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
353
+ }
354
+ function fileName(name2) {
355
+ const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
356
+ const points = Array.from(clean);
357
+ if (points.length <= MAX_NAME) return clean || "file";
358
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
359
+ return points.slice(0, MAX_NAME - extension.length).join("") + extension;
360
+ }
361
+ function fileType(mimeType) {
362
+ const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
363
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
364
+ }
365
+ function resourceBlock(file) {
366
+ return {
367
+ type: "resource",
368
+ resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
369
+ };
370
+ }
371
+
372
+ // src/core/http.ts
373
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
374
+ var USER_AGENT = "agent-connectors";
375
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
376
+ function errorCode(error) {
377
+ const code = error?.code;
378
+ return typeof code === "string" ? code : void 0;
379
+ }
380
+ function describe(error) {
381
+ const name2 = error?.name;
382
+ const code = errorCode(error);
383
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
384
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
385
+ if (code === "TOO_LARGE") return "the reply was too large";
386
+ return cleanVendorText(error?.message, 200) ?? "a network error";
387
+ }
388
+ function retryAfterSeconds(headers, now = Date.now()) {
389
+ const retryAfter = headers.get("retry-after");
390
+ if (retryAfter) {
391
+ const seconds = Number(retryAfter);
392
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
393
+ const date = Date.parse(retryAfter);
394
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
395
+ }
396
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
397
+ if (reset) {
398
+ const value = Number(reset);
399
+ if (Number.isFinite(value) && value >= 0) {
400
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
401
+ }
402
+ }
403
+ return void 0;
404
+ }
405
+ function vendorCode(data) {
406
+ if (typeof data !== "object" || data === null) return void 0;
407
+ for (const key of ["error", "code"]) {
408
+ const value = data[key];
409
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
410
+ }
411
+ return void 0;
412
+ }
413
+ function vendorMessage(data) {
414
+ if (typeof data === "string") return cleanVendorText(data);
415
+ if (typeof data !== "object" || data === null) return void 0;
416
+ const record = data;
417
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
418
+ const value = record[key];
419
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
420
+ const nested = value?.message;
421
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
422
+ }
423
+ if (Array.isArray(record["errors"])) {
424
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
425
+ if (messages.length) return cleanVendorText(messages.join("; "));
426
+ }
427
+ return void 0;
428
+ }
429
+ var TooLarge = class extends Error {
430
+ constructor(limit) {
431
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
432
+ this.limit = limit;
433
+ }
434
+ limit;
435
+ };
436
+ async function readCapped(response, maxBytes) {
437
+ const declared = Number(response.headers.get("content-length"));
438
+ if (Number.isFinite(declared) && declared > maxBytes) {
439
+ await response.body?.cancel().catch(() => {
440
+ });
441
+ throw new TooLarge(maxBytes);
442
+ }
443
+ if (!response.body) return new Uint8Array(0);
444
+ const reader = response.body.getReader();
445
+ const chunks = [];
446
+ let total = 0;
447
+ for (; ; ) {
448
+ const { done, value } = await reader.read();
449
+ if (done) break;
450
+ total += value.byteLength;
451
+ if (total > maxBytes) {
452
+ await reader.cancel().catch(() => {
453
+ });
454
+ throw new TooLarge(maxBytes);
455
+ }
456
+ chunks.push(value);
457
+ }
458
+ const bytes = new Uint8Array(total);
459
+ let offset = 0;
460
+ for (const chunk of chunks) {
461
+ bytes.set(chunk, offset);
462
+ offset += chunk.byteLength;
463
+ }
464
+ return bytes;
465
+ }
466
+ function parseBody(bytes, contentType) {
467
+ if (bytes.length === 0) return null;
468
+ const text = utf8Decode(bytes);
469
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
470
+ try {
471
+ return JSON.parse(text);
472
+ } catch {
473
+ }
474
+ }
475
+ return text;
476
+ }
477
+ function createHttp(env) {
478
+ const { label, ctx } = env;
479
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
480
+ const checkCredentials = env.credentialLabels.length ? `Check that the ${andList(env.credentialLabels)} ${env.credentialLabels.length > 1 ? "are" : "is"} correct and still active.` : `Check that the ${label} credentials are correct and still active.`;
481
+ function failureFor(status, headers, data, request) {
482
+ const message = vendorMessage(data);
483
+ const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
484
+ const retryAfter = retryAfterSeconds(headers);
485
+ const code = vendorCode(data);
486
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
487
+ const custom = request.errors?.[status];
488
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
489
+ if (status >= 500) {
490
+ if (request.write) {
491
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
492
+ }
493
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
494
+ }
495
+ if (status === 429) {
496
+ return new ToolFailure(
497
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
498
+ { status, ...extra }
499
+ );
500
+ }
501
+ if (status === 401) {
502
+ return new ToolFailure(
503
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
504
+ { status, ...extra }
505
+ );
506
+ }
507
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
508
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
509
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
510
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
511
+ }
512
+ async function api(request) {
513
+ const method = request.method ?? "GET";
514
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
515
+ throw new Error(`read-only tool sent ${method}`);
516
+ }
517
+ const origin = request.origin ?? env.origins[0];
518
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
519
+ const url = new URL(request.path, origin);
520
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
521
+ for (const [key, value] of Object.entries(request.query ?? {})) {
522
+ if (value === void 0 || value === null) continue;
523
+ if (Array.isArray(value)) {
524
+ url.searchParams.delete(key);
525
+ for (const item of value) url.searchParams.append(key, String(item));
526
+ } else {
527
+ url.searchParams.set(key, String(value));
528
+ }
529
+ }
530
+ const headers = {
531
+ accept: "application/json",
532
+ "user-agent": USER_AGENT,
533
+ ...request.auth === false ? {} : env.authHeaders(),
534
+ ...request.headers
535
+ };
536
+ let body;
537
+ if (request.json !== void 0) {
538
+ body = JSON.stringify(request.json);
539
+ headers["content-type"] = "application/json";
540
+ } else if (request.body) {
541
+ body = request.body;
542
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
543
+ }
544
+ const started = Date.now();
545
+ if (request.write) env.onWriteSent();
546
+ let response;
547
+ try {
548
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
549
+ } catch (error) {
550
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
551
+ if (errorCode(error) === "URL_REFUSED") {
552
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
553
+ }
554
+ if (request.write) {
555
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
556
+ }
557
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
558
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
559
+ }
560
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
561
+ let bytes;
562
+ try {
563
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
564
+ } catch (error) {
565
+ if (request.write && (response.ok || response.status >= 500)) {
566
+ throw new OutcomeUnknown(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}), so it is not known whether the change was made.`);
567
+ }
568
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
569
+ }
570
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
571
+ if (response.ok) return { status: response.status, headers: response.headers, data };
572
+ throw failureFor(response.status, response.headers, data, request);
573
+ }
574
+ async function media(rawUrl, options) {
575
+ const { what } = options;
576
+ let url;
577
+ try {
578
+ url = new URL(rawUrl);
579
+ } catch {
580
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
581
+ }
582
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
583
+ const started = Date.now();
584
+ let response;
585
+ try {
586
+ response = await ctx.fetch(url.toString(), {
587
+ method: "GET",
588
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
589
+ ...ctx.signal ? { signal: ctx.signal } : {}
590
+ });
591
+ } catch (error) {
592
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
593
+ if (errorCode(error) === "URL_REFUSED") {
594
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
595
+ }
596
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
597
+ }
598
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
599
+ if (!response.ok) {
600
+ await response.body?.cancel().catch(() => {
601
+ });
602
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
603
+ }
604
+ try {
605
+ const bytes = await readCapped(response, options.maxBytes);
606
+ return { bytes, contentType: response.headers.get("content-type") };
607
+ } catch (error) {
608
+ if (error instanceof TooLarge) {
609
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
610
+ }
611
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
612
+ }
613
+ }
614
+ return { api, media };
615
+ }
616
+
617
+ // src/core/origins.ts
618
+ function parseSiteUrl(value) {
619
+ const text = typeof value === "string" ? value.trim() : "";
620
+ if (!text) return { ok: false, problem: "is empty" };
621
+ let url;
622
+ try {
623
+ url = new URL(text.includes("://") ? text : `https://${text}`);
624
+ } catch {
625
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
626
+ }
627
+ if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
628
+ if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
629
+ if (!url.hostname) return { ok: false, problem: "has no host name" };
630
+ return { ok: true, url, origin: url.origin };
631
+ }
632
+
633
+ // src/core/schema.ts
634
+ var patterns = /* @__PURE__ */ new Map();
635
+ function patternOf(source) {
636
+ let compiled = patterns.get(source);
637
+ if (!compiled) {
638
+ compiled = new RegExp(source, "u");
639
+ patterns.set(source, compiled);
640
+ }
641
+ return compiled;
642
+ }
643
+ function isPlainObject(value) {
644
+ return typeof value === "object" && value !== null && !Array.isArray(value);
645
+ }
646
+ function isHttpUrl(value) {
647
+ try {
648
+ const url = new URL(value);
649
+ return url.protocol === "https:" || url.protocol === "http:";
650
+ } catch {
651
+ return false;
652
+ }
653
+ }
654
+ function name(path) {
655
+ return `\`${path}\``;
656
+ }
657
+ function child(path, key) {
658
+ return path ? `${path}.${key}` : key;
659
+ }
660
+ function checkValue(schema, value, path, issues) {
661
+ switch (schema.type) {
662
+ case "object":
663
+ checkObject(schema, value, path, issues);
664
+ return;
665
+ case "array": {
666
+ if (!Array.isArray(value)) {
667
+ issues.push(`${name(path)} must be an array`);
668
+ return;
669
+ }
670
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
671
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
672
+ }
673
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
674
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
675
+ }
676
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
677
+ issues.push(`${name(path)} must not repeat an item`);
678
+ }
679
+ if (schema.items) {
680
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
681
+ }
682
+ break;
683
+ }
684
+ case "string": {
685
+ if (typeof value !== "string") {
686
+ issues.push(`${name(path)} must be a string`);
687
+ return;
688
+ }
689
+ const length = Array.from(value).length;
690
+ if (schema.minLength !== void 0 && length < schema.minLength) {
691
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
692
+ }
693
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
694
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
695
+ }
696
+ if (schema.format === "uri" && !isHttpUrl(value)) {
697
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
698
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
699
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
700
+ }
701
+ break;
702
+ }
703
+ case "integer":
704
+ case "number": {
705
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
706
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
707
+ return;
708
+ }
709
+ if (schema.minimum !== void 0 && value < schema.minimum) {
710
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
711
+ }
712
+ if (schema.maximum !== void 0 && value > schema.maximum) {
713
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
714
+ }
715
+ break;
716
+ }
717
+ case "boolean":
718
+ if (typeof value !== "boolean") {
719
+ issues.push(`${name(path)} must be true or false`);
720
+ return;
721
+ }
722
+ break;
723
+ default:
724
+ break;
725
+ }
726
+ if (schema.enum && !schema.enum.includes(value)) {
727
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
728
+ }
729
+ }
730
+ function checkObject(schema, value, path, issues) {
731
+ if (!isPlainObject(value)) {
732
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
733
+ return;
734
+ }
735
+ const properties = schema.properties ?? {};
736
+ for (const key of schema.required ?? []) {
737
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
738
+ }
739
+ const unknown = [];
740
+ for (const [key, item] of Object.entries(value)) {
741
+ const property = properties[key];
742
+ if (!property) {
743
+ if (schema.additionalProperties === false) unknown.push(key);
744
+ continue;
745
+ }
746
+ if (item === void 0 || item === null) continue;
747
+ checkValue(property, item, child(path, key), issues);
748
+ }
749
+ if (unknown.length) {
750
+ const known = Object.keys(properties);
751
+ issues.push(`unknown ${path ? `field${unknown.length > 1 ? "s" : ""} in ${name(path)}` : `argument${unknown.length > 1 ? "s" : ""}`} ${unknown.map((key) => JSON.stringify(key)).join(", ")}` + (known.length ? ` (expected: ${known.join(", ")})` : ""));
752
+ }
753
+ }
754
+ function copyDefault(value) {
755
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
756
+ }
757
+ function validateArguments(schema, args) {
758
+ const input = args === void 0 || args === null ? {} : args;
759
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
760
+ const value = { ...input };
761
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
762
+ const issues = [];
763
+ checkObject(schema, value, "", issues);
764
+ if (issues.length) return { ok: false, issues };
765
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
766
+ if (value[key] === null) delete value[key];
767
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
768
+ }
769
+ return { ok: true, value };
770
+ }
771
+
772
+ // src/core/upload-hosts.ts
773
+ var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
774
+ function uploadHostProblem(entry) {
775
+ if (typeof entry !== "string") return "must be a host name";
776
+ const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
777
+ const labels = name2.split(".");
778
+ if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
779
+ return "must be a lowercase host name like uploads.example.com, or one with a leading dot like .example.com for every host under it";
780
+ }
781
+ if (labels.length < 2) return "needs at least two labels, like example.com";
782
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
783
+ return void 0;
784
+ }
785
+
786
+ // src/core/connector.ts
787
+ var ANNOTATIONS = {
788
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
789
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
790
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
791
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
792
+ write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
793
+ };
794
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
795
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
796
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
797
+ var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
798
+ var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
799
+ var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
800
+ var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
801
+ function deepFreeze(value) {
802
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
803
+ Object.freeze(value);
804
+ for (const item of Object.values(value)) deepFreeze(item);
805
+ }
806
+ return value;
807
+ }
808
+ function assertDefinition(def) {
809
+ const problem = (message) => {
810
+ throw new Error(`connector "${def.vendor}": ${message}`);
811
+ };
812
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
813
+ if (!def.label?.trim()) problem("label is required");
814
+ const originFields = def.originFields ?? [];
815
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
816
+ for (const origin of def.origins) {
817
+ let url;
818
+ try {
819
+ url = new URL(origin);
820
+ } catch {
821
+ }
822
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
823
+ }
824
+ for (const name2 of def.credentials) {
825
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
826
+ }
827
+ for (const [index, name2] of originFields.entries()) {
828
+ if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
829
+ if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
830
+ }
831
+ const names = /* @__PURE__ */ new Set();
832
+ for (const tool of def.tools) {
833
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
834
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
835
+ names.add(tool.name);
836
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
837
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
838
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
839
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
840
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
841
+ }
842
+ }
843
+ for (const tool of def.tools) {
844
+ if (tool.kind === "read") continue;
845
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
846
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
847
+ }
848
+ assertUploadHosts(def, problem);
849
+ assertRequiredCredentials(def, problem);
850
+ assertAccountPickers(def, problem);
851
+ }
852
+ function assertUploadHosts(def, problem) {
853
+ const hosts = def.uploadHosts;
854
+ if (hosts === void 0) return;
855
+ if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
856
+ hosts.forEach((entry, index) => {
857
+ const wrong = uploadHostProblem(entry);
858
+ if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
859
+ if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
860
+ });
861
+ }
862
+ function assertRequiredCredentials(def, problem) {
863
+ const required = def.requiredCredentials;
864
+ if (required === void 0) return;
865
+ if (!Array.isArray(required) || !required.length) {
866
+ problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
867
+ }
868
+ required.forEach((list, index) => {
869
+ const which = `requiredCredentials[${index}]`;
870
+ if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
871
+ list.forEach((name2, position) => {
872
+ if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
873
+ if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
874
+ });
875
+ });
876
+ const lists = required;
877
+ lists.forEach((list, index) => {
878
+ const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
879
+ if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
880
+ if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
881
+ problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
882
+ }
883
+ });
884
+ }
885
+ function isDotPath(value) {
886
+ return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
887
+ }
888
+ function assertAccountPickers(def, problem) {
889
+ const pickers = def.accountPickers;
890
+ if (pickers === void 0) return;
891
+ if (!Array.isArray(pickers)) problem("accountPickers must be a list");
892
+ const keys = /* @__PURE__ */ new Set();
893
+ for (const item of pickers) {
894
+ if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
895
+ const picker = item;
896
+ const key = picker["key"];
897
+ if (typeof key !== "string" || !PICKER_KEY_PATTERN.test(key)) problem(`account picker ${JSON.stringify(key)}: key must match ^[a-z][a-z0-9_]{0,63}$`);
898
+ if (keys.has(key)) problem(`account picker ${key} is defined twice`);
899
+ keys.add(key);
900
+ const fail = (message) => problem(`account picker ${key}: ${message}`);
901
+ const unknown = Object.keys(picker).filter((field2) => !PICKER_FIELDS.includes(field2));
902
+ if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
903
+ const { label, description, multiple, legacyField } = picker;
904
+ if (typeof label !== "string" || !label.trim()) fail("label is required");
905
+ if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
906
+ fail("description, when given, must be a text of 1 to 1024 characters");
907
+ }
908
+ if (typeof multiple !== "boolean") fail("multiple must be true or false");
909
+ const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
910
+ if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
911
+ if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
912
+ for (const field2 of ["idField", "nameField"]) {
913
+ if (!isDotPath(picker[field2])) fail(`${field2} must be a dot path into each item the tool returns, like "id" or "account.name"`);
914
+ }
915
+ if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
916
+ fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
917
+ }
918
+ }
919
+ }
920
+ function copyPicker(picker) {
921
+ return {
922
+ key: picker.key,
923
+ label: picker.label,
924
+ ...picker.description !== void 0 ? { description: picker.description } : {},
925
+ multiple: picker.multiple,
926
+ tool: picker.tool,
927
+ idField: picker.idField,
928
+ nameField: picker.nameField,
929
+ ...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
930
+ };
931
+ }
932
+ function result(payload, isError, files = []) {
933
+ return {
934
+ content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
935
+ ...isError ? { isError: true } : {}
936
+ };
937
+ }
938
+ function failure(message, details = {}) {
939
+ return result({ error: message, ...details }, true);
940
+ }
941
+ function trimmed(values) {
942
+ const out = {};
943
+ if (typeof values !== "object" || values === null) return out;
944
+ for (const [key, value] of Object.entries(values)) {
945
+ if (value === void 0 || value === null) continue;
946
+ const text = String(value).trim();
947
+ if (text) out[key] = text;
948
+ }
949
+ return out;
950
+ }
951
+ function defineConnector(def) {
952
+ assertDefinition(def);
953
+ const { label } = def;
954
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
955
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
956
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
957
+ const required = requiredAlternatives(def);
958
+ const notConnected = (unmet) => {
959
+ const [first] = unmet;
960
+ if (unmet.length === 1 && first) {
961
+ return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
962
+ }
963
+ return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
964
+ };
965
+ const descriptors = def.tools.map((tool) => ({
966
+ name: tool.name,
967
+ title: tool.title,
968
+ description: tool.description,
969
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
970
+ annotations: { ...ANNOTATIONS[tool.kind] }
971
+ }));
972
+ async function call(toolName, args, ctx) {
973
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
974
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
975
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
976
+ const log = (text) => {
977
+ try {
978
+ ctx.log?.(text);
979
+ } catch {
980
+ }
981
+ };
982
+ const given = trimmed(ctx.credentials);
983
+ const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
984
+ const has = (name2) => Boolean(credentials[name2]);
985
+ const unmet = unmetAlternatives(required, has);
986
+ if (unmet.length) return failure(notConnected(unmet));
987
+ const complete = required.filter((list) => list.every(has));
988
+ const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
989
+ const fieldOrigins = /* @__PURE__ */ new Map();
990
+ for (const name2 of def.originFields ?? []) {
991
+ if (!given[name2] && !inUse.includes(name2)) continue;
992
+ const site = parseSiteUrl(given[name2] ?? "");
993
+ if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
994
+ fieldOrigins.set(name2, site.origin);
995
+ }
996
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
997
+ const parsed = validateArguments(tool.inputSchema, args);
998
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
999
+ const frozenCredentials = Object.freeze({ ...credentials });
1000
+ let writeSent = false;
1001
+ const fileLimit = fileLimitOf(ctx);
1002
+ const files = [];
1003
+ let fileBytes2 = 0;
1004
+ const http = createHttp({
1005
+ vendor: def.vendor,
1006
+ label,
1007
+ tool: tool.name,
1008
+ readOnly: tool.kind === "read",
1009
+ origins,
1010
+ // A 401 names the credentials in use (for a module that needs none, the ones given).
1011
+ credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
1012
+ ctx,
1013
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
1014
+ log,
1015
+ onWriteSent: () => {
1016
+ writeSent = true;
1017
+ }
1018
+ });
1019
+ const helpers = {
1020
+ tool: tool.name,
1021
+ credentials: frozenCredentials,
1022
+ ctx,
1023
+ origins: Object.freeze([...origins]),
1024
+ originOf: (credential) => {
1025
+ const origin = fieldOrigins.get(credential);
1026
+ if (!origin) throw new Error(`${credential} gives no origin in this call`);
1027
+ return origin;
1028
+ },
1029
+ api: http.api,
1030
+ media: http.media,
1031
+ page: (input) => fitPage(input),
1032
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
1033
+ makeCursor: (state) => encodeCursor(tool.name, state),
1034
+ fileLimit: () => fileLimit,
1035
+ file: ({ name: name2, mimeType, bytes }) => {
1036
+ if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
1037
+ const total = fileBytes2 + bytes.byteLength;
1038
+ if (total > fileLimit) {
1039
+ throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total)} bytes in all, more than the ${formatNumber(fileLimit)} bytes this host takes from one call.` : `The file has ${formatNumber(bytes.byteLength)} bytes, more than the ${formatNumber(fileLimit)} bytes this host takes.`);
1040
+ }
1041
+ fileBytes2 = total;
1042
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
1043
+ files.push({ ...info, bytes });
1044
+ return { ...info };
1045
+ },
1046
+ log
1047
+ };
1048
+ try {
1049
+ const data = await tool.run(parsed.value, helpers);
1050
+ const fitted = shrinkToFit(data ?? {});
1051
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
1052
+ const payload = fitted.value;
1053
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
1054
+ } catch (error) {
1055
+ if (error instanceof OutcomeUnknown) {
1056
+ return result({
1057
+ outcome: "unknown",
1058
+ check: tool.check,
1059
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
1060
+ }, true);
1061
+ }
1062
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
1063
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
1064
+ if (writeSent) {
1065
+ return result({
1066
+ outcome: "unknown",
1067
+ check: tool.check,
1068
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
1069
+ }, true);
1070
+ }
1071
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
1072
+ }
1073
+ }
1074
+ return deepFreeze({
1075
+ vendor: def.vendor,
1076
+ origins: [...def.origins],
1077
+ originFields: [...def.originFields ?? []],
1078
+ uploadHosts: [...def.uploadHosts ?? []],
1079
+ credentials: [...def.credentials],
1080
+ requiredCredentials: required.map((list) => [...list]),
1081
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
1082
+ tools: descriptors,
1083
+ call
1084
+ });
1085
+ }
1086
+
1087
+ // src/core/jwt.ts
1088
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
1089
+
1090
+ // src/vendors/kaggle/helpers.ts
1091
+ var UPLOAD_ORIGINS = ["https://storage.googleapis.com", "https://www.googleapis.com", "https://www.kaggle.com"];
1092
+ var MAX_FILE_BYTES = 25 * 1024 * 1024;
1093
+ function compact(value) {
1094
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
1095
+ }
1096
+ function field(item, name2) {
1097
+ if (!item || typeof item !== "object") return void 0;
1098
+ const value = item[name2];
1099
+ return value !== void 0 && value !== null ? value : item[`${name2}Nullable`] ?? void 0;
1100
+ }
1101
+ var NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
1102
+ function ownerSlug(value, username, what) {
1103
+ let text = String(value ?? "").trim();
1104
+ const link = /^https?:\/\/(?:www\.)?kaggle\.com\/(?:code|datasets)\/([^/?#]+)\/([^/?#]+)/i.exec(text);
1105
+ if (link) text = `${link[1]}/${link[2]}`;
1106
+ const parts = text.split("/");
1107
+ const [owner, slug] = parts.length === 1 ? [username, parts[0]] : parts.length === 2 ? parts : [void 0, void 0];
1108
+ if (!owner || !slug || !NAME.test(owner) || !NAME.test(slug)) {
1109
+ throw new ToolFailure(`The ${what} must be named "owner/slug", like janedoe/sales-forecast, or by its slug alone for your own. Nothing was sent.`);
1110
+ }
1111
+ return { owner, slug, ref: `${owner}/${slug}` };
1112
+ }
1113
+ function competitionSlug(value) {
1114
+ let text = String(value ?? "").trim();
1115
+ const link = /^https?:\/\/(?:www\.)?kaggle\.com\/(?:c|competitions)\/([^/?#]+)/i.exec(text);
1116
+ if (link?.[1]) text = link[1];
1117
+ if (!/^[A-Za-z0-9][A-Za-z0-9-]{0,99}$/.test(text)) {
1118
+ throw new ToolFailure("The competition must be named by its slug, such as titanic, or its kaggle.com link. Nothing was sent.");
1119
+ }
1120
+ return text;
1121
+ }
1122
+ function listOf(data, key) {
1123
+ if (Array.isArray(data)) return data;
1124
+ return Array.isArray(data?.[key]) ? data[key] : [];
1125
+ }
1126
+ function answerError(data) {
1127
+ if (!data || typeof data !== "object" || Array.isArray(data)) return void 0;
1128
+ if (typeof data.error === "string" && data.error.trim()) return truncate(data.error.trim(), 500);
1129
+ if (typeof data.code === "number" && data.code >= 400) return truncate(String(data.message ?? `code ${data.code}`), 500);
1130
+ return void 0;
1131
+ }
1132
+ function hours(value) {
1133
+ let seconds;
1134
+ if (typeof value === "number") seconds = value;
1135
+ else if (typeof value === "string") seconds = Number(value.replace(/s$/, ""));
1136
+ else if (value && typeof value === "object") {
1137
+ const record = value;
1138
+ seconds = Number(record.seconds ?? 0) + Number(record.nanos ?? 0) / 1e9;
1139
+ }
1140
+ return seconds !== void 0 && Number.isFinite(seconds) ? Math.round(seconds / 3600 * 10) / 10 : void 0;
1141
+ }
1142
+ function logTail(raw, maxLines, budget = 12e3) {
1143
+ let text = typeof raw === "string" ? raw : "";
1144
+ if (/^\s*\[/.test(text)) {
1145
+ try {
1146
+ const events = JSON.parse(text);
1147
+ if (Array.isArray(events)) text = events.map((event) => typeof event?.data === "string" ? event.data : "").join("");
1148
+ } catch {
1149
+ }
1150
+ }
1151
+ const all = text.split(/\r?\n/).filter((line) => line.trim() !== "");
1152
+ const lines = [];
1153
+ let used = 0;
1154
+ for (let index = all.length - 1; index >= 0 && lines.length < maxLines; index--) {
1155
+ const line = truncate(all[index], 500);
1156
+ used += utf8Length(JSON.stringify(line)) + 1;
1157
+ if (used > budget) break;
1158
+ lines.unshift(line);
1159
+ }
1160
+ return { lines, total: all.length };
1161
+ }
1162
+ async function fileBytes(h, file) {
1163
+ if (file.url === void 0 === (file.content === void 0)) {
1164
+ throw new ToolFailure(`File ${file.name}: give url or content, one of them. Nothing was created.`);
1165
+ }
1166
+ if (file.content !== void 0) return utf8Bytes(file.content);
1167
+ const { bytes } = await h.media(file.url, { what: `file ${file.name}`, maxBytes: MAX_FILE_BYTES });
1168
+ return bytes;
1169
+ }
1170
+ async function uploadFile(h, ticket, bytes, name2) {
1171
+ const { data } = await h.api({ method: "POST", path: ticket.path, json: ticket.json });
1172
+ const failed = answerError(data);
1173
+ if (failed) throw new ToolFailure(`Kaggle refused the upload of ${name2}: ${failed}. Nothing was created.`);
1174
+ const token = field(data, "token");
1175
+ const address = field(data, "createUrl");
1176
+ if (typeof token !== "string" || !token || typeof address !== "string") {
1177
+ throw new ToolFailure(`Kaggle gave no upload address for ${name2}. Nothing was created.`);
1178
+ }
1179
+ let url;
1180
+ try {
1181
+ url = new URL(address);
1182
+ } catch {
1183
+ throw new ToolFailure(`Kaggle gave an upload address for ${name2} that is not a valid URL. Nothing was created.`);
1184
+ }
1185
+ if (!UPLOAD_ORIGINS.includes(url.origin)) {
1186
+ throw new ToolFailure(`Kaggle gave an upload address on ${url.host}, where this connector does not send files. Nothing was created.`);
1187
+ }
1188
+ await h.api({
1189
+ method: "PUT",
1190
+ origin: url.origin,
1191
+ path: `${url.pathname}${url.search}`,
1192
+ body: bytes,
1193
+ contentType: "application/octet-stream",
1194
+ auth: false,
1195
+ errors: {
1196
+ 403: `The upload address Kaggle gave refused ${name2}`,
1197
+ 404: `The upload address Kaggle gave for ${name2} has expired: try again`
1198
+ }
1199
+ });
1200
+ return token;
1201
+ }
1202
+ async function uploadAll(h, files, ticketFor) {
1203
+ const names = /* @__PURE__ */ new Set();
1204
+ for (const file of files) {
1205
+ if (names.has(file.name)) throw new ToolFailure(`The file name ${file.name} is given twice. Nothing was created.`);
1206
+ names.add(file.name);
1207
+ }
1208
+ const uploaded = [];
1209
+ for (const file of files) {
1210
+ const bytes = await fileBytes(h, file);
1211
+ if (!bytes.length) throw new ToolFailure(`File ${file.name} is empty. Nothing was created.`);
1212
+ const token = await uploadFile(h, ticketFor(file, bytes.length), bytes, file.name);
1213
+ uploaded.push({ token, file, size: bytes.length });
1214
+ }
1215
+ return uploaded;
1216
+ }
1217
+ function textOf(bytes, name2) {
1218
+ const head = bytes.subarray(0, 8192);
1219
+ if (head.includes(0)) {
1220
+ throw new ToolFailure(`${name2} is a binary file, which is not shown here: open it from the notebook's Output tab on Kaggle.`);
1221
+ }
1222
+ return utf8Decode(bytes);
1223
+ }
1224
+ var TEXT_WINDOW_BYTES = 24e3;
1225
+ function textWindow(text, offset, budget = TEXT_WINDOW_BYTES) {
1226
+ const start = Math.max(0, Math.min(Math.floor(offset), text.length));
1227
+ const rest = text.length - start;
1228
+ const size = (count2) => utf8Length(JSON.stringify(text.slice(start, start + count2)));
1229
+ let count = Math.min(rest, budget);
1230
+ if (size(count) > budget) {
1231
+ let low = 0;
1232
+ let high = count;
1233
+ while (low < high) {
1234
+ const middle = Math.ceil((low + high) / 2);
1235
+ if (size(middle) <= budget) low = middle;
1236
+ else high = middle - 1;
1237
+ }
1238
+ count = low;
1239
+ }
1240
+ if (count < rest) {
1241
+ const lineBreak = text.lastIndexOf("\n", start + count - 1);
1242
+ if (lineBreak >= start + Math.floor(count / 2)) count = lineBreak + 1 - start;
1243
+ const code = text.charCodeAt(start + count - 1);
1244
+ if (code >= 55296 && code <= 56319) count -= 1;
1245
+ }
1246
+ const end = start + Math.max(count, 0);
1247
+ return { text: text.slice(start, end), offset: start, ...end < text.length ? { next: end } : {} };
1248
+ }
1249
+
1250
+ // src/vendors/kaggle/index.ts
1251
+ var API = "/api/v1";
1252
+ var LARGE_REPLY_BYTES = 8 * 1024 * 1024;
1253
+ var MACHINES = {
1254
+ none: { enableGpu: false, enableTpu: false },
1255
+ gpu_t4x2: { machineShape: "NvidiaTeslaT4", enableGpu: true, enableTpu: false },
1256
+ gpu_l4: { machineShape: "NvidiaL4", enableGpu: true, enableTpu: false },
1257
+ tpu_v5e8: { machineShape: "TpuV5E8", enableGpu: false, enableTpu: true }
1258
+ };
1259
+ var LICENSES = ["CC0-1.0", "CC-BY-4.0", "CC-BY-SA-4.0", "CC-BY-NC-SA-4.0", "ODbL-1.0", "GPL-2.0", "other", "unknown"];
1260
+ var NOTEBOOK_REF = { type: "string", minLength: 1, maxLength: 300, description: 'The notebook as "owner/slug" (its ref), its slug alone for your own, or its kaggle.com link.' };
1261
+ var DATASET_REF = { type: "string", minLength: 1, maxLength: 300, description: 'The dataset as "owner/slug", its slug alone for your own, or its kaggle.com link.' };
1262
+ var COMPETITION = { type: "string", minLength: 1, maxLength: 300, description: "The competition's slug, such as titanic, or its kaggle.com link." };
1263
+ var CURSOR_SCHEMA = { type: "string", description: "nextCursor from the previous result; pass the same other arguments again." };
1264
+ var SOURCES = (example, what) => ({
1265
+ type: "array",
1266
+ maxItems: 50,
1267
+ uniqueItems: true,
1268
+ items: { type: "string", minLength: 1, maxLength: 300 },
1269
+ description: `${what}, e.g. ["${example}"]. They appear in the run under /kaggle/input/.`
1270
+ });
1271
+ var FILE_SCHEMA = {
1272
+ type: "object",
1273
+ properties: {
1274
+ name: { type: "string", pattern: "^[^/\\\\]{1,255}$", description: "The file name on Kaggle, e.g. sales.csv." },
1275
+ url: { type: "string", format: "uri", maxLength: 2e3, description: "A public https URL to download the file from (up to 25 MB)." },
1276
+ content: { type: "string", maxLength: 1e6, description: "Or the file's text itself (up to 1,000,000 characters)." },
1277
+ description: { type: "string", maxLength: 1e3, description: "What the file holds." }
1278
+ },
1279
+ required: ["name"],
1280
+ additionalProperties: false,
1281
+ description: "A file from a public https URL (up to 25 MB) or as text: give url or content."
1282
+ };
1283
+ var FILES_SCHEMA = {
1284
+ type: "array",
1285
+ minItems: 1,
1286
+ maxItems: 20,
1287
+ items: FILE_SCHEMA,
1288
+ description: "The files, each from a public https URL or as text (up to 20 per call, 25 MB each)."
1289
+ };
1290
+ function cursorPage(h, cursor) {
1291
+ const state = h.cursor(cursor);
1292
+ return {
1293
+ page: typeof state?.["p"] === "number" ? state["p"] : 1,
1294
+ ...typeof state?.["k"] === "string" && state["k"] ? { token: state["k"] } : {},
1295
+ skip: typeof state?.["o"] === "number" ? state["o"] : 0
1296
+ };
1297
+ }
1298
+ function kagglePage(h, key, data, items, at, pageSize, extra) {
1299
+ const nextToken = !Array.isArray(data) && typeof data?.nextPageToken === "string" && data.nextPageToken ? data.nextPageToken : void 0;
1300
+ const here = { p: at.page, ...at.token ? { k: at.token } : {} };
1301
+ const next = nextToken ? { p: at.page + 1, k: nextToken, o: 0 } : items.length >= pageSize ? { p: at.page + 1, o: 0 } : void 0;
1302
+ return h.page({
1303
+ key,
1304
+ items: items.slice(at.skip),
1305
+ ...extra ? { extra } : {},
1306
+ resumeAt: (index) => h.makeCursor({ ...here, o: at.skip + index }),
1307
+ ...next ? { nextPage: h.makeCursor(next) } : {}
1308
+ });
1309
+ }
1310
+ function trimNotebook(item) {
1311
+ const ref = field(item, "ref");
1312
+ const private_ = field(item, "isPrivate");
1313
+ return compact({
1314
+ ref,
1315
+ title: field(item, "title"),
1316
+ url: typeof ref === "string" ? `https://www.kaggle.com/code/${ref}` : void 0,
1317
+ last_run: field(item, "lastRunTime"),
1318
+ language: field(item, "language"),
1319
+ type: field(item, "kernelType"),
1320
+ visibility: private_ === true ? "private" : private_ === false ? "public" : void 0,
1321
+ gpu: field(item, "enableGpu"),
1322
+ tpu: field(item, "enableTpu"),
1323
+ machine: field(item, "machineShape"),
1324
+ internet: field(item, "enableInternet"),
1325
+ votes: field(item, "totalVotes"),
1326
+ version: field(item, "currentVersionNumber")
1327
+ });
1328
+ }
1329
+ function trimDataset(item) {
1330
+ const ref = field(item, "ref");
1331
+ const private_ = field(item, "isPrivate");
1332
+ const usability = field(item, "usabilityRating");
1333
+ return compact({
1334
+ ref,
1335
+ title: field(item, "title"),
1336
+ url: typeof ref === "string" ? `https://www.kaggle.com/datasets/${ref}` : void 0,
1337
+ size_bytes: field(item, "totalBytes"),
1338
+ updated: field(item, "lastUpdated"),
1339
+ visibility: private_ === true ? "private" : private_ === false ? "public" : void 0,
1340
+ downloads: field(item, "downloadCount"),
1341
+ votes: field(item, "voteCount"),
1342
+ version: field(item, "currentVersionNumber"),
1343
+ usability: typeof usability === "number" ? Math.round(usability * 100) / 10 : void 0,
1344
+ license: field(item, "licenseName")
1345
+ });
1346
+ }
1347
+ function quotaRow(quota) {
1348
+ if (!quota || typeof quota !== "object") return void 0;
1349
+ const used = hours(field(quota, "timeUsed"));
1350
+ const reserved = hours(field(quota, "timeReserved"));
1351
+ const allowed = hours(field(quota, "totalTimeAllowed"));
1352
+ const left = used !== void 0 && allowed !== void 0 ? Math.max(0, Math.round((allowed - used - (reserved ?? 0)) * 10) / 10) : void 0;
1353
+ return compact({ used_hours: used, reserved_hours: reserved, left_hours: left, weekly_hours: allowed, extra_hours_enabled: field(quota, "isPayToScaleEnabled") === true });
1354
+ }
1355
+ var refused = (data) => {
1356
+ const lists = compact({
1357
+ datasets: field(data, "invalidDatasetSources"),
1358
+ competitions: field(data, "invalidCompetitionSources"),
1359
+ notebooks: field(data, "invalidKernelSources"),
1360
+ models: field(data, "invalidModelSources"),
1361
+ tags: field(data, "invalidTags")
1362
+ });
1363
+ const nonEmpty = Object.fromEntries(Object.entries(lists).filter(([, value]) => Array.isArray(value) && value.length));
1364
+ return Object.keys(nonEmpty).length ? nonEmpty : void 0;
1365
+ };
1366
+ async function findOutputFile(h, owner, slug, name2) {
1367
+ let token;
1368
+ for (let page = 0; page < 10; page++) {
1369
+ const { data } = await h.api({ path: `${API}/kernels/output`, query: { userName: owner, kernelSlug: slug, pageSize: 100, pageToken: token }, maxBytes: LARGE_REPLY_BYTES });
1370
+ const failed = answerError(data);
1371
+ if (failed) throw new ToolFailure(`Kaggle refused to list the output: ${failed}.`);
1372
+ for (const file of listOf(data, "files")) {
1373
+ if (field(file, "fileName") === name2 && typeof field(file, "url") === "string") return { name: name2, url: field(file, "url") };
1374
+ }
1375
+ token = typeof data?.nextPageToken === "string" && data.nextPageToken ? data.nextPageToken : void 0;
1376
+ if (!token) break;
1377
+ }
1378
+ return void 0;
1379
+ }
1380
+ var connector = defineConnector({
1381
+ vendor: "kaggle",
1382
+ label: "Kaggle",
1383
+ origins: ["https://www.kaggle.com", ...UPLOAD_ORIGINS.filter((origin) => origin !== "https://www.kaggle.com")],
1384
+ credentials: ["username", "apitoken"],
1385
+ credentialLabels: { username: "Kaggle username", apitoken: "Kaggle API token" },
1386
+ normalizeCredentials: (credentials) => {
1387
+ const username = (credentials["username"] ?? "").replace(/^https?:\/\/(?:www\.)?kaggle\.com\//i, "").replace(/^@/, "").split(/[/?#]/)[0] ?? "";
1388
+ return { ...credentials, username, apitoken: (credentials["apitoken"] ?? "").replace(/^Bearer\s+/i, "") };
1389
+ },
1390
+ authHeaders: (credentials) => {
1391
+ const token = credentials["apitoken"];
1392
+ if (/^[0-9a-f]{32}$/i.test(token)) return { authorization: `Basic ${btoa(`${credentials["username"]}:${token}`)}` };
1393
+ return { authorization: `Bearer ${token}` };
1394
+ },
1395
+ tools: [
1396
+ {
1397
+ name: "get_quota",
1398
+ kind: "read",
1399
+ title: "Get my Kaggle GPU and TPU quota",
1400
+ description: "The weekly GPU and TPU allowance of the account, in hours: used, held by running sessions, left, the weekly total, and when it refreshes. Check it before a GPU or TPU run. It also confirms the token works.",
1401
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1402
+ async run(_args, h) {
1403
+ const { data } = await h.api({ path: `${API}/kernels/quota` });
1404
+ return compact({ gpu: quotaRow(field(data, "gpuQuota")), tpu: quotaRow(field(data, "tpuQuota")), refreshes_at: field(data, "quotaRefreshTime") });
1405
+ }
1406
+ },
1407
+ {
1408
+ name: "list_notebooks",
1409
+ kind: "read",
1410
+ title: "List Kaggle notebooks",
1411
+ description: "Your own notebooks, last run first by default, with their ref, link, language, type, visibility, accelerator, internet, votes and current version; or someone's public notebooks with scope everyone and user. Pass nextCursor back as cursor for more.",
1412
+ inputSchema: {
1413
+ type: "object",
1414
+ properties: {
1415
+ scope: { type: "string", enum: ["mine", "everyone"], default: "mine", description: "mine (default) or everyone (public notebooks; narrow with user or search)." },
1416
+ user: { type: "string", pattern: "^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$", description: "A username whose public notebooks to list (with scope everyone)." },
1417
+ search: { type: "string", maxLength: 200, description: "Words to search for." },
1418
+ kernel_type: { type: "string", enum: ["notebook", "script"], description: "Only notebooks or only scripts." },
1419
+ language: { type: "string", enum: ["python", "r", "sqlite", "julia"], description: "Only this language." },
1420
+ sort_by: {
1421
+ type: "string",
1422
+ enum: ["dateRun", "dateCreated", "voteCount", "viewCount", "hotness", "commentCount", "scoreDescending", "scoreAscending", "relevance"],
1423
+ default: "dateRun",
1424
+ description: "The order (default dateRun; relevance needs search)."
1425
+ },
1426
+ page_size: { type: "integer", minimum: 1, maximum: 100, default: 20, description: "Notebooks per page, 1 to 100 (default 20)." },
1427
+ cursor: CURSOR_SCHEMA
1428
+ },
1429
+ additionalProperties: false
1430
+ },
1431
+ async run(args, h) {
1432
+ const at = cursorPage(h, args.cursor);
1433
+ const { data } = await h.api({
1434
+ path: `${API}/kernels/list`,
1435
+ query: {
1436
+ group: args.scope === "mine" ? "profile" : "everyone",
1437
+ user: args.user,
1438
+ search: args.search,
1439
+ kernelType: args.kernel_type,
1440
+ language: args.language,
1441
+ sortBy: args.sort_by,
1442
+ pageSize: args.page_size,
1443
+ page: at.token ? void 0 : at.page,
1444
+ pageToken: at.token
1445
+ }
1446
+ });
1447
+ const notebooks = listOf(data, "kernels").map(trimNotebook);
1448
+ return kagglePage(h, "notebooks", data, notebooks, at, args.page_size);
1449
+ }
1450
+ },
1451
+ {
1452
+ name: "get_notebook",
1453
+ kind: "read",
1454
+ title: "Get a Kaggle notebook and its code",
1455
+ description: "One notebook's settings (language, type, visibility, accelerator, internet, data sources, version) and its code: the script, or the whole notebook JSON, in windows of about 24 KB. Pass nextCursor back as cursor for the next part of the code.",
1456
+ inputSchema: {
1457
+ type: "object",
1458
+ properties: {
1459
+ notebook: NOTEBOOK_REF,
1460
+ include_code: { type: "boolean", default: true, description: "Return the code too (default true)." },
1461
+ cursor: CURSOR_SCHEMA
1462
+ },
1463
+ required: ["notebook"],
1464
+ additionalProperties: false
1465
+ },
1466
+ async run(args, h) {
1467
+ const { owner, slug } = ownerSlug(args.notebook, h.credentials["username"], "notebook");
1468
+ const { data } = await h.api({ path: `${API}/kernels/pull`, query: { userName: owner, kernelSlug: slug }, maxBytes: LARGE_REPLY_BYTES, errors: { 404: "Kaggle found no notebook with that name that this account can see" } });
1469
+ const failed = answerError(data);
1470
+ if (failed) throw new ToolFailure(`Kaggle refused to read the notebook: ${failed}.`);
1471
+ const metadata = field(data, "metadata") ?? {};
1472
+ const result2 = {
1473
+ ...trimNotebook(metadata),
1474
+ ref: field(metadata, "ref") ?? `${owner}/${slug}`,
1475
+ dataset_sources: field(metadata, "datasetDataSources"),
1476
+ competition_sources: field(metadata, "competitionDataSources"),
1477
+ notebook_sources: field(metadata, "kernelDataSources"),
1478
+ model_sources: field(metadata, "modelDataSources")
1479
+ };
1480
+ if (args.include_code) {
1481
+ const blob = field(data, "blob") ?? {};
1482
+ const source = typeof field(blob, "source") === "string" ? field(blob, "source") : "";
1483
+ const state = h.cursor(args.cursor);
1484
+ const window = textWindow(source, typeof state?.["o"] === "number" ? state["o"] : 0, TEXT_WINDOW_BYTES);
1485
+ result2["code"] = window.text;
1486
+ result2["code_length"] = source.length;
1487
+ if (window.offset) result2["code_offset"] = window.offset;
1488
+ if (window.next !== void 0) result2["nextCursor"] = h.makeCursor({ o: window.next });
1489
+ }
1490
+ return compact(result2);
1491
+ }
1492
+ },
1493
+ {
1494
+ name: "push_notebook",
1495
+ kind: "create",
1496
+ check: "get_notebook",
1497
+ title: "Push a Kaggle notebook",
1498
+ description: "Creates a notebook, or saves a new version of an existing one, and runs it unless run is false. It is private, on CPU and without internet unless asked: a GPU or TPU uses the weekly quota (get_quota), and GPU and internet need a phone-verified account. For a new notebook the slug must be the title in lowercase with dashes. Each push is a new version; check the run with get_notebook_status.",
1499
+ inputSchema: {
1500
+ type: "object",
1501
+ properties: {
1502
+ notebook: NOTEBOOK_REF,
1503
+ title: { type: "string", minLength: 5, maxLength: 50, description: "The title, at least 5 characters (renaming changes the slug)." },
1504
+ code: { type: "string", minLength: 1, maxLength: 1e6, description: 'The script, or the whole notebook as nbformat 4 JSON (code cells with "outputs": []).' },
1505
+ kernel_type: { type: "string", enum: ["script", "notebook"], default: "script", description: "script (default) or notebook; fixed once the notebook exists." },
1506
+ language: { type: "string", enum: ["python", "r", "rmarkdown"], default: "python", description: "python (default), r or rmarkdown." },
1507
+ private: { type: "boolean", default: true, description: "true (default). false makes it public: anyone can see and copy it." },
1508
+ accelerator: {
1509
+ type: "string",
1510
+ enum: ["none", "gpu_t4x2", "gpu_l4", "tpu_v5e8"],
1511
+ default: "none",
1512
+ description: "none (CPU, default), gpu_t4x2 (two T4 GPUs), gpu_l4, or tpu_v5e8. A GPU or TPU uses the weekly quota."
1513
+ },
1514
+ internet: { type: "boolean", default: false, description: "Let the code reach the internet (default false), e.g. to install packages." },
1515
+ dataset_sources: SOURCES("janedoe/sales-2026", 'Datasets as "owner/slug"'),
1516
+ competition_sources: SOURCES("titanic", "Competitions you joined, by slug"),
1517
+ notebook_sources: SOURCES("janedoe/feature-prep", `Other notebooks' output, as "owner/slug"`),
1518
+ model_sources: SOURCES("janedoe/my-model/pytorch/base", 'Models as "owner/model/framework/variation", a version number at the end to pin one'),
1519
+ run: { type: "boolean", default: true, description: "true (default) saves and runs; false saves a version without running it." },
1520
+ session_timeout_seconds: { type: "integer", minimum: 60, maximum: 43200, description: "Stop the run after this many seconds (Kaggle's own limit is 12 hours, 9 on TPU)." }
1521
+ },
1522
+ required: ["notebook", "title", "code"],
1523
+ additionalProperties: false
1524
+ },
1525
+ async run(args, h) {
1526
+ const { ref } = ownerSlug(args.notebook, h.credentials["username"], "notebook");
1527
+ const machine = MACHINES[args.accelerator] ?? MACHINES["none"];
1528
+ const { data } = await h.api({
1529
+ method: "POST",
1530
+ path: `${API}/kernels/push`,
1531
+ json: compact({
1532
+ slug: ref,
1533
+ newTitle: args.title,
1534
+ text: args.code,
1535
+ language: args.language,
1536
+ kernelType: args.kernel_type,
1537
+ isPrivate: args.private,
1538
+ enableGpu: machine.enableGpu,
1539
+ enableTpu: machine.enableTpu,
1540
+ machineShape: machine.machineShape,
1541
+ enableInternet: args.internet,
1542
+ datasetDataSources: args.dataset_sources ?? [],
1543
+ competitionDataSources: args.competition_sources ?? [],
1544
+ kernelDataSources: args.notebook_sources ?? [],
1545
+ modelDataSources: args.model_sources ?? [],
1546
+ categoryIds: [],
1547
+ kernelExecutionType: args.run ? void 0 : "QUICK_SAVE",
1548
+ sessionTimeoutSeconds: args.session_timeout_seconds
1549
+ }),
1550
+ write: true
1551
+ });
1552
+ const failed = answerError(data);
1553
+ const version = field(data, "versionNumber");
1554
+ if (failed && version === void 0) throw new ToolFailure(`Kaggle did not save the notebook: ${failed}. Nothing was changed.`);
1555
+ return compact({
1556
+ saved: true,
1557
+ ref: field(data, "ref") ?? ref,
1558
+ url: field(data, "url"),
1559
+ version,
1560
+ run: args.run ? "started: check it with get_notebook_status" : "not started (saved without running)",
1561
+ refused_sources: refused(data),
1562
+ warning: failed
1563
+ });
1564
+ }
1565
+ },
1566
+ {
1567
+ name: "get_notebook_status",
1568
+ kind: "read",
1569
+ title: "Get a Kaggle notebook run's status",
1570
+ description: "The status of the notebook's latest run: queued, running, complete, error, or cancelled, with Kaggle's failure message on error. Runs take minutes to hours: check again later rather than in a loop.",
1571
+ inputSchema: {
1572
+ type: "object",
1573
+ properties: { notebook: NOTEBOOK_REF },
1574
+ required: ["notebook"],
1575
+ additionalProperties: false
1576
+ },
1577
+ async run(args, h) {
1578
+ const { owner, slug, ref } = ownerSlug(args.notebook, h.credentials["username"], "notebook");
1579
+ const { data } = await h.api({ path: `${API}/kernels/status`, query: { userName: owner, kernelSlug: slug }, errors: { 404: "Kaggle found no notebook with that name that this account can see" } });
1580
+ const status = typeof data === "string" ? data : field(data, "status");
1581
+ const message = field(data, "failureMessage");
1582
+ return compact({ ref, status: typeof status === "string" ? status.toLowerCase() : void 0, failure_message: message ? truncate(String(message), 2e3) : void 0 });
1583
+ }
1584
+ },
1585
+ {
1586
+ name: "get_notebook_output",
1587
+ kind: "read",
1588
+ title: "Get a Kaggle notebook's output and log",
1589
+ description: "The output files of the notebook's latest run (names and signed download links that expire soon) and the last lines of its log. read_notebook_output_file shows a text file's contents. Pass nextCursor back as cursor for more files.",
1590
+ inputSchema: {
1591
+ type: "object",
1592
+ properties: {
1593
+ notebook: NOTEBOOK_REF,
1594
+ log_lines: { type: "integer", minimum: 0, maximum: 400, default: 40, description: "How many log lines to show from the end (default 40)." },
1595
+ page_size: { type: "integer", minimum: 1, maximum: 100, default: 20, description: "Files per page, 1 to 100 (default 20)." },
1596
+ cursor: CURSOR_SCHEMA
1597
+ },
1598
+ required: ["notebook"],
1599
+ additionalProperties: false
1600
+ },
1601
+ async run(args, h) {
1602
+ const { owner, slug, ref } = ownerSlug(args.notebook, h.credentials["username"], "notebook");
1603
+ const at = cursorPage(h, args.cursor);
1604
+ const { data } = await h.api({
1605
+ path: `${API}/kernels/output`,
1606
+ query: { userName: owner, kernelSlug: slug, pageSize: args.page_size, pageToken: at.token },
1607
+ maxBytes: LARGE_REPLY_BYTES,
1608
+ errors: { 404: "Kaggle found no notebook with that name that this account can see" }
1609
+ });
1610
+ const failed = answerError(data);
1611
+ if (failed) throw new ToolFailure(`Kaggle refused to list the output: ${failed}.`);
1612
+ const files = listOf(data, "files").map((file) => compact({ name: field(file, "fileName"), url: field(file, "url") }));
1613
+ const log = at.page === 1 && args.log_lines > 0 ? logTail(field(data, "log"), args.log_lines) : void 0;
1614
+ const extra = compact({ ref, log_tail: log?.lines, log_lines_total: log?.total });
1615
+ const nextToken = typeof data?.nextPageToken === "string" && data.nextPageToken ? data.nextPageToken : void 0;
1616
+ return h.page({
1617
+ key: "files",
1618
+ items: files.slice(at.skip),
1619
+ extra,
1620
+ resumeAt: (index) => h.makeCursor({ p: at.page, ...at.token ? { k: at.token } : {}, o: at.skip + index }),
1621
+ ...nextToken ? { nextPage: h.makeCursor({ p: at.page + 1, k: nextToken, o: 0 }) } : {}
1622
+ });
1623
+ }
1624
+ },
1625
+ {
1626
+ name: "read_notebook_output_file",
1627
+ kind: "read",
1628
+ title: "Read a Kaggle notebook output file",
1629
+ description: "Shows a text output file of the notebook's latest run (a CSV of results, a log, a JSON file), in windows of about 24 KB: pass nextCursor back as cursor for the next part. Files up to 8 MB; binary files are not shown.",
1630
+ inputSchema: {
1631
+ type: "object",
1632
+ properties: {
1633
+ notebook: NOTEBOOK_REF,
1634
+ file_name: { type: "string", minLength: 1, maxLength: 500, description: "The file name as get_notebook_output lists it." },
1635
+ cursor: CURSOR_SCHEMA
1636
+ },
1637
+ required: ["notebook", "file_name"],
1638
+ additionalProperties: false
1639
+ },
1640
+ async run(args, h) {
1641
+ const { owner, slug, ref } = ownerSlug(args.notebook, h.credentials["username"], "notebook");
1642
+ const file = await findOutputFile(h, owner, slug, args.file_name);
1643
+ if (!file) throw new ToolFailure(`The latest run of ${ref} has no output file named ${args.file_name}: get_notebook_output lists them.`);
1644
+ const { bytes } = await h.media(file.url, { what: "output file", maxBytes: 8 * 1024 * 1024 });
1645
+ const text = textOf(bytes, args.file_name);
1646
+ const state = h.cursor(args.cursor);
1647
+ const window = textWindow(text, typeof state?.["o"] === "number" ? state["o"] : 0, TEXT_WINDOW_BYTES);
1648
+ return compact({
1649
+ ref,
1650
+ file_name: args.file_name,
1651
+ size_bytes: bytes.length,
1652
+ text: window.text,
1653
+ offset: window.offset || void 0,
1654
+ length: text.length,
1655
+ nextCursor: window.next !== void 0 ? h.makeCursor({ o: window.next }) : void 0
1656
+ });
1657
+ }
1658
+ },
1659
+ {
1660
+ name: "list_datasets",
1661
+ kind: "read",
1662
+ title: "List Kaggle datasets",
1663
+ description: "Your own datasets, last updated first by default, with ref, link, size, visibility, downloads, votes, version and usability; or public datasets (scope public, with search) or one user's (user). Pass nextCursor back as cursor for more.",
1664
+ inputSchema: {
1665
+ type: "object",
1666
+ properties: {
1667
+ scope: { type: "string", enum: ["mine", "public"], default: "mine", description: "mine (default) or public; ignored with user." },
1668
+ search: { type: "string", maxLength: 200, description: "Words to search for (with scope public, or within one user's datasets)." },
1669
+ user: { type: "string", pattern: "^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$", description: "Only this user's or organization's public datasets." },
1670
+ sort_by: { type: "string", enum: ["updated", "hottest", "votes", "active", "published"], default: "updated", description: "The order (default updated)." },
1671
+ page_size: { type: "integer", minimum: 1, maximum: 100, default: 20, description: "Datasets per page, 1 to 100 (default 20)." },
1672
+ cursor: CURSOR_SCHEMA
1673
+ },
1674
+ additionalProperties: false
1675
+ },
1676
+ async run(args, h) {
1677
+ const at = cursorPage(h, args.cursor);
1678
+ const { data } = await h.api({
1679
+ path: `${API}/datasets/list`,
1680
+ query: {
1681
+ // Kaggle's own client sends group user with user: without it the user filter does not pick the list.
1682
+ group: args.user ? "user" : args.scope === "mine" ? "my" : "public",
1683
+ user: args.user,
1684
+ search: args.search,
1685
+ sortBy: args.sort_by,
1686
+ pageSize: args.page_size,
1687
+ page: at.token ? void 0 : at.page,
1688
+ pageToken: at.token
1689
+ }
1690
+ });
1691
+ const datasets = listOf(data, "datasets").map(trimDataset);
1692
+ return kagglePage(h, "datasets", data, datasets, at, Array.isArray(data) ? Math.min(args.page_size, 20) : args.page_size);
1693
+ }
1694
+ },
1695
+ {
1696
+ name: "list_dataset_files",
1697
+ kind: "read",
1698
+ title: "List a Kaggle dataset's files",
1699
+ description: "The files of a dataset (its current version, or a given one), with their names, sizes and dates. Pass nextCursor back as cursor for more.",
1700
+ inputSchema: {
1701
+ type: "object",
1702
+ properties: {
1703
+ dataset: DATASET_REF,
1704
+ version: { type: "integer", minimum: 1, description: "A version number (default: the current one)." },
1705
+ cursor: CURSOR_SCHEMA
1706
+ },
1707
+ required: ["dataset"],
1708
+ additionalProperties: false
1709
+ },
1710
+ async run(args, h) {
1711
+ const { owner, slug, ref } = ownerSlug(args.dataset, h.credentials["username"], "dataset");
1712
+ const at = cursorPage(h, args.cursor);
1713
+ const { data } = await h.api({
1714
+ path: `${API}/datasets/list/${encodeURIComponent(owner)}/${encodeURIComponent(slug)}`,
1715
+ query: { datasetVersionNumber: args.version, pageSize: 100, pageToken: at.token },
1716
+ errors: { 404: "Kaggle found no dataset with that name that this account can see" }
1717
+ });
1718
+ const failed = answerError(data);
1719
+ if (failed) throw new ToolFailure(`Kaggle refused to list the files: ${failed}.`);
1720
+ const files = listOf(data, "datasetFiles").map((file) => compact({ name: field(file, "name"), size_bytes: field(file, "totalBytes"), created: field(file, "creationDate") }));
1721
+ const nextToken = typeof data?.nextPageToken === "string" && data.nextPageToken ? data.nextPageToken : void 0;
1722
+ return h.page({
1723
+ key: "files",
1724
+ items: files.slice(at.skip),
1725
+ extra: { ref },
1726
+ resumeAt: (index) => h.makeCursor({ p: at.page, ...at.token ? { k: at.token } : {}, o: at.skip + index }),
1727
+ ...nextToken ? { nextPage: h.makeCursor({ p: at.page + 1, k: nextToken, o: 0 }) } : {}
1728
+ });
1729
+ }
1730
+ },
1731
+ {
1732
+ name: "get_dataset_status",
1733
+ kind: "read",
1734
+ title: "Get a Kaggle dataset's status",
1735
+ description: "Whether a dataset (after a create or a new version) is still processing or ready. Large files can take minutes.",
1736
+ inputSchema: {
1737
+ type: "object",
1738
+ properties: { dataset: DATASET_REF },
1739
+ required: ["dataset"],
1740
+ additionalProperties: false
1741
+ },
1742
+ async run(args, h) {
1743
+ const { owner, slug, ref } = ownerSlug(args.dataset, h.credentials["username"], "dataset");
1744
+ const { data } = await h.api({
1745
+ path: `${API}/datasets/status/${encodeURIComponent(owner)}/${encodeURIComponent(slug)}`,
1746
+ errors: { 404: "Kaggle found no dataset with that name that this account can see" }
1747
+ });
1748
+ const status = typeof data === "string" ? data : field(data, "status");
1749
+ return compact({ ref, status: typeof status === "string" ? status.toLowerCase() : void 0 });
1750
+ }
1751
+ },
1752
+ {
1753
+ name: "create_dataset",
1754
+ kind: "create",
1755
+ check: "list_datasets",
1756
+ title: "Create a Kaggle dataset",
1757
+ description: "Creates a dataset from files given by public https URL or as text: each file is uploaded to the signed address Kaggle hands out, then the dataset is created, private unless asked. A public dataset needs a license the owner chose; anyone can then see and copy it. Check processing with get_dataset_status.",
1758
+ inputSchema: {
1759
+ type: "object",
1760
+ properties: {
1761
+ slug: { type: "string", pattern: "^[a-z0-9][a-z0-9-]{5,49}$", description: "The dataset slug, 6 to 50 lowercase letters, digits and dashes; one in use is refused." },
1762
+ title: { type: "string", minLength: 6, maxLength: 50, description: "The title, 6 to 50 characters." },
1763
+ subtitle: { type: "string", minLength: 20, maxLength: 80, description: "A subtitle, 20 to 80 characters." },
1764
+ description: { type: "string", maxLength: 2e4, description: "Where the data comes from and what each column means (Markdown)." },
1765
+ license: { type: "string", enum: LICENSES, default: "unknown", description: "The license (default unknown, for a private dataset)." },
1766
+ private: { type: "boolean", default: true, description: "true (default). false makes it public." },
1767
+ owner: { type: "string", pattern: "^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$", description: "An organization to own it (default: your account)." },
1768
+ files: FILES_SCHEMA
1769
+ },
1770
+ required: ["slug", "title", "files"],
1771
+ additionalProperties: false
1772
+ },
1773
+ async run(args, h) {
1774
+ if (!args.private && args.license === "unknown") {
1775
+ throw new ToolFailure("A public dataset needs a license the owner chose (license). Nothing was created.");
1776
+ }
1777
+ const uploaded = await uploadAll(h, args.files, (file, size) => ({
1778
+ path: `${API}/blobs/upload`,
1779
+ json: { type: "DATASET", name: file.name, contentLength: size, lastModifiedEpochSeconds: Math.floor(Date.now() / 1e3) }
1780
+ }));
1781
+ const owner = args.owner ?? h.credentials["username"];
1782
+ const { data } = await h.api({
1783
+ method: "POST",
1784
+ path: `${API}/datasets/create/new`,
1785
+ json: compact({
1786
+ ownerSlug: owner,
1787
+ slug: args.slug,
1788
+ title: args.title,
1789
+ subtitle: args.subtitle,
1790
+ description: args.description,
1791
+ licenseName: args.license,
1792
+ isPrivate: args.private,
1793
+ files: uploaded.map((item) => compact({ token: item.token, description: item.file.description }))
1794
+ }),
1795
+ write: true
1796
+ });
1797
+ const failed = answerError(data);
1798
+ if (failed) throw new ToolFailure(`Kaggle did not create the dataset: ${failed}. Nothing was created.`);
1799
+ return compact({
1800
+ created: true,
1801
+ ref: field(data, "ref") ?? `${owner}/${args.slug}`,
1802
+ url: field(data, "url"),
1803
+ status: typeof field(data, "status") === "string" ? String(field(data, "status")).toLowerCase() : void 0,
1804
+ visibility: args.private ? "private" : "public",
1805
+ files: uploaded.map((item) => ({ name: item.file.name, size_bytes: item.size })),
1806
+ refused_tags: field(data, "invalidTags")?.length ? field(data, "invalidTags") : void 0
1807
+ });
1808
+ }
1809
+ },
1810
+ {
1811
+ // A write: with delete_old_versions it also deletes every earlier version for good, so it is annotated destructive.
1812
+ name: "create_dataset_version",
1813
+ kind: "write",
1814
+ check: "get_dataset_status",
1815
+ title: "Upload a new Kaggle dataset version",
1816
+ description: "Uploads a new version of a dataset. Kaggle builds the version from the files sent with it, so send every file the dataset should keep. delete_old_versions removes every earlier version for good: only when the owner asked for exactly that. Check processing with get_dataset_status.",
1817
+ inputSchema: {
1818
+ type: "object",
1819
+ properties: {
1820
+ dataset: DATASET_REF,
1821
+ version_notes: { type: "string", minLength: 1, maxLength: 1e3, description: "What changed in this version." },
1822
+ files: FILES_SCHEMA,
1823
+ delete_old_versions: { type: "boolean", default: false, description: "true deletes every earlier version for good (default false)." }
1824
+ },
1825
+ required: ["dataset", "version_notes", "files"],
1826
+ additionalProperties: false
1827
+ },
1828
+ async run(args, h) {
1829
+ const { owner, slug, ref } = ownerSlug(args.dataset, h.credentials["username"], "dataset");
1830
+ const uploaded = await uploadAll(h, args.files, (file, size) => ({
1831
+ path: `${API}/blobs/upload`,
1832
+ json: { type: "DATASET", name: file.name, contentLength: size, lastModifiedEpochSeconds: Math.floor(Date.now() / 1e3) }
1833
+ }));
1834
+ const { data } = await h.api({
1835
+ method: "POST",
1836
+ path: `${API}/datasets/create/version/${encodeURIComponent(owner)}/${encodeURIComponent(slug)}`,
1837
+ json: {
1838
+ versionNotes: args.version_notes,
1839
+ deleteOldVersions: args.delete_old_versions,
1840
+ files: uploaded.map((item) => compact({ token: item.token, description: item.file.description }))
1841
+ },
1842
+ write: true,
1843
+ errors: { 404: "Kaggle found no dataset with that name that this account may change" }
1844
+ });
1845
+ const failed = answerError(data);
1846
+ if (failed) throw new ToolFailure(`Kaggle did not create the version: ${failed}. Nothing was created.`);
1847
+ return compact({
1848
+ created: true,
1849
+ ref: field(data, "ref") ?? ref,
1850
+ url: field(data, "url"),
1851
+ status: typeof field(data, "status") === "string" ? String(field(data, "status")).toLowerCase() : void 0,
1852
+ files: uploaded.map((item) => ({ name: item.file.name, size_bytes: item.size }))
1853
+ });
1854
+ }
1855
+ },
1856
+ {
1857
+ name: "list_competitions",
1858
+ kind: "read",
1859
+ title: "List Kaggle competitions",
1860
+ description: "Competitions matching some words, latest deadline first by default, with category, reward, deadline, teams, whether you entered and whether it takes notebook submissions only. group entered lists the ones you joined, community the ones Kaggle users host, and hosted your own. Pass nextCursor back as cursor for more.",
1861
+ inputSchema: {
1862
+ type: "object",
1863
+ properties: {
1864
+ search: { type: "string", maxLength: 200, description: "Words to search for." },
1865
+ group: {
1866
+ type: "string",
1867
+ enum: ["general", "entered", "community", "hosted"],
1868
+ description: "general (the main list), entered (the ones you joined), community (community competitions, which Kaggle users host) or hosted (the ones you host)."
1869
+ },
1870
+ category: { type: "string", enum: ["featured", "research", "recruitment", "gettingStarted", "masters", "playground"], description: "Only this category." },
1871
+ sort_by: {
1872
+ type: "string",
1873
+ enum: ["latestDeadline", "earliestDeadline", "prize", "numberOfTeams", "recentlyCreated", "grouped", "best", "relevance"],
1874
+ default: "latestDeadline",
1875
+ description: "The order (default latestDeadline)."
1876
+ },
1877
+ cursor: CURSOR_SCHEMA
1878
+ },
1879
+ additionalProperties: false
1880
+ },
1881
+ async run(args, h) {
1882
+ const at = cursorPage(h, args.cursor);
1883
+ const { data } = await h.api({
1884
+ path: `${API}/competitions/list`,
1885
+ query: { search: args.search, group: args.group, category: args.category, sortBy: args.sort_by, page: at.token ? void 0 : at.page, pageToken: at.token }
1886
+ });
1887
+ const competitions = listOf(data, "competitions").map((item) => {
1888
+ const ref = String(field(item, "ref") ?? field(item, "url") ?? "");
1889
+ const slug = ref.replace(/\/+$/, "").split("/").pop() || void 0;
1890
+ return compact({
1891
+ slug,
1892
+ title: field(item, "title"),
1893
+ url: slug ? `https://www.kaggle.com/competitions/${slug}` : void 0,
1894
+ category: field(item, "category"),
1895
+ reward: field(item, "reward"),
1896
+ deadline: field(item, "deadline"),
1897
+ teams: field(item, "teamCount"),
1898
+ entered: field(item, "userHasEntered"),
1899
+ notebooks_only: field(item, "isKernelsSubmissionsOnly"),
1900
+ max_daily_submissions: field(item, "maxDailySubmissions")
1901
+ });
1902
+ });
1903
+ return kagglePage(h, "competitions", data, competitions, at, 20);
1904
+ }
1905
+ },
1906
+ {
1907
+ name: "get_leaderboard",
1908
+ kind: "read",
1909
+ title: "Get a Kaggle competition leaderboard",
1910
+ description: "The top of a competition's public leaderboard: rank, team, score and submission date.",
1911
+ inputSchema: {
1912
+ type: "object",
1913
+ properties: {
1914
+ competition: COMPETITION,
1915
+ top: { type: "integer", minimum: 1, maximum: 200, default: 20, description: "How many rows, 1 to 200 (default 20)." }
1916
+ },
1917
+ required: ["competition"],
1918
+ additionalProperties: false
1919
+ },
1920
+ async run(args, h) {
1921
+ const slug = competitionSlug(args.competition);
1922
+ const { data } = await h.api({ path: `${API}/competitions/${encodeURIComponent(slug)}/leaderboard/view`, errors: { 404: "Kaggle found no competition with that slug" } });
1923
+ const rows = listOf(data, "submissions");
1924
+ return {
1925
+ competition: slug,
1926
+ rows: rows.slice(0, args.top).map((row, index) => compact({ rank: index + 1, team: field(row, "teamName"), score: field(row, "score"), submitted: field(row, "submissionDate") })),
1927
+ total_on_page: rows.length
1928
+ };
1929
+ }
1930
+ },
1931
+ {
1932
+ name: "list_submissions",
1933
+ kind: "read",
1934
+ title: "List my Kaggle competition submissions",
1935
+ description: "Your submissions to a competition, newest first, with file, date, status, public and private scores and description. Pass nextCursor back as cursor for more.",
1936
+ inputSchema: {
1937
+ type: "object",
1938
+ properties: { competition: COMPETITION, cursor: CURSOR_SCHEMA },
1939
+ required: ["competition"],
1940
+ additionalProperties: false
1941
+ },
1942
+ async run(args, h) {
1943
+ const slug = competitionSlug(args.competition);
1944
+ const at = cursorPage(h, args.cursor);
1945
+ const { data } = await h.api({
1946
+ path: `${API}/competitions/submissions/list/${encodeURIComponent(slug)}`,
1947
+ query: { page: at.token ? void 0 : at.page, pageToken: at.token },
1948
+ errors: { 404: "Kaggle found no competition with that slug" }
1949
+ });
1950
+ const submissions = listOf(data, "submissions").map((item) => compact({
1951
+ ref: field(item, "ref"),
1952
+ file: field(item, "fileName"),
1953
+ date: field(item, "date"),
1954
+ status: typeof field(item, "status") === "string" ? String(field(item, "status")).toLowerCase() : void 0,
1955
+ public_score: field(item, "publicScore"),
1956
+ private_score: field(item, "privateScore"),
1957
+ description: field(item, "description"),
1958
+ error: field(item, "errorDescription")
1959
+ }));
1960
+ return kagglePage(h, "submissions", data, submissions, at, 20, { competition: slug });
1961
+ }
1962
+ },
1963
+ {
1964
+ name: "submit_to_competition",
1965
+ kind: "create",
1966
+ check: "list_submissions",
1967
+ title: "Submit a file to a Kaggle competition",
1968
+ description: "Sends a submission file (from a public https URL or as text) to a competition: Kaggle hands out an upload address, the file goes there, then the submission is made. It uses one of the day's submissions. You must have joined the competition and accepted its rules on kaggle.com first; the API cannot. Read the score later with list_submissions.",
1969
+ inputSchema: {
1970
+ type: "object",
1971
+ properties: {
1972
+ competition: COMPETITION,
1973
+ file: FILE_SCHEMA,
1974
+ description: { type: "string", minLength: 1, maxLength: 1e3, description: 'What this submission is, e.g. "Gradient boosting, 5 folds".' }
1975
+ },
1976
+ required: ["competition", "file", "description"],
1977
+ additionalProperties: false
1978
+ },
1979
+ async run(args, h) {
1980
+ const slug = competitionSlug(args.competition);
1981
+ const [uploaded] = await uploadAll(h, [args.file], (file, size) => ({
1982
+ path: `${API}/competitions/submission-url`,
1983
+ json: { competitionName: slug, fileName: file.name, contentLength: size, lastModifiedEpochSeconds: Math.floor(Date.now() / 1e3) }
1984
+ }));
1985
+ const { data } = await h.api({
1986
+ method: "POST",
1987
+ path: `${API}/competitions/submissions/submit/${encodeURIComponent(slug)}`,
1988
+ json: { blobFileTokens: uploaded.token, submissionDescription: args.description },
1989
+ write: true,
1990
+ errors: { 403: "Kaggle refused the submission: join the competition and accept its rules on kaggle.com first" }
1991
+ });
1992
+ const failed = answerError(data);
1993
+ if (failed) throw new ToolFailure(`Kaggle did not take the submission: ${failed}. Nothing was submitted.`);
1994
+ return compact({ submitted: true, competition: slug, ref: field(data, "ref"), message: field(data, "message") });
1995
+ }
1996
+ },
1997
+ {
1998
+ name: "submit_notebook_to_competition",
1999
+ kind: "create",
2000
+ check: "list_submissions",
2001
+ title: "Submit a notebook version to a Kaggle competition",
2002
+ description: "For a code competition: submits a version of one of your notebooks and the output file it writes. It uses one of the day's submissions; you must have joined the competition and accepted its rules on kaggle.com first.",
2003
+ inputSchema: {
2004
+ type: "object",
2005
+ properties: {
2006
+ competition: COMPETITION,
2007
+ notebook: NOTEBOOK_REF,
2008
+ version: { type: "integer", minimum: 1, description: "The notebook version to submit." },
2009
+ file_name: { type: "string", minLength: 1, maxLength: 255, description: "The output file to score, e.g. submission.csv." },
2010
+ description: { type: "string", minLength: 1, maxLength: 1e3, description: "What this submission is." }
2011
+ },
2012
+ required: ["competition", "notebook", "version", "file_name", "description"],
2013
+ additionalProperties: false
2014
+ },
2015
+ async run(args, h) {
2016
+ const slug = competitionSlug(args.competition);
2017
+ const { owner, slug: kernel } = ownerSlug(args.notebook, h.credentials["username"], "notebook");
2018
+ const { data } = await h.api({
2019
+ method: "POST",
2020
+ path: `${API}/competitions/submissions/submit-notebook/${encodeURIComponent(slug)}`,
2021
+ json: { kernelOwner: owner, kernelSlug: kernel, kernelVersion: args.version, fileName: args.file_name, submissionDescription: args.description },
2022
+ write: true,
2023
+ errors: { 403: "Kaggle refused the submission: join the competition and accept its rules on kaggle.com first" }
2024
+ });
2025
+ const failed = answerError(data);
2026
+ if (failed) throw new ToolFailure(`Kaggle did not take the submission: ${failed}. Nothing was submitted.`);
2027
+ return compact({ submitted: true, competition: slug, ref: field(data, "ref"), message: field(data, "message") });
2028
+ }
2029
+ },
2030
+ // The rest of the Kaggle API v1: models, dataset metadata, kernel sessions, competition data files.
2031
+ ...apiTools({
2032
+ label: "Kaggle",
2033
+ description: "The Kaggle API v1 at https://www.kaggle.com/api/v1, with the connected token: paths start with /api/v1/, such as /api/v1/datasets/metadata/{owner}/{slug}, /api/v1/competitions/data/list/{slug} or /api/v1/models/list. Deleting notebooks, datasets or models is not offered here. Reference: https://www.kaggle.com/docs/api.",
2034
+ basePath: "/api/v1/",
2035
+ guard(request) {
2036
+ if (request.method !== "GET" && request.segments.some((segment) => segment.toLowerCase().includes("delete"))) {
2037
+ throw new ToolFailure("Deleting on Kaggle is not offered here: delete it on kaggle.com itself. Nothing was sent.");
2038
+ }
2039
+ }
2040
+ })
2041
+ ]
2042
+ });
2043
+ module.exports = connector;