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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1131 -34
  3. package/dist/cli.js +15 -12
  4. package/dist/core/credentials.d.ts +21 -0
  5. package/dist/core/credentials.js +45 -0
  6. package/dist/core/origins.d.ts +18 -0
  7. package/dist/core/origins.js +40 -0
  8. package/dist/core/upload-hosts.d.ts +15 -0
  9. package/dist/core/upload-hosts.js +43 -0
  10. package/dist/host/describe.d.ts +10 -0
  11. package/dist/host/describe.js +38 -0
  12. package/dist/host/env.d.ts +25 -2
  13. package/dist/host/env.js +24 -7
  14. package/dist/host/guarded-fetch.d.ts +36 -9
  15. package/dist/host/guarded-fetch.js +175 -52
  16. package/dist/host/index.d.ts +8 -5
  17. package/dist/host/index.js +12 -1
  18. package/dist/host/load.js +31 -1
  19. package/dist/host/server.d.ts +13 -2
  20. package/dist/host/server.js +15 -2
  21. package/dist/types.d.ts +96 -5
  22. package/dist/vendors/adapty.js +1303 -0
  23. package/dist/vendors/adjust.js +1372 -0
  24. package/dist/vendors/apollo.js +2499 -0
  25. package/dist/vendors/apple-appstore.js +2798 -0
  26. package/dist/vendors/beehiiv.js +1965 -0
  27. package/dist/vendors/blogger.js +1687 -0
  28. package/dist/vendors/bluesky.js +850 -127
  29. package/dist/vendors/brevo.js +2195 -0
  30. package/dist/vendors/calendarific.js +1116 -0
  31. package/dist/vendors/devto.js +685 -92
  32. package/dist/vendors/facebook-pages.js +2185 -0
  33. package/dist/vendors/firebase.js +1333 -0
  34. package/dist/vendors/ga4.js +1585 -0
  35. package/dist/vendors/gmail.js +1962 -0
  36. package/dist/vendors/google-ads.js +2201 -0
  37. package/dist/vendors/google-business.js +1621 -0
  38. package/dist/vendors/google-calendar.js +1936 -0
  39. package/dist/vendors/google-drive.js +2654 -0
  40. package/dist/vendors/google-merchant-center.js +1742 -0
  41. package/dist/vendors/google-play.js +1856 -0
  42. package/dist/vendors/google-search-console.js +1572 -0
  43. package/dist/vendors/hashnode.js +1722 -0
  44. package/dist/vendors/instagram.js +2249 -0
  45. package/dist/vendors/kaggle.js +2043 -0
  46. package/dist/vendors/keepa.js +2087 -0
  47. package/dist/vendors/linkedin.js +1588 -0
  48. package/dist/vendors/mailchimp.js +2402 -0
  49. package/dist/vendors/mastodon.js +1836 -0
  50. package/dist/vendors/meta-ads.js +2375 -0
  51. package/dist/vendors/notion.js +1950 -0
  52. package/dist/vendors/pinterest.js +1744 -0
  53. package/dist/vendors/qiita.js +1552 -0
  54. package/dist/vendors/reddit.js +1791 -0
  55. package/dist/vendors/revenuecat.js +1593 -0
  56. package/dist/vendors/roasit.js +1460 -0
  57. package/dist/vendors/sendgrid.js +2188 -0
  58. package/dist/vendors/serper.js +901 -179
  59. package/dist/vendors/shopify.js +2511 -0
  60. package/dist/vendors/threads.js +1869 -0
  61. package/dist/vendors/tiktok.js +2199 -0
  62. package/dist/vendors/tumblr.js +1793 -0
  63. package/dist/vendors/twitter.js +1650 -0
  64. package/dist/vendors/woocommerce.js +2258 -0
  65. package/dist/vendors/wordpress.js +1904 -0
  66. package/dist/vendors/youtube.js +2542 -0
  67. package/package.json +1 -1
@@ -0,0 +1,1791 @@
1
+ /* reddit connector module (MIT License). Built from src/vendors/reddit; do not edit. */
2
+ "use strict";
3
+
4
+ // src/core/errors.ts
5
+ var ToolFailure = class extends Error {
6
+ details;
7
+ constructor(message, details = {}) {
8
+ super(message);
9
+ this.name = "ToolFailure";
10
+ this.details = details;
11
+ }
12
+ };
13
+ var OutcomeUnknown = class extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "OutcomeUnknown";
17
+ }
18
+ };
19
+
20
+ // src/core/accounts.ts
21
+ function allowedAccounts(accounts, key) {
22
+ if (accounts === null) return null;
23
+ const list = accounts?.[key];
24
+ return Array.isArray(list) ? list.map(String) : [];
25
+ }
26
+ function requireAccounts(accounts, key, ids, label = "account") {
27
+ const allowed = allowedAccounts(accounts, key);
28
+ if (allowed === null) return;
29
+ const requested = (Array.isArray(ids) ? ids : [ids]).map(String);
30
+ const refused = requested.filter((id) => !allowed.includes(id));
31
+ if (!refused.length) return;
32
+ throw new ToolFailure(
33
+ `The ${label} ${refused.join(", ")} ${refused.length > 1 ? "are" : "is"} not among the ${label}s chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`) + " Nothing was sent."
34
+ );
35
+ }
36
+
37
+ // src/core/text.ts
38
+ var encoder = new TextEncoder();
39
+ var decoder = new TextDecoder();
40
+ function utf8Bytes(text) {
41
+ return encoder.encode(text);
42
+ }
43
+ function utf8Length(text) {
44
+ return encoder.encode(text).length;
45
+ }
46
+ function utf8Decode(bytes) {
47
+ return decoder.decode(bytes);
48
+ }
49
+ function base64Encode(bytes) {
50
+ let binary = "";
51
+ for (let i = 0; i < bytes.length; i += 32768) {
52
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
53
+ }
54
+ return btoa(binary);
55
+ }
56
+ function base64UrlEncode(bytes) {
57
+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
58
+ }
59
+ function base64UrlDecode(text) {
60
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
61
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
62
+ const binary = atob(padded);
63
+ const bytes = new Uint8Array(binary.length);
64
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
65
+ return bytes;
66
+ }
67
+ async function sha256Hex(text) {
68
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(text)));
69
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
70
+ }
71
+ function truncate(text, max) {
72
+ if (text.length <= max) return text;
73
+ const points = Array.from(text);
74
+ if (points.length <= max) return text;
75
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
76
+ }
77
+ function cleanVendorText(text, max = 300) {
78
+ if (typeof text !== "string") return void 0;
79
+ if (/^\s*</.test(text)) return void 0;
80
+ const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
81
+ return line ? truncate(line, max) : void 0;
82
+ }
83
+ function formatNumber(value) {
84
+ return value.toLocaleString("en-US");
85
+ }
86
+
87
+ // src/core/output.ts
88
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
89
+ function jsonSize(value) {
90
+ return utf8Length(JSON.stringify(value) ?? "");
91
+ }
92
+ function cutStrings(value, max) {
93
+ if (typeof value === "string") return truncate(value, max);
94
+ if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
95
+ if (typeof value === "object" && value !== null) {
96
+ const out = {};
97
+ for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
98
+ return out;
99
+ }
100
+ return value;
101
+ }
102
+ function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
103
+ if (jsonSize(value) <= limit) return { value, truncated: false };
104
+ for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
105
+ const cut = cutStrings(value, max);
106
+ if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
107
+ }
108
+ return void 0;
109
+ }
110
+ function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
111
+ const build = (count) => {
112
+ const cut = count < input.items.length;
113
+ const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
114
+ const next = cut ? input.resumeAt(count) : input.nextPage;
115
+ if (next) result2["nextCursor"] = next;
116
+ if (cut) result2["truncated"] = true;
117
+ return result2;
118
+ };
119
+ const all = build(input.items.length);
120
+ if (jsonSize(all) <= limit) return all;
121
+ let low = 1;
122
+ let high = input.items.length - 1;
123
+ while (low < high) {
124
+ const middle = Math.ceil((low + high) / 2);
125
+ if (jsonSize(build(middle)) <= limit) low = middle;
126
+ else high = middle - 1;
127
+ }
128
+ const best = build(low);
129
+ if (jsonSize(best) <= limit) return best;
130
+ const shrunk = shrinkToFit(best, limit);
131
+ if (shrunk) return { ...shrunk.value, truncated: true };
132
+ throw new ToolFailure("The result is too large to return, even one item at a time.");
133
+ }
134
+ function encodeCursor(tool, state) {
135
+ return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
136
+ }
137
+ function decodeCursor(tool, cursor) {
138
+ if (cursor === void 0 || cursor === "") return null;
139
+ try {
140
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
141
+ if (typeof state === "object" && state !== null && state.t === tool) {
142
+ return state;
143
+ }
144
+ } catch {
145
+ }
146
+ throw new ToolFailure(
147
+ "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."
148
+ );
149
+ }
150
+
151
+ // src/core/api-tools.ts
152
+ var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
153
+ var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
154
+ var NOTE_ROOM = 400;
155
+ var MAX_CUT_POINTS = 4e4;
156
+ function isQueryValue(value) {
157
+ return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
158
+ }
159
+ function nothingSent(sentence) {
160
+ return new ToolFailure(`${sentence} Nothing was sent.`);
161
+ }
162
+ function fitReply(reply) {
163
+ if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
164
+ const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
165
+ if (shrunk) {
166
+ return {
167
+ ...shrunk.value,
168
+ truncated: true,
169
+ note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
170
+ };
171
+ }
172
+ const text = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
173
+ const points = Array.from(text.length > MAX_CUT_POINTS ? text.slice(0, MAX_CUT_POINTS) : text);
174
+ if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
175
+ const cut = (count) => ({
176
+ status: reply["status"],
177
+ ...reply["headers"] ? { headers: reply["headers"] } : {},
178
+ truncated: true,
179
+ 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.`,
180
+ text: points.slice(0, count).join("")
181
+ });
182
+ let low = 0;
183
+ let high = points.length;
184
+ while (low < high) {
185
+ const middle = Math.ceil((low + high) / 2);
186
+ if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
187
+ else high = middle - 1;
188
+ }
189
+ return cut(low);
190
+ }
191
+ function shapeReply(response, headerNames) {
192
+ const reply = { status: response.status };
193
+ const headers = {};
194
+ for (const name2 of headerNames) {
195
+ const value = response.headers.get(name2);
196
+ if (value) headers[name2] = truncate(value, 2e3);
197
+ }
198
+ if (Object.keys(headers).length) reply["headers"] = headers;
199
+ const type = response.headers.get("content-type") ?? "";
200
+ if (type && !TEXT_TYPES.test(type)) {
201
+ reply["contentType"] = truncate(type, 200);
202
+ reply["note"] = "The reply is a binary file and is not shown.";
203
+ return reply;
204
+ }
205
+ if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
206
+ return fitReply(reply);
207
+ }
208
+ function checkAccounts(rule, request, h) {
209
+ const label = rule.label ?? "account";
210
+ const allowed = allowedAccounts(h.ctx.accounts, rule.key);
211
+ if (allowed === null) return;
212
+ const namesNone = nothingSent(
213
+ `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.`)
214
+ );
215
+ if (rule.ids) {
216
+ const ids = rule.ids(request).map(String);
217
+ if (!ids.length) throw namesNone;
218
+ requireAccounts(h.ctx.accounts, rule.key, ids, label);
219
+ return;
220
+ }
221
+ if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
222
+ }
223
+ function apiTools(options) {
224
+ const { label, basePath } = options;
225
+ const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
226
+ const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
227
+ const base = basePath?.replace(/\/+$/, "");
228
+ const pathSchema = {
229
+ type: "string",
230
+ minLength: 1,
231
+ maxLength: 2e3,
232
+ pattern: "^(?!.*//)/[^?#]*$",
233
+ description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
234
+ };
235
+ const querySchema = {
236
+ type: "object",
237
+ description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
238
+ };
239
+ const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
240
+ async function run(method, args, h) {
241
+ let origin = h.origins[0];
242
+ if (args.origin !== void 0) {
243
+ let wanted;
244
+ try {
245
+ wanted = new URL(args.origin).origin;
246
+ } catch {
247
+ }
248
+ if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
249
+ origin = wanted;
250
+ }
251
+ const url = new URL(args.path, origin);
252
+ if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
253
+ const path = url.pathname;
254
+ if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
255
+ let segments;
256
+ try {
257
+ segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
258
+ } catch {
259
+ throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
260
+ }
261
+ if (segments[segments.length - 1] === "") segments.pop();
262
+ const query = {};
263
+ const queryLists = {};
264
+ for (const [key, value] of Object.entries(args.query ?? {})) {
265
+ if (value === void 0 || value === null) continue;
266
+ const list = Array.isArray(value) ? value : [value];
267
+ if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
268
+ query[key] = Array.isArray(value) ? list : value;
269
+ queryLists[key] = list.map(String);
270
+ }
271
+ const request = { method, origin, path, query };
272
+ if (method !== "GET") {
273
+ if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
274
+ if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
275
+ if (args.json !== void 0 && !args.content_type) {
276
+ request.json = args.json;
277
+ } else if (args.json !== void 0 || args.body !== void 0) {
278
+ request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
279
+ request.contentType = args.content_type;
280
+ }
281
+ request.write = true;
282
+ }
283
+ const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
284
+ if (options.accounts) checkAccounts(options.accounts, info, h);
285
+ await options.guard?.(info, h);
286
+ const response = options.send ? await options.send(request, h) : await h.api(request);
287
+ return shapeReply(response, headerNames);
288
+ }
289
+ return [
290
+ {
291
+ name: "api_get",
292
+ kind: "read",
293
+ title: `Call the ${label} API (GET)`,
294
+ 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.`,
295
+ inputSchema: {
296
+ type: "object",
297
+ properties: { path: pathSchema, query: querySchema, ...originSchema },
298
+ required: ["path"],
299
+ additionalProperties: false
300
+ },
301
+ run: (args, h) => run("GET", args, h)
302
+ },
303
+ {
304
+ name: "api_request",
305
+ kind: "write",
306
+ check: "api_get",
307
+ title: `Send a request to the ${label} API`,
308
+ 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.`,
309
+ inputSchema: {
310
+ type: "object",
311
+ properties: {
312
+ method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
313
+ path: pathSchema,
314
+ query: querySchema,
315
+ json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
316
+ body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
317
+ content_type: {
318
+ type: "string",
319
+ pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
320
+ maxLength: 200,
321
+ description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
322
+ },
323
+ ...originSchema
324
+ },
325
+ required: ["method", "path"],
326
+ additionalProperties: false
327
+ },
328
+ run: (args, h) => run(args.method, args, h)
329
+ }
330
+ ];
331
+ }
332
+
333
+ // src/core/credentials.ts
334
+ function requiredAlternatives(module2) {
335
+ return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
336
+ }
337
+ function unmetAlternatives(alternatives, has) {
338
+ const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
339
+ if (lacking.some((list) => list.length === 0)) return [];
340
+ return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
341
+ }
342
+ function andList(items) {
343
+ if (items.length <= 2) return items.join(" and ");
344
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
345
+ }
346
+ function orList(items) {
347
+ if (items.length <= 1) return items.join("");
348
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
349
+ }
350
+
351
+ // src/core/files.ts
352
+ var ATTACHMENT_URI = "attachment:///";
353
+ var MAX_NAME = 200;
354
+ function fileLimitOf(ctx) {
355
+ const maxBytes = ctx.files?.maxBytes;
356
+ return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
357
+ }
358
+ function fileName(name2) {
359
+ const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
360
+ const points = Array.from(clean);
361
+ if (points.length <= MAX_NAME) return clean || "file";
362
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
363
+ return points.slice(0, MAX_NAME - extension.length).join("") + extension;
364
+ }
365
+ function fileType(mimeType) {
366
+ const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
367
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
368
+ }
369
+ function resourceBlock(file) {
370
+ return {
371
+ type: "resource",
372
+ resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
373
+ };
374
+ }
375
+
376
+ // src/core/http.ts
377
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
378
+ var USER_AGENT = "agent-connectors";
379
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
380
+ function errorCode(error) {
381
+ const code = error?.code;
382
+ return typeof code === "string" ? code : void 0;
383
+ }
384
+ function describe(error) {
385
+ const name2 = error?.name;
386
+ const code = errorCode(error);
387
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
388
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
389
+ if (code === "TOO_LARGE") return "the reply was too large";
390
+ return cleanVendorText(error?.message, 200) ?? "a network error";
391
+ }
392
+ function retryAfterSeconds(headers, now = Date.now()) {
393
+ const retryAfter = headers.get("retry-after");
394
+ if (retryAfter) {
395
+ const seconds2 = Number(retryAfter);
396
+ if (Number.isFinite(seconds2) && seconds2 >= 0) return Math.ceil(seconds2);
397
+ const date = Date.parse(retryAfter);
398
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
399
+ }
400
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
401
+ if (reset) {
402
+ const value = Number(reset);
403
+ if (Number.isFinite(value) && value >= 0) {
404
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
405
+ }
406
+ }
407
+ return void 0;
408
+ }
409
+ function vendorCode(data) {
410
+ if (typeof data !== "object" || data === null) return void 0;
411
+ for (const key of ["error", "code"]) {
412
+ const value = data[key];
413
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
414
+ }
415
+ return void 0;
416
+ }
417
+ function vendorMessage(data) {
418
+ if (typeof data === "string") return cleanVendorText(data);
419
+ if (typeof data !== "object" || data === null) return void 0;
420
+ const record = data;
421
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
422
+ const value = record[key];
423
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
424
+ const nested = value?.message;
425
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
426
+ }
427
+ if (Array.isArray(record["errors"])) {
428
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
429
+ if (messages.length) return cleanVendorText(messages.join("; "));
430
+ }
431
+ return void 0;
432
+ }
433
+ var TooLarge = class extends Error {
434
+ constructor(limit) {
435
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
436
+ this.limit = limit;
437
+ }
438
+ limit;
439
+ };
440
+ async function readCapped(response, maxBytes) {
441
+ const declared = Number(response.headers.get("content-length"));
442
+ if (Number.isFinite(declared) && declared > maxBytes) {
443
+ await response.body?.cancel().catch(() => {
444
+ });
445
+ throw new TooLarge(maxBytes);
446
+ }
447
+ if (!response.body) return new Uint8Array(0);
448
+ const reader = response.body.getReader();
449
+ const chunks = [];
450
+ let total = 0;
451
+ for (; ; ) {
452
+ const { done, value } = await reader.read();
453
+ if (done) break;
454
+ total += value.byteLength;
455
+ if (total > maxBytes) {
456
+ await reader.cancel().catch(() => {
457
+ });
458
+ throw new TooLarge(maxBytes);
459
+ }
460
+ chunks.push(value);
461
+ }
462
+ const bytes = new Uint8Array(total);
463
+ let offset = 0;
464
+ for (const chunk of chunks) {
465
+ bytes.set(chunk, offset);
466
+ offset += chunk.byteLength;
467
+ }
468
+ return bytes;
469
+ }
470
+ function parseBody(bytes, contentType) {
471
+ if (bytes.length === 0) return null;
472
+ const text = utf8Decode(bytes);
473
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
474
+ try {
475
+ return JSON.parse(text);
476
+ } catch {
477
+ }
478
+ }
479
+ return text;
480
+ }
481
+ function createHttp(env) {
482
+ const { label, ctx } = env;
483
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
484
+ 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.`;
485
+ function failureFor(status, headers, data, request) {
486
+ const message = vendorMessage(data);
487
+ const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
488
+ const retryAfter = retryAfterSeconds(headers);
489
+ const code = vendorCode(data);
490
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
491
+ const custom = request.errors?.[status];
492
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
493
+ if (status >= 500) {
494
+ if (request.write) {
495
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
496
+ }
497
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
498
+ }
499
+ if (status === 429) {
500
+ return new ToolFailure(
501
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
502
+ { status, ...extra }
503
+ );
504
+ }
505
+ if (status === 401) {
506
+ return new ToolFailure(
507
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
508
+ { status, ...extra }
509
+ );
510
+ }
511
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
512
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
513
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
514
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
515
+ }
516
+ async function api(request) {
517
+ const method = request.method ?? "GET";
518
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
519
+ throw new Error(`read-only tool sent ${method}`);
520
+ }
521
+ const origin = request.origin ?? env.origins[0];
522
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
523
+ const url = new URL(request.path, origin);
524
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
525
+ for (const [key, value] of Object.entries(request.query ?? {})) {
526
+ if (value === void 0 || value === null) continue;
527
+ if (Array.isArray(value)) {
528
+ url.searchParams.delete(key);
529
+ for (const item of value) url.searchParams.append(key, String(item));
530
+ } else {
531
+ url.searchParams.set(key, String(value));
532
+ }
533
+ }
534
+ const headers = {
535
+ accept: "application/json",
536
+ "user-agent": USER_AGENT,
537
+ ...request.auth === false ? {} : env.authHeaders(),
538
+ ...request.headers
539
+ };
540
+ let body;
541
+ if (request.json !== void 0) {
542
+ body = JSON.stringify(request.json);
543
+ headers["content-type"] = "application/json";
544
+ } else if (request.body) {
545
+ body = request.body;
546
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
547
+ }
548
+ const started = Date.now();
549
+ if (request.write) env.onWriteSent();
550
+ let response;
551
+ try {
552
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
553
+ } catch (error) {
554
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
555
+ if (errorCode(error) === "URL_REFUSED") {
556
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
557
+ }
558
+ if (request.write) {
559
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
560
+ }
561
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
562
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
563
+ }
564
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
565
+ let bytes;
566
+ try {
567
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
568
+ } catch (error) {
569
+ if (request.write && (response.ok || response.status >= 500)) {
570
+ 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.`);
571
+ }
572
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
573
+ }
574
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
575
+ if (response.ok) return { status: response.status, headers: response.headers, data };
576
+ throw failureFor(response.status, response.headers, data, request);
577
+ }
578
+ async function media(rawUrl, options) {
579
+ const { what } = options;
580
+ let url;
581
+ try {
582
+ url = new URL(rawUrl);
583
+ } catch {
584
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
585
+ }
586
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
587
+ const started = Date.now();
588
+ let response;
589
+ try {
590
+ response = await ctx.fetch(url.toString(), {
591
+ method: "GET",
592
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
593
+ ...ctx.signal ? { signal: ctx.signal } : {}
594
+ });
595
+ } catch (error) {
596
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
597
+ if (errorCode(error) === "URL_REFUSED") {
598
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
599
+ }
600
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
601
+ }
602
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
603
+ if (!response.ok) {
604
+ await response.body?.cancel().catch(() => {
605
+ });
606
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
607
+ }
608
+ try {
609
+ const bytes = await readCapped(response, options.maxBytes);
610
+ return { bytes, contentType: response.headers.get("content-type") };
611
+ } catch (error) {
612
+ if (error instanceof TooLarge) {
613
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
614
+ }
615
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
616
+ }
617
+ }
618
+ return { api, media };
619
+ }
620
+
621
+ // src/core/origins.ts
622
+ function parseSiteUrl(value) {
623
+ const text = typeof value === "string" ? value.trim() : "";
624
+ if (!text) return { ok: false, problem: "is empty" };
625
+ let url;
626
+ try {
627
+ url = new URL(text.includes("://") ? text : `https://${text}`);
628
+ } catch {
629
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
630
+ }
631
+ if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
632
+ if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
633
+ if (!url.hostname) return { ok: false, problem: "has no host name" };
634
+ return { ok: true, url, origin: url.origin };
635
+ }
636
+
637
+ // src/core/schema.ts
638
+ var patterns = /* @__PURE__ */ new Map();
639
+ function patternOf(source) {
640
+ let compiled = patterns.get(source);
641
+ if (!compiled) {
642
+ compiled = new RegExp(source, "u");
643
+ patterns.set(source, compiled);
644
+ }
645
+ return compiled;
646
+ }
647
+ function isPlainObject(value) {
648
+ return typeof value === "object" && value !== null && !Array.isArray(value);
649
+ }
650
+ function isHttpUrl(value) {
651
+ try {
652
+ const url = new URL(value);
653
+ return url.protocol === "https:" || url.protocol === "http:";
654
+ } catch {
655
+ return false;
656
+ }
657
+ }
658
+ function name(path) {
659
+ return `\`${path}\``;
660
+ }
661
+ function child(path, key) {
662
+ return path ? `${path}.${key}` : key;
663
+ }
664
+ function checkValue(schema, value, path, issues) {
665
+ switch (schema.type) {
666
+ case "object":
667
+ checkObject(schema, value, path, issues);
668
+ return;
669
+ case "array": {
670
+ if (!Array.isArray(value)) {
671
+ issues.push(`${name(path)} must be an array`);
672
+ return;
673
+ }
674
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
675
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
676
+ }
677
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
678
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
679
+ }
680
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
681
+ issues.push(`${name(path)} must not repeat an item`);
682
+ }
683
+ if (schema.items) {
684
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
685
+ }
686
+ break;
687
+ }
688
+ case "string": {
689
+ if (typeof value !== "string") {
690
+ issues.push(`${name(path)} must be a string`);
691
+ return;
692
+ }
693
+ const length = Array.from(value).length;
694
+ if (schema.minLength !== void 0 && length < schema.minLength) {
695
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
696
+ }
697
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
698
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
699
+ }
700
+ if (schema.format === "uri" && !isHttpUrl(value)) {
701
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
702
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
703
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
704
+ }
705
+ break;
706
+ }
707
+ case "integer":
708
+ case "number": {
709
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
710
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
711
+ return;
712
+ }
713
+ if (schema.minimum !== void 0 && value < schema.minimum) {
714
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
715
+ }
716
+ if (schema.maximum !== void 0 && value > schema.maximum) {
717
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
718
+ }
719
+ break;
720
+ }
721
+ case "boolean":
722
+ if (typeof value !== "boolean") {
723
+ issues.push(`${name(path)} must be true or false`);
724
+ return;
725
+ }
726
+ break;
727
+ default:
728
+ break;
729
+ }
730
+ if (schema.enum && !schema.enum.includes(value)) {
731
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
732
+ }
733
+ }
734
+ function checkObject(schema, value, path, issues) {
735
+ if (!isPlainObject(value)) {
736
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
737
+ return;
738
+ }
739
+ const properties = schema.properties ?? {};
740
+ for (const key of schema.required ?? []) {
741
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
742
+ }
743
+ const unknown = [];
744
+ for (const [key, item] of Object.entries(value)) {
745
+ const property = properties[key];
746
+ if (!property) {
747
+ if (schema.additionalProperties === false) unknown.push(key);
748
+ continue;
749
+ }
750
+ if (item === void 0 || item === null) continue;
751
+ checkValue(property, item, child(path, key), issues);
752
+ }
753
+ if (unknown.length) {
754
+ const known = Object.keys(properties);
755
+ 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(", ")})` : ""));
756
+ }
757
+ }
758
+ function copyDefault(value) {
759
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
760
+ }
761
+ function validateArguments(schema, args) {
762
+ const input = args === void 0 || args === null ? {} : args;
763
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
764
+ const value = { ...input };
765
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
766
+ const issues = [];
767
+ checkObject(schema, value, "", issues);
768
+ if (issues.length) return { ok: false, issues };
769
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
770
+ if (value[key] === null) delete value[key];
771
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
772
+ }
773
+ return { ok: true, value };
774
+ }
775
+
776
+ // src/core/upload-hosts.ts
777
+ var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
778
+ function uploadHostProblem(entry) {
779
+ if (typeof entry !== "string") return "must be a host name";
780
+ const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
781
+ const labels = name2.split(".");
782
+ if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
783
+ 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";
784
+ }
785
+ if (labels.length < 2) return "needs at least two labels, like example.com";
786
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
787
+ return void 0;
788
+ }
789
+
790
+ // src/core/connector.ts
791
+ var ANNOTATIONS = {
792
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
793
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
794
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
795
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
796
+ write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
797
+ };
798
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
799
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
800
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
801
+ var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
802
+ var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
803
+ var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
804
+ var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
805
+ function deepFreeze(value) {
806
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
807
+ Object.freeze(value);
808
+ for (const item of Object.values(value)) deepFreeze(item);
809
+ }
810
+ return value;
811
+ }
812
+ function assertDefinition(def) {
813
+ const problem = (message) => {
814
+ throw new Error(`connector "${def.vendor}": ${message}`);
815
+ };
816
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
817
+ if (!def.label?.trim()) problem("label is required");
818
+ const originFields = def.originFields ?? [];
819
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
820
+ for (const origin of def.origins) {
821
+ let url;
822
+ try {
823
+ url = new URL(origin);
824
+ } catch {
825
+ }
826
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
827
+ }
828
+ for (const name2 of def.credentials) {
829
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
830
+ }
831
+ for (const [index, name2] of originFields.entries()) {
832
+ if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
833
+ if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
834
+ }
835
+ const names = /* @__PURE__ */ new Set();
836
+ for (const tool of def.tools) {
837
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
838
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
839
+ names.add(tool.name);
840
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
841
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
842
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
843
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
844
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
845
+ }
846
+ }
847
+ for (const tool of def.tools) {
848
+ if (tool.kind === "read") continue;
849
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
850
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
851
+ }
852
+ assertUploadHosts(def, problem);
853
+ assertRequiredCredentials(def, problem);
854
+ assertAccountPickers(def, problem);
855
+ }
856
+ function assertUploadHosts(def, problem) {
857
+ const hosts = def.uploadHosts;
858
+ if (hosts === void 0) return;
859
+ if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
860
+ hosts.forEach((entry, index) => {
861
+ const wrong = uploadHostProblem(entry);
862
+ if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
863
+ if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
864
+ });
865
+ }
866
+ function assertRequiredCredentials(def, problem) {
867
+ const required = def.requiredCredentials;
868
+ if (required === void 0) return;
869
+ if (!Array.isArray(required) || !required.length) {
870
+ problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
871
+ }
872
+ required.forEach((list, index) => {
873
+ const which = `requiredCredentials[${index}]`;
874
+ if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
875
+ list.forEach((name2, position) => {
876
+ if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
877
+ if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
878
+ });
879
+ });
880
+ const lists = required;
881
+ lists.forEach((list, index) => {
882
+ const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
883
+ if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
884
+ if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
885
+ problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
886
+ }
887
+ });
888
+ }
889
+ function isDotPath(value) {
890
+ return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
891
+ }
892
+ function assertAccountPickers(def, problem) {
893
+ const pickers = def.accountPickers;
894
+ if (pickers === void 0) return;
895
+ if (!Array.isArray(pickers)) problem("accountPickers must be a list");
896
+ const keys = /* @__PURE__ */ new Set();
897
+ for (const item of pickers) {
898
+ if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
899
+ const picker = item;
900
+ const key = picker["key"];
901
+ 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}$`);
902
+ if (keys.has(key)) problem(`account picker ${key} is defined twice`);
903
+ keys.add(key);
904
+ const fail = (message) => problem(`account picker ${key}: ${message}`);
905
+ const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
906
+ if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
907
+ const { label, description, multiple, legacyField } = picker;
908
+ if (typeof label !== "string" || !label.trim()) fail("label is required");
909
+ if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
910
+ fail("description, when given, must be a text of 1 to 1024 characters");
911
+ }
912
+ if (typeof multiple !== "boolean") fail("multiple must be true or false");
913
+ const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
914
+ if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
915
+ if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
916
+ for (const field of ["idField", "nameField"]) {
917
+ if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
918
+ }
919
+ if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
920
+ fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
921
+ }
922
+ }
923
+ }
924
+ function copyPicker(picker) {
925
+ return {
926
+ key: picker.key,
927
+ label: picker.label,
928
+ ...picker.description !== void 0 ? { description: picker.description } : {},
929
+ multiple: picker.multiple,
930
+ tool: picker.tool,
931
+ idField: picker.idField,
932
+ nameField: picker.nameField,
933
+ ...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
934
+ };
935
+ }
936
+ function result(payload, isError, files = []) {
937
+ return {
938
+ content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
939
+ ...isError ? { isError: true } : {}
940
+ };
941
+ }
942
+ function failure(message, details = {}) {
943
+ return result({ error: message, ...details }, true);
944
+ }
945
+ function trimmed(values) {
946
+ const out = {};
947
+ if (typeof values !== "object" || values === null) return out;
948
+ for (const [key, value] of Object.entries(values)) {
949
+ if (value === void 0 || value === null) continue;
950
+ const text = String(value).trim();
951
+ if (text) out[key] = text;
952
+ }
953
+ return out;
954
+ }
955
+ function defineConnector(def) {
956
+ assertDefinition(def);
957
+ const { label } = def;
958
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
959
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
960
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
961
+ const required = requiredAlternatives(def);
962
+ const notConnected = (unmet) => {
963
+ const [first] = unmet;
964
+ if (unmet.length === 1 && first) {
965
+ return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
966
+ }
967
+ return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
968
+ };
969
+ const descriptors = def.tools.map((tool) => ({
970
+ name: tool.name,
971
+ title: tool.title,
972
+ description: tool.description,
973
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
974
+ annotations: { ...ANNOTATIONS[tool.kind] }
975
+ }));
976
+ async function call(toolName, args, ctx) {
977
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
978
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
979
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
980
+ const log = (text) => {
981
+ try {
982
+ ctx.log?.(text);
983
+ } catch {
984
+ }
985
+ };
986
+ const given = trimmed(ctx.credentials);
987
+ const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
988
+ const has = (name2) => Boolean(credentials[name2]);
989
+ const unmet = unmetAlternatives(required, has);
990
+ if (unmet.length) return failure(notConnected(unmet));
991
+ const complete = required.filter((list) => list.every(has));
992
+ const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
993
+ const fieldOrigins = /* @__PURE__ */ new Map();
994
+ for (const name2 of def.originFields ?? []) {
995
+ if (!given[name2] && !inUse.includes(name2)) continue;
996
+ const site = parseSiteUrl(given[name2] ?? "");
997
+ if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
998
+ fieldOrigins.set(name2, site.origin);
999
+ }
1000
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
1001
+ const parsed = validateArguments(tool.inputSchema, args);
1002
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
1003
+ const frozenCredentials = Object.freeze({ ...credentials });
1004
+ let writeSent = false;
1005
+ const fileLimit = fileLimitOf(ctx);
1006
+ const files = [];
1007
+ let fileBytes = 0;
1008
+ const http = createHttp({
1009
+ vendor: def.vendor,
1010
+ label,
1011
+ tool: tool.name,
1012
+ readOnly: tool.kind === "read",
1013
+ origins,
1014
+ // A 401 names the credentials in use (for a module that needs none, the ones given).
1015
+ credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
1016
+ ctx,
1017
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
1018
+ log,
1019
+ onWriteSent: () => {
1020
+ writeSent = true;
1021
+ }
1022
+ });
1023
+ const helpers = {
1024
+ tool: tool.name,
1025
+ credentials: frozenCredentials,
1026
+ ctx,
1027
+ origins: Object.freeze([...origins]),
1028
+ originOf: (credential) => {
1029
+ const origin = fieldOrigins.get(credential);
1030
+ if (!origin) throw new Error(`${credential} gives no origin in this call`);
1031
+ return origin;
1032
+ },
1033
+ api: http.api,
1034
+ media: http.media,
1035
+ page: (input) => fitPage(input),
1036
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
1037
+ makeCursor: (state) => encodeCursor(tool.name, state),
1038
+ fileLimit: () => fileLimit,
1039
+ file: ({ name: name2, mimeType, bytes }) => {
1040
+ if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
1041
+ const total = fileBytes + bytes.byteLength;
1042
+ if (total > fileLimit) {
1043
+ 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.`);
1044
+ }
1045
+ fileBytes = total;
1046
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
1047
+ files.push({ ...info, bytes });
1048
+ return { ...info };
1049
+ },
1050
+ log
1051
+ };
1052
+ try {
1053
+ const data = await tool.run(parsed.value, helpers);
1054
+ const fitted = shrinkToFit(data ?? {});
1055
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
1056
+ const payload = fitted.value;
1057
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
1058
+ } catch (error) {
1059
+ if (error instanceof OutcomeUnknown) {
1060
+ return result({
1061
+ outcome: "unknown",
1062
+ check: tool.check,
1063
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
1064
+ }, true);
1065
+ }
1066
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
1067
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
1068
+ if (writeSent) {
1069
+ return result({
1070
+ outcome: "unknown",
1071
+ check: tool.check,
1072
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
1073
+ }, true);
1074
+ }
1075
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
1076
+ }
1077
+ }
1078
+ return deepFreeze({
1079
+ vendor: def.vendor,
1080
+ origins: [...def.origins],
1081
+ originFields: [...def.originFields ?? []],
1082
+ uploadHosts: [...def.uploadHosts ?? []],
1083
+ credentials: [...def.credentials],
1084
+ requiredCredentials: required.map((list) => [...list]),
1085
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
1086
+ tools: descriptors,
1087
+ call
1088
+ });
1089
+ }
1090
+
1091
+ // src/core/jwt.ts
1092
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
1093
+
1094
+ // src/vendors/reddit/guard.ts
1095
+ var HOUR = 60 * 60 * 1e3;
1096
+ var LEDGER_TTL_MS = 48 * HOUR;
1097
+ var MAX_LEDGER_ROWS = 500;
1098
+ var MAX_CONNECTIONS = 64;
1099
+ var rates = /* @__PURE__ */ new Map();
1100
+ async function connectionKey(h) {
1101
+ const developer = String(h.credentials["developerprofileusername"] ?? "").toLowerCase();
1102
+ return sha256Hex(`reddit-connection
1103
+ ${developer}
1104
+ ${String(h.credentials["access_token"] ?? "")}`);
1105
+ }
1106
+ function stateFor(key) {
1107
+ let state = rates.get(key);
1108
+ if (!state) {
1109
+ while (rates.size >= MAX_CONNECTIONS) {
1110
+ const oldest = rates.keys().next().value;
1111
+ if (oldest === void 0) break;
1112
+ rates.delete(oldest);
1113
+ }
1114
+ state = { cooldownUntil: 0, writeCooldownUntil: 0, queue: Promise.resolve() };
1115
+ rates.set(key, state);
1116
+ }
1117
+ return state;
1118
+ }
1119
+ function headerNumber(headers, name2) {
1120
+ const value = headers.get(name2);
1121
+ if (value === null || value.trim() === "") return void 0;
1122
+ const number = Number(value);
1123
+ return Number.isFinite(number) && number >= 0 ? number : void 0;
1124
+ }
1125
+ function remember(state, headers, now) {
1126
+ const used = headerNumber(headers, "x-ratelimit-used");
1127
+ const remaining = headerNumber(headers, "x-ratelimit-remaining");
1128
+ const reset = headerNumber(headers, "x-ratelimit-reset");
1129
+ if (used !== void 0) state.used = used;
1130
+ if (remaining !== void 0) state.remaining = remaining;
1131
+ if (reset !== void 0) state.resetAt = now + reset * 1e3;
1132
+ if (remaining !== void 0 && remaining < 1 && reset !== void 0) state.cooldownUntil = Math.max(state.cooldownUntil, now + reset * 1e3);
1133
+ }
1134
+ function seconds(ms) {
1135
+ return Math.max(1, Math.ceil(ms / 1e3));
1136
+ }
1137
+ async function rateInfo(h) {
1138
+ const state = rates.get(await connectionKey(h));
1139
+ if (!state || state.used === void 0 && state.remaining === void 0) return void 0;
1140
+ const reset = state.resetAt !== void 0 ? Math.max(0, Math.ceil((state.resetAt - Date.now()) / 1e3)) : void 0;
1141
+ return { used: state.used, remaining: state.remaining, resetSeconds: reset };
1142
+ }
1143
+ async function redditRequest(h, request) {
1144
+ const state = stateFor(await connectionKey(h));
1145
+ const previous = state.queue;
1146
+ let release = () => {
1147
+ };
1148
+ state.queue = new Promise((resolve) => {
1149
+ release = resolve;
1150
+ });
1151
+ await previous;
1152
+ try {
1153
+ const now = Date.now();
1154
+ const read = (request.method ?? "GET") === "GET";
1155
+ const until = Math.max(state.cooldownUntil, read ? 0 : state.writeCooldownUntil);
1156
+ if (until > now) {
1157
+ const retryAfter = seconds(until - now);
1158
+ throw new ToolFailure(`Reddit's rate limit for this app needs a pause. Nothing was sent. Retry after ${retryAfter} seconds.`, { retryAfter });
1159
+ }
1160
+ if (read && state.remaining !== void 0 && state.remaining <= 1 && state.resetAt !== void 0 && state.resetAt > now) {
1161
+ const retryAfter = seconds(state.resetAt - now);
1162
+ throw new ToolFailure(
1163
+ `Only one Reddit request is left in this rate window, kept for a post or comment. Nothing was sent. Retry the read after ${retryAfter} seconds.`,
1164
+ { retryAfter }
1165
+ );
1166
+ }
1167
+ try {
1168
+ const response = await h.api(request);
1169
+ remember(state, response.headers, Date.now());
1170
+ return response;
1171
+ } catch (error) {
1172
+ if (error instanceof ToolFailure && error.details.status === 429 && error.details.retryAfter !== void 0) {
1173
+ state.cooldownUntil = Math.max(state.cooldownUntil, Date.now() + error.details.retryAfter * 1e3);
1174
+ }
1175
+ throw error;
1176
+ }
1177
+ } finally {
1178
+ release();
1179
+ }
1180
+ }
1181
+ async function noteWriteLimit(h, statedSeconds) {
1182
+ const state = stateFor(await connectionKey(h));
1183
+ const now = Date.now();
1184
+ const headerWait = state.resetAt !== void 0 ? (state.resetAt - now) / 1e3 : 0;
1185
+ const wait = Math.max(statedSeconds ?? 0, headerWait);
1186
+ if (wait <= 0) return void 0;
1187
+ const rounded = Math.ceil(wait);
1188
+ state.writeCooldownUntil = Math.max(state.writeCooldownUntil, now + rounded * 1e3);
1189
+ return rounded;
1190
+ }
1191
+ var ledger = /* @__PURE__ */ new Map();
1192
+ var TRACKING = /^(utm_[a-z0-9_]+|fbclid|gclid|dclid|gbraid|wbraid|msclkid|mc_cid|mc_eid|igshid|yclid|_hsenc|_hsmi)$/i;
1193
+ function normalizeText(text) {
1194
+ return text.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
1195
+ }
1196
+ function normalizeUrl(url) {
1197
+ try {
1198
+ const parsed = new URL(url);
1199
+ parsed.hash = "";
1200
+ for (const key of [...parsed.searchParams.keys()]) if (TRACKING.test(key)) parsed.searchParams.delete(key);
1201
+ return normalizeText(parsed.toString());
1202
+ } catch {
1203
+ return normalizeText(url);
1204
+ }
1205
+ }
1206
+ function thing(target) {
1207
+ return sha256Hex(`reddit-target
1208
+ ${target.toLowerCase()}`);
1209
+ }
1210
+ function prune(now) {
1211
+ for (const [key, row] of ledger) {
1212
+ if ((row.status === "succeeded" || row.status === "failed") && now - row.at > LEDGER_TTL_MS) ledger.delete(key);
1213
+ }
1214
+ while (ledger.size >= MAX_LEDGER_ROWS) {
1215
+ const terminal = [...ledger.entries()].find(([, row]) => row.status === "succeeded" || row.status === "failed");
1216
+ const oldest = terminal?.[0] ?? ledger.keys().next().value;
1217
+ if (oldest === void 0) break;
1218
+ ledger.delete(oldest);
1219
+ }
1220
+ }
1221
+ async function describeMutation(operation, identity2, target, content, kind) {
1222
+ const who = identity2.toLowerCase();
1223
+ return {
1224
+ key: await sha256Hex(`reddit-mutation
1225
+ ${operation}
1226
+ ${who}
1227
+ ${target.toLowerCase()}
1228
+ ${content}`),
1229
+ target: await thing(target),
1230
+ ...kind ? { payload: await sha256Hex(`reddit-payload
1231
+ ${kind}
1232
+ ${who}
1233
+ ${content}`) } : {}
1234
+ };
1235
+ }
1236
+ function checkMutation(mutation, options) {
1237
+ const now = Date.now();
1238
+ prune(now);
1239
+ const row = ledger.get(mutation.key);
1240
+ if (row?.status === "in_flight") throw new ToolFailure(`The same Reddit ${options.what} is being sent right now. Nothing was sent.`);
1241
+ if (row?.status === "succeeded" && !options.idempotent) {
1242
+ throw new ToolFailure(`This exact Reddit ${options.what} already went through in the last 48 hours, so it was not sent again. Nothing was sent.`);
1243
+ }
1244
+ if (row?.status === "ambiguous" && !options.idempotent && !options.allowRepeat) {
1245
+ throw new ToolFailure(
1246
+ `An identical Reddit ${options.what} was sent earlier and its outcome is unknown. Check ${options.check} first; only if it is not there and a new attempt is approved, call again with allow_repeat_after_check: true. Nothing was sent.`
1247
+ );
1248
+ }
1249
+ if (mutation.payload) {
1250
+ for (const other of ledger.values()) {
1251
+ if (other.payload === mutation.payload && other.target !== mutation.target && other.status !== "failed" && now - other.at <= LEDGER_TTL_MS) {
1252
+ throw new ToolFailure(
1253
+ `The same ${options.what} text went to another ${options.what === "post" ? "community" : "thread"} in the last 48 hours. Reddit does not allow repeating it: write a materially different ${options.what} for this one. Nothing was sent.`
1254
+ );
1255
+ }
1256
+ }
1257
+ }
1258
+ }
1259
+ async function recordMutation(mutation, status, resultFullname) {
1260
+ ledger.set(mutation.key, {
1261
+ status,
1262
+ at: Date.now(),
1263
+ target: mutation.target,
1264
+ ...mutation.payload ? { payload: mutation.payload } : {},
1265
+ ...resultFullname ? { result: await thing(resultFullname) } : {}
1266
+ });
1267
+ }
1268
+ async function forgetThing(fullname) {
1269
+ const digest = await thing(fullname);
1270
+ for (const [key, row] of ledger) if (row.target === digest || row.result === digest) ledger.delete(key);
1271
+ }
1272
+
1273
+ // src/vendors/reddit/index.ts
1274
+ var SUBREDDIT = "^(?:/?r/)?[A-Za-z0-9][A-Za-z0-9_]{1,20}$";
1275
+ var FULLNAME = "^t[13]_[a-z0-9]{1,13}$";
1276
+ var USERNAME = /^[A-Za-z0-9_-]{3,20}$/;
1277
+ var MAX_TITLE = 300;
1278
+ var MAX_TEXT = 4e4;
1279
+ var MAX_COMMENT = 1e4;
1280
+ function compact(value) {
1281
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
1282
+ }
1283
+ function bareName(value) {
1284
+ return value.replace(/^\/?u\//i, "").replace(/^@/, "");
1285
+ }
1286
+ function subredditName(value) {
1287
+ return value.replace(/^\/?r\//i, "");
1288
+ }
1289
+ function userAgent(developer) {
1290
+ return `server:agent-connectors.${developer}:1.0.0 (by /u/${developer})`;
1291
+ }
1292
+ function permalink(path) {
1293
+ return typeof path === "string" && path.startsWith("/") ? `https://www.reddit.com${path}` : void 0;
1294
+ }
1295
+ function isoTime(seconds2) {
1296
+ return typeof seconds2 === "number" && Number.isFinite(seconds2) && seconds2 > 0 ? new Date(seconds2 * 1e3).toISOString() : void 0;
1297
+ }
1298
+ function form(values) {
1299
+ const params = new URLSearchParams();
1300
+ for (const [key, value] of Object.entries(values)) if (value !== void 0) params.set(key, String(value));
1301
+ return { body: utf8Bytes(params.toString()), contentType: "application/x-www-form-urlencoded" };
1302
+ }
1303
+ function checkDeveloper(h) {
1304
+ if (!USERNAME.test(h.credentials["developerprofileusername"] ?? "")) {
1305
+ throw new ToolFailure(
1306
+ "The Reddit developer profile username must be the 3 to 20 letters, digits, - or _ of the account that owns the app, without u/. Nothing was sent to Reddit."
1307
+ );
1308
+ }
1309
+ }
1310
+ async function reddit(h, request) {
1311
+ checkDeveloper(h);
1312
+ const { data } = await redditRequest(h, request);
1313
+ return data;
1314
+ }
1315
+ function trimThing(child2) {
1316
+ const data = child2?.data ?? {};
1317
+ if (child2?.kind === "t1") {
1318
+ return compact({
1319
+ id: data.name,
1320
+ type: "comment",
1321
+ subreddit: data.subreddit,
1322
+ author: data.author,
1323
+ postId: data.link_id,
1324
+ parentId: data.parent_id,
1325
+ postTitle: typeof data.link_title === "string" ? truncate(data.link_title, 300) : void 0,
1326
+ url: permalink(data.permalink),
1327
+ text: typeof data.body === "string" ? truncate(data.body, 500) : void 0,
1328
+ score: data.score,
1329
+ createdAt: isoTime(data.created_utc),
1330
+ edited: data.edited ? true : void 0
1331
+ });
1332
+ }
1333
+ if (child2?.kind === "t3") {
1334
+ return compact({
1335
+ id: data.name,
1336
+ type: "post",
1337
+ subreddit: data.subreddit,
1338
+ author: data.author,
1339
+ title: typeof data.title === "string" ? truncate(data.title, 300) : void 0,
1340
+ url: permalink(data.permalink),
1341
+ link: data.is_self ? void 0 : data.url,
1342
+ text: data.is_self && typeof data.selftext === "string" && data.selftext ? truncate(data.selftext, 500) : void 0,
1343
+ selfPost: data.is_self,
1344
+ score: data.score,
1345
+ comments: data.num_comments,
1346
+ nsfw: data.over_18 || void 0,
1347
+ spoiler: data.spoiler || void 0,
1348
+ locked: data.locked || void 0,
1349
+ removed: data.removed_by_category ?? void 0,
1350
+ createdAt: isoTime(data.created_utc),
1351
+ edited: data.edited ? true : void 0
1352
+ });
1353
+ }
1354
+ return compact({ id: data.name, type: child2?.kind });
1355
+ }
1356
+ async function identity(h, live) {
1357
+ const known = h.credentials["redditusername"];
1358
+ if (!live && known && USERNAME.test(known)) return known;
1359
+ const data = await reddit(h, { path: "/api/v1/me" });
1360
+ if (typeof data?.name !== "string" || !data.name) throw new ToolFailure("Reddit did not say which account is connected. Nothing was changed.");
1361
+ return data.name;
1362
+ }
1363
+ async function throwJsonErrors(h, data, what) {
1364
+ const errors = Array.isArray(data?.json?.errors) ? data.json.errors.filter(Array.isArray) : [];
1365
+ if (!errors.length) return;
1366
+ const rate = errors.find((item) => item[0] === "RATELIMIT");
1367
+ if (rate) {
1368
+ const stated = typeof data?.json?.ratelimit === "number" ? data.json.ratelimit : statedDelay(String(rate[1] ?? ""));
1369
+ const wait = await noteWriteLimit(h, stated);
1370
+ throw new ToolFailure(
1371
+ `Reddit asked to slow down before another ${what}${rate[1] ? `: ${cleanVendorText(rate[1], 200)?.replace(/[.!?]+$/, "")}` : ""}. Nothing was changed. ` + (wait !== void 0 ? `Retry after ${wait} seconds, with a fresh approval.` : "Try again later, with a fresh approval."),
1372
+ { vendorCode: "RATELIMIT", ...wait !== void 0 ? { retryAfter: wait } : {} }
1373
+ );
1374
+ }
1375
+ const [code, message, field] = errors[0];
1376
+ const said = cleanVendorText(message, 300);
1377
+ throw new ToolFailure(
1378
+ `Reddit did not accept the ${what} (${String(code)}${field ? `, ${String(field)}` : ""})${said ? `: ${said.replace(/[.!?]+$/, "")}` : ""}. Nothing was changed.`,
1379
+ typeof code === "string" ? { vendorCode: code } : {}
1380
+ );
1381
+ }
1382
+ function statedDelay(text) {
1383
+ const match = /(\d+)\s*(second|minute|hour)s?/i.exec(text);
1384
+ if (!match) return void 0;
1385
+ const value = Number(match[1]);
1386
+ const unit = match[2].toLowerCase();
1387
+ return value * (unit === "hour" ? 3600 : unit === "minute" ? 60 : 1);
1388
+ }
1389
+ async function guarded(mutation, check, send) {
1390
+ checkMutation(mutation, check);
1391
+ await recordMutation(mutation, "in_flight");
1392
+ try {
1393
+ const { value, fullname } = await send();
1394
+ await recordMutation(mutation, "succeeded", fullname);
1395
+ return value;
1396
+ } catch (error) {
1397
+ await recordMutation(mutation, error instanceof ToolFailure ? "failed" : "ambiguous");
1398
+ throw error;
1399
+ }
1400
+ }
1401
+ async function ownThing(h, fullname, what) {
1402
+ const me = await identity(h, true);
1403
+ const data = await reddit(h, { path: "/api/info", query: { id: fullname, raw_json: 1 } });
1404
+ const children = Array.isArray(data?.data?.children) ? data.data.children : [];
1405
+ const matches = children.filter((child2) => child2?.data?.name === fullname);
1406
+ if (matches.length !== 1) throw new ToolFailure(`Reddit found no post or comment ${fullname}, so there is nothing to ${what}. Nothing was changed.`);
1407
+ const item = matches[0];
1408
+ const author = typeof item?.data?.author === "string" ? item.data.author : "";
1409
+ if (author.toLowerCase() !== me.toLowerCase()) {
1410
+ throw new ToolFailure(`${fullname} is not the connected account's own ${item.kind === "t1" ? "comment" : "post"} (or it was already deleted), so it cannot be changed here. Nothing was changed.`);
1411
+ }
1412
+ return { item, me };
1413
+ }
1414
+ var ALLOW_REPEAT = {
1415
+ type: "boolean",
1416
+ default: false,
1417
+ description: "Only after an identical earlier attempt had an unknown outcome, the check showed it did not go through, and a new attempt was approved."
1418
+ };
1419
+ var connector = defineConnector({
1420
+ vendor: "reddit",
1421
+ label: "Reddit",
1422
+ origins: ["https://oauth.reddit.com"],
1423
+ credentials: ["access_token", "developerprofileusername", "redditusername"],
1424
+ requiredCredentials: [["access_token", "developerprofileusername"]],
1425
+ credentialLabels: {
1426
+ access_token: "Reddit access token",
1427
+ developerprofileusername: "Reddit developer profile username",
1428
+ redditusername: "Reddit username"
1429
+ },
1430
+ normalizeCredentials: (credentials) => {
1431
+ for (const name2 of ["developerprofileusername", "redditusername"]) {
1432
+ if (credentials[name2]) credentials[name2] = bareName(credentials[name2]);
1433
+ }
1434
+ return credentials;
1435
+ },
1436
+ authHeaders: (credentials) => ({
1437
+ authorization: `Bearer ${credentials["access_token"]}`,
1438
+ "user-agent": userAgent(String(credentials["developerprofileusername"] ?? ""))
1439
+ }),
1440
+ tools: [
1441
+ {
1442
+ name: "get_me",
1443
+ kind: "read",
1444
+ title: "Get the connected Reddit account",
1445
+ description: "Returns the connected Reddit account: username, id, karma, account age, and whether its email is verified.",
1446
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1447
+ async run(_args, h) {
1448
+ const data = await reddit(h, { path: "/api/v1/me" });
1449
+ return compact({
1450
+ name: data?.name,
1451
+ id: data?.id ? `t2_${data.id}` : void 0,
1452
+ url: data?.name ? `https://www.reddit.com/user/${data.name}/` : void 0,
1453
+ linkKarma: data?.link_karma,
1454
+ commentKarma: data?.comment_karma,
1455
+ totalKarma: data?.total_karma,
1456
+ createdAt: isoTime(data?.created_utc),
1457
+ verifiedEmail: data?.has_verified_email,
1458
+ suspended: data?.is_suspended || void 0,
1459
+ rateLimit: await rateInfo(h)
1460
+ });
1461
+ }
1462
+ },
1463
+ {
1464
+ name: "list_my_subreddits",
1465
+ kind: "read",
1466
+ title: "List my Reddit communities",
1467
+ description: "Lists the communities the connected account is subscribed to, or those where it is an approved contributor: name, title, subscribers, type and which posts they take. Pass nextCursor back as cursor for more; read only as many pages as the task needs.",
1468
+ inputSchema: {
1469
+ type: "object",
1470
+ properties: {
1471
+ where: { type: "string", enum: ["subscriber", "contributor"], default: "subscriber", description: "subscriber (default) or contributor." },
1472
+ limit: { type: "integer", minimum: 1, maximum: 100, default: 100, description: "Communities per page, 1 to 100 (default 100)." },
1473
+ cursor: { type: "string", description: "nextCursor from the previous result." }
1474
+ },
1475
+ additionalProperties: false
1476
+ },
1477
+ async run(args, h) {
1478
+ const state = h.cursor(args.cursor);
1479
+ const after = typeof state?.["a"] === "string" ? state["a"] : void 0;
1480
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
1481
+ const where = typeof state?.["w"] === "string" ? state["w"] : args.where;
1482
+ const limit = typeof state?.["n"] === "number" ? state["n"] : args.limit;
1483
+ const data = await reddit(h, { path: `/subreddits/mine/${where}`, query: { limit, after, raw_json: 1 } });
1484
+ const children = Array.isArray(data?.data?.children) ? data.data.children : [];
1485
+ const items = children.map((child2) => {
1486
+ const sub = child2?.data ?? {};
1487
+ return compact({
1488
+ name: sub.display_name,
1489
+ title: typeof sub.title === "string" ? truncate(sub.title, 200) : void 0,
1490
+ url: typeof sub.url === "string" ? `https://www.reddit.com${sub.url}` : void 0,
1491
+ subscribers: sub.subscribers,
1492
+ type: sub.subreddit_type,
1493
+ submissionType: sub.submission_type,
1494
+ nsfw: sub.over18 || void 0
1495
+ });
1496
+ });
1497
+ const next = typeof data?.data?.after === "string" ? data.data.after : void 0;
1498
+ return h.page({
1499
+ key: "subreddits",
1500
+ items: items.slice(skip),
1501
+ extra: { where, rateLimit: await rateInfo(h) },
1502
+ resumeAt: (index) => h.makeCursor({ ...after ? { a: after } : {}, o: skip + index, w: where, n: limit }),
1503
+ ...next ? { nextPage: h.makeCursor({ a: next, o: 0, w: where, n: limit }) } : {}
1504
+ });
1505
+ }
1506
+ },
1507
+ {
1508
+ name: "get_subreddit_rules",
1509
+ kind: "read",
1510
+ title: "Get a Reddit community's rules",
1511
+ description: "Returns one community's rules (name, what they apply to, description) and Reddit's site-wide rules. Read them before posting or commenting there: every post must follow both.",
1512
+ inputSchema: {
1513
+ type: "object",
1514
+ properties: { subreddit: { type: "string", pattern: SUBREDDIT, description: "The community name, such as test or r/test." } },
1515
+ required: ["subreddit"],
1516
+ additionalProperties: false
1517
+ },
1518
+ async run(args, h) {
1519
+ const name2 = subredditName(args.subreddit);
1520
+ const data = await reddit(h, {
1521
+ path: `/r/${name2}/about/rules`,
1522
+ query: { raw_json: 1 },
1523
+ errors: { 403: "Reddit refused to show this community's rules (it may be private or banned)", 404: "Reddit found no such community" }
1524
+ });
1525
+ const rules = Array.isArray(data?.rules) ? data.rules : [];
1526
+ return compact({
1527
+ subreddit: name2,
1528
+ rules: rules.map((rule) => compact({
1529
+ name: rule?.short_name,
1530
+ appliesTo: rule?.kind,
1531
+ description: typeof rule?.description === "string" && rule.description ? truncate(rule.description, 1e3) : void 0,
1532
+ violationReason: rule?.violation_reason && rule.violation_reason !== rule.short_name ? rule.violation_reason : void 0
1533
+ })),
1534
+ siteRules: Array.isArray(data?.site_rules) ? data.site_rules.map((rule) => truncate(String(rule), 300)) : void 0,
1535
+ rateLimit: await rateInfo(h)
1536
+ });
1537
+ }
1538
+ },
1539
+ {
1540
+ name: "submit_post",
1541
+ kind: "create",
1542
+ check: "list_my_posts",
1543
+ title: "Submit a Reddit post",
1544
+ description: "Submits one text or link post to one community, after its rules were read with get_subreddit_rules. nsfw and spoiler must be set on purpose. Reddit never gets the same post twice from here: an identical post that went through in the last 48 hours, the same text in another community, and a repeat after an unclear outcome are refused. Reddit has no crossposting or bulk posting here. Returns the post id and link.",
1545
+ inputSchema: {
1546
+ type: "object",
1547
+ properties: {
1548
+ subreddit: { type: "string", pattern: SUBREDDIT, description: "The one community to post in, such as test or r/test." },
1549
+ kind: { type: "string", enum: ["self", "link"], description: "self for a text post, link for a link post." },
1550
+ title: { type: "string", minLength: 1, maxLength: MAX_TITLE, description: "The title, up to 300 characters. Never cut a title: write a shorter one." },
1551
+ text: { type: "string", maxLength: MAX_TEXT, description: "The body of a text post, in Markdown." },
1552
+ url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "The link of a link post (https)." },
1553
+ nsfw: { type: "boolean", description: "Whether the post is NSFW, from the content and the community's rules." },
1554
+ spoiler: { type: "boolean", description: "Whether the post is a spoiler." },
1555
+ flair_id: { type: "string", maxLength: 64, description: "A post flair template id, for communities that require flair." },
1556
+ flair_text: { type: "string", maxLength: 64, description: "The flair text, for a flair that allows its own text." },
1557
+ send_replies: { type: "boolean", default: true, description: "Send replies to the account's inbox (default true)." },
1558
+ allow_repeat_after_check: ALLOW_REPEAT
1559
+ },
1560
+ required: ["subreddit", "kind", "title", "nsfw", "spoiler"],
1561
+ additionalProperties: false
1562
+ },
1563
+ async run(args, h) {
1564
+ if (args.kind === "self" && args.url !== void 0) throw new ToolFailure("A text post (kind self) takes text, not url. Nothing was sent.");
1565
+ if (args.kind === "link" && args.url === void 0) throw new ToolFailure("A link post (kind link) needs url. Nothing was sent.");
1566
+ if (args.kind === "link" && args.text !== void 0) throw new ToolFailure("A link post (kind link) takes url, not text. Nothing was sent.");
1567
+ if (!args.title.trim()) throw new ToolFailure("The title is empty. Nothing was sent.");
1568
+ checkDeveloper(h);
1569
+ const subreddit = subredditName(args.subreddit);
1570
+ const me = await identity(h, false);
1571
+ const content = `${normalizeText(args.title)}
1572
+ ${args.kind === "link" ? normalizeUrl(args.url ?? "") : normalizeText(args.text ?? "")}`;
1573
+ const mutation = await describeMutation(`submit_${args.kind}`, me, `r/${subreddit}`, content, "post");
1574
+ return guarded(mutation, { what: "post", check: "list_my_posts", allowRepeat: args.allow_repeat_after_check }, async () => {
1575
+ const data = await reddit(h, {
1576
+ method: "POST",
1577
+ path: "/api/submit",
1578
+ ...form({
1579
+ api_type: "json",
1580
+ kind: args.kind,
1581
+ sr: subreddit,
1582
+ title: args.title,
1583
+ text: args.kind === "self" ? args.text ?? "" : void 0,
1584
+ url: args.kind === "link" ? args.url : void 0,
1585
+ nsfw: args.nsfw,
1586
+ spoiler: args.spoiler,
1587
+ sendreplies: args.send_replies,
1588
+ flair_id: args.flair_id,
1589
+ flair_text: args.flair_text
1590
+ }),
1591
+ write: true,
1592
+ errors: { 403: "Reddit refused the post (the account may be banned from this community, or the community restricts who may post)" }
1593
+ });
1594
+ await throwJsonErrors(h, data, "post");
1595
+ const name2 = data?.json?.data?.name;
1596
+ const url = data?.json?.data?.url;
1597
+ if (typeof name2 !== "string" && typeof url !== "string") {
1598
+ throw new OutcomeUnknown("Reddit answered without the new post's id or link, so it is not known whether it was submitted.");
1599
+ }
1600
+ return {
1601
+ fullname: typeof name2 === "string" ? name2 : void 0,
1602
+ value: compact({ id: name2, url, subreddit, kind: args.kind, rateLimit: await rateInfo(h) })
1603
+ };
1604
+ });
1605
+ }
1606
+ },
1607
+ {
1608
+ name: "add_comment",
1609
+ kind: "create",
1610
+ check: "list_my_comments",
1611
+ title: "Comment on Reddit",
1612
+ description: "Posts one comment on a post (t3_...) or one reply to a comment (t1_...), by its fullname. One comment per approved operation: an identical comment that went through in the last 48 hours, the same text on another thread, and a repeat after an unclear outcome are refused. Returns the comment id and link.",
1613
+ inputSchema: {
1614
+ type: "object",
1615
+ properties: {
1616
+ thing_id: { type: "string", pattern: FULLNAME, description: "The fullname to reply to: t3_... for a post, t1_... for a comment." },
1617
+ text: { type: "string", minLength: 1, maxLength: MAX_COMMENT, description: "The comment, in Markdown, up to 10,000 characters." },
1618
+ allow_repeat_after_check: ALLOW_REPEAT
1619
+ },
1620
+ required: ["thing_id", "text"],
1621
+ additionalProperties: false
1622
+ },
1623
+ async run(args, h) {
1624
+ if (!args.text.trim()) throw new ToolFailure("The comment is empty. Nothing was sent.");
1625
+ checkDeveloper(h);
1626
+ const me = await identity(h, false);
1627
+ const mutation = await describeMutation("comment", me, args.thing_id, normalizeText(args.text), "comment");
1628
+ return guarded(mutation, { what: "comment", check: "list_my_comments", allowRepeat: args.allow_repeat_after_check }, async () => {
1629
+ const data = await reddit(h, {
1630
+ method: "POST",
1631
+ path: "/api/comment",
1632
+ ...form({ api_type: "json", thing_id: args.thing_id, text: args.text }),
1633
+ write: true,
1634
+ errors: { 403: "Reddit refused the comment (the thread may be locked or archived, or the account banned from the community)" }
1635
+ });
1636
+ await throwJsonErrors(h, data, "comment");
1637
+ const comment = data?.json?.data?.things?.[0]?.data;
1638
+ if (typeof comment?.name !== "string") {
1639
+ throw new OutcomeUnknown("Reddit answered without the new comment's id, so it is not known whether it was posted.");
1640
+ }
1641
+ return {
1642
+ fullname: comment.name,
1643
+ value: compact({ id: comment.name, url: permalink(comment.permalink), parentId: comment.parent_id ?? args.thing_id, postId: comment.link_id, rateLimit: await rateInfo(h) })
1644
+ };
1645
+ });
1646
+ }
1647
+ },
1648
+ {
1649
+ name: "edit_text",
1650
+ kind: "update",
1651
+ check: "get_items",
1652
+ title: "Edit my Reddit post or comment",
1653
+ description: "Replaces the text of one of the connected account's own text posts (t3_...) or comments (t1_...). Reddit edits bodies only, never a title or a link post. Checks with Reddit right before that the item is the account's own.",
1654
+ inputSchema: {
1655
+ type: "object",
1656
+ properties: {
1657
+ thing_id: { type: "string", pattern: FULLNAME, description: "The fullname of the account's own post or comment." },
1658
+ text: { type: "string", minLength: 1, maxLength: MAX_TEXT, description: "The new text, in Markdown." }
1659
+ },
1660
+ required: ["thing_id", "text"],
1661
+ additionalProperties: false
1662
+ },
1663
+ async run(args, h) {
1664
+ checkDeveloper(h);
1665
+ const { item, me } = await ownThing(h, args.thing_id, "edit");
1666
+ if (item.kind === "t3" && item.data?.is_self !== true) throw new ToolFailure(`${args.thing_id} is a link post, which has no text to edit. Nothing was changed.`);
1667
+ const mutation = await describeMutation("edit", me, args.thing_id, normalizeText(args.text));
1668
+ return guarded(mutation, { what: "edit", check: "get_items", idempotent: true }, async () => {
1669
+ const data = await reddit(h, {
1670
+ method: "POST",
1671
+ path: "/api/editusertext",
1672
+ ...form({ api_type: "json", thing_id: args.thing_id, text: args.text }),
1673
+ write: true,
1674
+ errors: { 403: "Reddit refused the edit (the item may be archived or locked)" }
1675
+ });
1676
+ await throwJsonErrors(h, data, "edit");
1677
+ const edited = data?.json?.data?.things?.[0]?.data;
1678
+ if (edited?.name !== args.thing_id) throw new OutcomeUnknown("Reddit answered without the edited item, so it is not known whether the edit was saved.");
1679
+ return { value: compact({ id: args.thing_id, url: permalink(edited.permalink), edited: true, rateLimit: await rateInfo(h) }) };
1680
+ });
1681
+ }
1682
+ },
1683
+ {
1684
+ name: "delete_item",
1685
+ kind: "delete",
1686
+ check: "get_items",
1687
+ title: "Delete my Reddit post or comment",
1688
+ description: "Deletes one of the connected account's own posts (t3_...) or comments (t1_...), for good. Checks with Reddit right before that the item is the account's own.",
1689
+ inputSchema: {
1690
+ type: "object",
1691
+ properties: { thing_id: { type: "string", pattern: FULLNAME, description: "The fullname of the account's own post or comment." } },
1692
+ required: ["thing_id"],
1693
+ additionalProperties: false
1694
+ },
1695
+ async run(args, h) {
1696
+ checkDeveloper(h);
1697
+ const { me } = await ownThing(h, args.thing_id, "delete");
1698
+ const mutation = await describeMutation("delete", me, args.thing_id, "");
1699
+ const result2 = await guarded(mutation, { what: "delete", check: "get_items", idempotent: true }, async () => {
1700
+ const data = await reddit(h, { method: "POST", path: "/api/del", ...form({ id: args.thing_id }), write: true });
1701
+ await throwJsonErrors(h, data, "delete");
1702
+ return { value: compact({ id: args.thing_id, deleted: true, rateLimit: await rateInfo(h) }) };
1703
+ });
1704
+ await forgetThing(args.thing_id);
1705
+ return result2;
1706
+ }
1707
+ },
1708
+ {
1709
+ name: "list_my_posts",
1710
+ kind: "read",
1711
+ title: "List my Reddit posts",
1712
+ description: "Lists the connected account's own posts, newest first: id, community, title, link, score and comment count. Pass nextCursor back as cursor for older ones.",
1713
+ inputSchema: {
1714
+ type: "object",
1715
+ properties: {
1716
+ limit: { type: "integer", minimum: 1, maximum: 100, default: 25, description: "Posts per page, 1 to 100 (default 25)." },
1717
+ cursor: { type: "string", description: "nextCursor from the previous result." }
1718
+ },
1719
+ additionalProperties: false
1720
+ },
1721
+ async run(args, h) {
1722
+ return listHistory(h, "submitted", "posts", args);
1723
+ }
1724
+ },
1725
+ {
1726
+ name: "list_my_comments",
1727
+ kind: "read",
1728
+ title: "List my Reddit comments",
1729
+ description: "Lists the connected account's own comments, newest first: id, community, the post it is on, link, text and score. Pass nextCursor back as cursor for older ones.",
1730
+ inputSchema: {
1731
+ type: "object",
1732
+ properties: {
1733
+ limit: { type: "integer", minimum: 1, maximum: 100, default: 25, description: "Comments per page, 1 to 100 (default 25)." },
1734
+ cursor: { type: "string", description: "nextCursor from the previous result." }
1735
+ },
1736
+ additionalProperties: false
1737
+ },
1738
+ async run(args, h) {
1739
+ return listHistory(h, "comments", "comments", args);
1740
+ }
1741
+ },
1742
+ {
1743
+ name: "get_items",
1744
+ kind: "read",
1745
+ title: "Get Reddit posts or comments",
1746
+ description: "Returns up to 25 posts (t3_...) or comments (t1_...) by their fullnames: author, community, text, score, and whether they were removed.",
1747
+ inputSchema: {
1748
+ type: "object",
1749
+ properties: {
1750
+ ids: { type: "array", minItems: 1, maxItems: 25, uniqueItems: true, items: { type: "string", pattern: FULLNAME }, description: 'The fullnames, such as ["t3_abc123", "t1_def456"].' }
1751
+ },
1752
+ required: ["ids"],
1753
+ additionalProperties: false
1754
+ },
1755
+ async run(args, h) {
1756
+ const data = await reddit(h, { path: "/api/info", query: { id: args.ids.join(","), raw_json: 1 } });
1757
+ const children = Array.isArray(data?.data?.children) ? data.data.children : [];
1758
+ const found = new Set(children.map((child2) => child2?.data?.name));
1759
+ const missing = args.ids.filter((id) => !found.has(id));
1760
+ return compact({ items: children.map(trimThing), missing: missing.length ? missing : void 0, rateLimit: await rateInfo(h) });
1761
+ }
1762
+ },
1763
+ // Reads only: every change goes through the tools above and their checks.
1764
+ ...apiTools({
1765
+ label: "Reddit",
1766
+ description: "The Reddit Data API on https://oauth.reddit.com, with the connection's token and Reddit's User-Agent, inside the app's rate window: documented GET endpoints such as /r/{name}/about, /r/{name}/new or /comments/{id} (add raw_json=1 in query). Read only what the task needs, never whole listings. Reference: https://www.reddit.com/dev/api.",
1767
+ send: (request, h) => {
1768
+ checkDeveloper(h);
1769
+ return redditRequest(h, request);
1770
+ }
1771
+ }).filter((tool) => tool.name === "api_get")
1772
+ ]
1773
+ });
1774
+ async function listHistory(h, where, key, args) {
1775
+ const state = h.cursor(args.cursor);
1776
+ const after = typeof state?.["a"] === "string" ? state["a"] : void 0;
1777
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
1778
+ const limit = typeof state?.["n"] === "number" ? state["n"] : args.limit;
1779
+ const me = typeof state?.["u"] === "string" ? state["u"] : await identity(h, false);
1780
+ const data = await reddit(h, { path: `/user/${encodeURIComponent(me)}/${where}`, query: { sort: "new", limit, after, raw_json: 1 } });
1781
+ const children = Array.isArray(data?.data?.children) ? data.data.children : [];
1782
+ const next = typeof data?.data?.after === "string" ? data.data.after : void 0;
1783
+ return h.page({
1784
+ key,
1785
+ items: children.map(trimThing).slice(skip),
1786
+ extra: { account: me, rateLimit: await rateInfo(h) },
1787
+ resumeAt: (index) => h.makeCursor({ u: me, ...after ? { a: after } : {}, o: skip + index, n: limit }),
1788
+ ...next ? { nextPage: h.makeCursor({ u: me, a: next, o: 0, n: limit }) } : {}
1789
+ });
1790
+ }
1791
+ module.exports = connector;