@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
@@ -17,6 +17,23 @@ var OutcomeUnknown = class extends Error {
17
17
  }
18
18
  };
19
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
+
20
37
  // src/core/text.ts
21
38
  var encoder = new TextEncoder();
22
39
  var decoder = new TextDecoder();
@@ -29,12 +46,15 @@ function utf8Length(text) {
29
46
  function utf8Decode(bytes) {
30
47
  return decoder.decode(bytes);
31
48
  }
32
- function base64UrlEncode(bytes) {
49
+ function base64Encode(bytes) {
33
50
  let binary = "";
34
51
  for (let i = 0; i < bytes.length; i += 32768) {
35
52
  binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
36
53
  }
37
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
54
+ return btoa(binary);
55
+ }
56
+ function base64UrlEncode(bytes) {
57
+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
38
58
  }
39
59
  function base64UrlDecode(text) {
40
60
  if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
@@ -60,6 +80,295 @@ function formatNumber(value) {
60
80
  return value.toLocaleString("en-US");
61
81
  }
62
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
+
63
372
  // src/core/http.ts
64
373
  var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
65
374
  var USER_AGENT = "agent-connectors";
@@ -134,19 +443,19 @@ async function readCapped(response, maxBytes) {
134
443
  if (!response.body) return new Uint8Array(0);
135
444
  const reader = response.body.getReader();
136
445
  const chunks = [];
137
- let total = 0;
446
+ let total2 = 0;
138
447
  for (; ; ) {
139
448
  const { done, value } = await reader.read();
140
449
  if (done) break;
141
- total += value.byteLength;
142
- if (total > maxBytes) {
450
+ total2 += value.byteLength;
451
+ if (total2 > maxBytes) {
143
452
  await reader.cancel().catch(() => {
144
453
  });
145
454
  throw new TooLarge(maxBytes);
146
455
  }
147
456
  chunks.push(value);
148
457
  }
149
- const bytes = new Uint8Array(total);
458
+ const bytes = new Uint8Array(total2);
150
459
  let offset = 0;
151
460
  for (const chunk of chunks) {
152
461
  bytes.set(chunk, offset);
@@ -168,6 +477,7 @@ function parseBody(bytes, contentType) {
168
477
  function createHttp(env) {
169
478
  const { label, ctx } = env;
170
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.`;
171
481
  function failureFor(status, headers, data, request) {
172
482
  const message = vendorMessage(data);
173
483
  const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
@@ -190,7 +500,7 @@ function createHttp(env) {
190
500
  }
191
501
  if (status === 401) {
192
502
  return new ToolFailure(
193
- withCustom(`${label} rejected the credentials (HTTP 401)${said}. Check that the ${env.credentialLabel} is correct and still active.${nothingChanged}`),
503
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
194
504
  { status, ...extra }
195
505
  );
196
506
  }
@@ -209,7 +519,13 @@ function createHttp(env) {
209
519
  const url = new URL(request.path, origin);
210
520
  if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
211
521
  for (const [key, value] of Object.entries(request.query ?? {})) {
212
- if (value !== void 0 && value !== null) url.searchParams.set(key, String(value));
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
+ }
213
529
  }
214
530
  const headers = {
215
531
  accept: "application/json",
@@ -238,6 +554,7 @@ function createHttp(env) {
238
554
  if (request.write) {
239
555
  throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
240
556
  }
557
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
241
558
  throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
242
559
  }
243
560
  env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
@@ -250,7 +567,7 @@ function createHttp(env) {
250
567
  }
251
568
  throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
252
569
  }
253
- const data = parseBody(bytes, response.headers.get("content-type"));
570
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
254
571
  if (response.ok) return { status: response.status, headers: response.headers, data };
255
572
  throw failureFor(response.status, response.headers, data, request);
256
573
  }
@@ -297,68 +614,20 @@ function createHttp(env) {
297
614
  return { api, media };
298
615
  }
299
616
 
300
- // src/core/output.ts
301
- var OUTPUT_LIMIT_BYTES = 32 * 1024;
302
- function jsonSize(value) {
303
- return utf8Length(JSON.stringify(value) ?? "");
304
- }
305
- function cutStrings(value, max) {
306
- if (typeof value === "string") return truncate(value, max);
307
- if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
308
- if (typeof value === "object" && value !== null) {
309
- const out = {};
310
- for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
311
- return out;
312
- }
313
- return value;
314
- }
315
- function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
316
- if (jsonSize(value) <= limit) return { value, truncated: false };
317
- for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
318
- const cut = cutStrings(value, max);
319
- if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
320
- }
321
- return void 0;
322
- }
323
- function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
324
- const build = (count) => {
325
- const cut = count < input.items.length;
326
- const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
327
- const next = cut ? input.resumeAt(count) : input.nextPage;
328
- if (next) result2["nextCursor"] = next;
329
- if (cut) result2["truncated"] = true;
330
- return result2;
331
- };
332
- const all = build(input.items.length);
333
- if (jsonSize(all) <= limit) return all;
334
- let low = 1;
335
- let high = input.items.length - 1;
336
- while (low < high) {
337
- const middle = Math.ceil((low + high) / 2);
338
- if (jsonSize(build(middle)) <= limit) low = middle;
339
- else high = middle - 1;
340
- }
341
- const best = build(low);
342
- if (jsonSize(best) <= limit) return best;
343
- const shrunk = shrinkToFit(best, limit);
344
- if (shrunk) return { ...shrunk.value, truncated: true };
345
- throw new ToolFailure("The result is too large to return, even one item at a time.");
346
- }
347
- function encodeCursor(tool, state) {
348
- return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
349
- }
350
- function decodeCursor(tool, cursor) {
351
- if (cursor === void 0 || cursor === "") return null;
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;
352
622
  try {
353
- const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
354
- if (typeof state === "object" && state !== null && state.t === tool) {
355
- return state;
356
- }
623
+ url = new URL(text.includes("://") ? text : `https://${text}`);
357
624
  } catch {
625
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
358
626
  }
359
- throw new ToolFailure(
360
- "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."
361
- );
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 };
362
631
  }
363
632
 
364
633
  // src/core/schema.ts
@@ -500,16 +769,35 @@ function validateArguments(schema, args) {
500
769
  return { ok: true, value };
501
770
  }
502
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
+
503
786
  // src/core/connector.ts
504
787
  var ANNOTATIONS = {
505
788
  read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
506
789
  create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
507
790
  update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
508
- delete: { 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 }
509
793
  };
510
794
  var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
511
795
  var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
512
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"];
513
801
  function deepFreeze(value) {
514
802
  if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
515
803
  Object.freeze(value);
@@ -523,7 +811,8 @@ function assertDefinition(def) {
523
811
  };
524
812
  if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
525
813
  if (!def.label?.trim()) problem("label is required");
526
- if (!def.origins.length) problem("at least one origin is required");
814
+ const originFields = def.originFields ?? [];
815
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
527
816
  for (const origin of def.origins) {
528
817
  let url;
529
818
  try {
@@ -535,6 +824,10 @@ function assertDefinition(def) {
535
824
  for (const name2 of def.credentials) {
536
825
  if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
537
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
+ }
538
831
  const names = /* @__PURE__ */ new Set();
539
832
  for (const tool of def.tools) {
540
833
  if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
@@ -542,7 +835,7 @@ function assertDefinition(def) {
542
835
  names.add(tool.name);
543
836
  if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
544
837
  if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
545
- if (!(tool.kind in ANNOTATIONS)) problem(`tool ${tool.name} has an unknown kind`);
838
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
546
839
  if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
547
840
  problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
548
841
  }
@@ -552,9 +845,95 @@ function assertDefinition(def) {
552
845
  const check = def.tools.find((candidate) => candidate.name === tool.check);
553
846
  if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
554
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
+ });
555
861
  }
556
- function result(payload, isError) {
557
- return { content: [{ type: "text", text: JSON.stringify(payload) }], ...isError ? { isError: true } : {} };
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((field) => !PICKER_FIELDS.includes(field));
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 field of ["idField", "nameField"]) {
913
+ if (!isDotPath(picker[field])) fail(`${field} 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
+ };
558
937
  }
559
938
  function failure(message, details = {}) {
560
939
  return result({ error: message, ...details }, true);
@@ -575,6 +954,14 @@ function defineConnector(def) {
575
954
  const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
576
955
  const toolList = def.tools.map((tool) => tool.name).join(", ");
577
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
+ };
578
965
  const descriptors = def.tools.map((tool) => ({
579
966
  name: tool.name,
580
967
  title: tool.title,
@@ -592,23 +979,36 @@ function defineConnector(def) {
592
979
  } catch {
593
980
  }
594
981
  };
595
- let credentials = trimmed(ctx.credentials);
596
- if (def.normalizeCredentials) credentials = def.normalizeCredentials(credentials);
597
- const missing = def.credentials.filter((name2) => !credentials[name2]);
598
- if (missing.length) {
599
- return failure(`${label} is not connected: the ${missing.map(credentialLabel).join(" and ")} ${missing.length > 1 ? "are" : "is"} missing.`);
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);
600
995
  }
996
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
601
997
  const parsed = validateArguments(tool.inputSchema, args);
602
998
  if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
603
999
  const frozenCredentials = Object.freeze({ ...credentials });
604
1000
  let writeSent = false;
1001
+ const fileLimit = fileLimitOf(ctx);
1002
+ const files = [];
1003
+ let fileBytes = 0;
605
1004
  const http = createHttp({
606
1005
  vendor: def.vendor,
607
1006
  label,
608
1007
  tool: tool.name,
609
1008
  readOnly: tool.kind === "read",
610
- origins: def.origins,
611
- credentialLabel: def.credentials.map(credentialLabel).join(" and "),
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),
612
1012
  ctx,
613
1013
  authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
614
1014
  log,
@@ -620,11 +1020,29 @@ function defineConnector(def) {
620
1020
  tool: tool.name,
621
1021
  credentials: frozenCredentials,
622
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
+ },
623
1029
  api: http.api,
624
1030
  media: http.media,
625
1031
  page: (input) => fitPage(input),
626
1032
  cursor: (cursor) => decodeCursor(tool.name, cursor),
627
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 total2 = fileBytes + bytes.byteLength;
1038
+ if (total2 > fileLimit) {
1039
+ throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total2)} 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
+ fileBytes = total2;
1042
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
1043
+ files.push({ ...info, bytes });
1044
+ return { ...info };
1045
+ },
628
1046
  log
629
1047
  };
630
1048
  try {
@@ -632,7 +1050,7 @@ function defineConnector(def) {
632
1050
  const fitted = shrinkToFit(data ?? {});
633
1051
  if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
634
1052
  const payload = fitted.value;
635
- return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false);
1053
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
636
1054
  } catch (error) {
637
1055
  if (error instanceof OutcomeUnknown) {
638
1056
  return result({
@@ -656,16 +1074,26 @@ function defineConnector(def) {
656
1074
  return deepFreeze({
657
1075
  vendor: def.vendor,
658
1076
  origins: [...def.origins],
1077
+ originFields: [...def.originFields ?? []],
1078
+ uploadHosts: [...def.uploadHosts ?? []],
659
1079
  credentials: [...def.credentials],
1080
+ requiredCredentials: required.map((list) => [...list]),
1081
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
660
1082
  tools: descriptors,
661
1083
  call
662
1084
  });
663
1085
  }
664
1086
 
1087
+ // src/core/jwt.ts
1088
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
1089
+
665
1090
  // src/vendors/devto/index.ts
666
1091
  var DISCLOSURE_LEVELS = ["fully_autonomous", "some_ai", "no_ai"];
667
1092
  var DISCLOSURE_HELP = "dev.to's AI disclosure for the article: fully_autonomous when an AI wrote it (even if a person asked for it or approved it), some_ai when a person wrote it and AI helped with drafting, editing, code or translation, no_ai only when a person wrote it with no AI help.";
668
1093
  var TAG_SCHEMA = { type: "string", pattern: "^[A-Za-z0-9]{1,30}$", description: "Letters and digits only, up to 30." };
1094
+ var DATE_SCHEMA = { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$" };
1095
+ var BODY_PART_BYTES = 2e4;
1096
+ var MAX_DRAFT_PAGES = 10;
669
1097
  var ARTICLE_FIELDS = {
670
1098
  title: { type: "string", minLength: 1, maxLength: 128, description: "The article title, up to 128 characters." },
671
1099
  body_markdown: {
@@ -772,14 +1200,67 @@ async function saveArticle(h, method, path, article) {
772
1200
  throw error;
773
1201
  }
774
1202
  }
1203
+ async function findArticle(h, id) {
1204
+ try {
1205
+ const { data } = await h.api({ path: `/api/articles/${id}` });
1206
+ if (data && typeof data === "object" && !Array.isArray(data)) return data;
1207
+ } catch (error) {
1208
+ if (!(error instanceof ToolFailure) || error.details.status !== 404) throw error;
1209
+ }
1210
+ for (let page = 1; page <= MAX_DRAFT_PAGES; page++) {
1211
+ const { data } = await h.api({ path: "/api/articles/me/unpublished", query: { page, per_page: 100 } });
1212
+ const drafts = Array.isArray(data) ? data : [];
1213
+ const found = drafts.find((article) => article?.id === id);
1214
+ if (found) return found;
1215
+ if (drafts.length < 100) break;
1216
+ }
1217
+ throw new ToolFailure(
1218
+ `dev.to has no published article ${id}, and it is not among the account's drafts. Check the id with list_my_articles.`,
1219
+ { status: 404 }
1220
+ );
1221
+ }
1222
+ function bodyPart(body, offset) {
1223
+ const rest = body.slice(offset, offset + BODY_PART_BYTES);
1224
+ if (offset + rest.length >= body.length && jsonSize(rest) <= BODY_PART_BYTES) return { text: rest, end: body.length };
1225
+ let low = 1;
1226
+ let high = rest.length;
1227
+ while (low < high) {
1228
+ const middle = Math.ceil((low + high) / 2);
1229
+ if (jsonSize(rest.slice(0, middle)) <= BODY_PART_BYTES) low = middle;
1230
+ else high = middle - 1;
1231
+ }
1232
+ let end = low;
1233
+ if (/[\ud800-\udbff]/.test(rest[end - 1] ?? "")) end -= 1;
1234
+ const lineBreak = rest.lastIndexOf("\n", end - 1);
1235
+ if (lineBreak >= end * 0.7) end = lineBreak + 1;
1236
+ return { text: rest.slice(0, end), end: offset + end };
1237
+ }
1238
+ function total(entry, name2) {
1239
+ const value = entry?.[name2]?.total;
1240
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
1241
+ }
1242
+ function dayStats(date, entry) {
1243
+ const average = entry?.page_views?.average_read_time_in_seconds;
1244
+ const readSeconds = entry?.page_views?.total_read_time_in_seconds;
1245
+ return {
1246
+ date,
1247
+ page_views: total(entry, "page_views"),
1248
+ reactions: total(entry, "reactions"),
1249
+ comments: total(entry, "comments"),
1250
+ follows: total(entry, "follows"),
1251
+ ...typeof average === "number" ? { average_read_time_seconds: average } : {},
1252
+ ...typeof readSeconds === "number" ? { read_seconds: readSeconds } : {}
1253
+ };
1254
+ }
1255
+ var LIST_STATUSES = ["all", "published", "unpublished"];
775
1256
  var connector = defineConnector({
776
1257
  vendor: "devto",
777
1258
  label: "dev.to",
778
1259
  origins: ["https://dev.to"],
779
- credentials: ["api_key"],
780
- credentialLabels: { api_key: "dev.to API key" },
1260
+ credentials: ["apikey"],
1261
+ credentialLabels: { apikey: "dev.to API key" },
781
1262
  authHeaders: (credentials) => ({
782
- "api-key": credentials["api_key"],
1263
+ "api-key": credentials["apikey"],
783
1264
  accept: "application/vnd.forem.api-v1+json"
784
1265
  }),
785
1266
  tools: [
@@ -793,7 +1274,7 @@ var connector = defineConnector({
793
1274
  properties: {
794
1275
  status: {
795
1276
  type: "string",
796
- enum: ["all", "published", "unpublished"],
1277
+ enum: [...LIST_STATUSES],
797
1278
  default: "all",
798
1279
  description: "all (default), published, or unpublished (drafts)."
799
1280
  },
@@ -807,14 +1288,49 @@ var connector = defineConnector({
807
1288
  const page = typeof state?.["p"] === "number" ? state["p"] : 1;
808
1289
  const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
809
1290
  const perPage = typeof state?.["n"] === "number" ? state["n"] : args.per_page;
810
- const { data } = await h.api({ path: `/api/articles/me/${args.status}`, query: { page, per_page: perPage } });
1291
+ const status = typeof state?.["s"] === "string" && LIST_STATUSES.includes(state["s"]) ? state["s"] : args.status;
1292
+ const { data } = await h.api({ path: `/api/articles/me/${status}`, query: { page, per_page: perPage } });
811
1293
  const articles = Array.isArray(data) ? data : [];
812
1294
  return h.page({
813
1295
  key: "articles",
814
1296
  items: articles.map(trimArticle).slice(skip),
815
- extra: { status: args.status, page },
816
- resumeAt: (index) => h.makeCursor({ p: page, o: skip + index, n: perPage }),
817
- ...articles.length >= perPage ? { nextPage: h.makeCursor({ p: page + 1, o: 0, n: perPage }) } : {}
1297
+ extra: { status, page },
1298
+ resumeAt: (index) => h.makeCursor({ s: status, p: page, o: skip + index, n: perPage }),
1299
+ ...articles.length >= perPage ? { nextPage: h.makeCursor({ s: status, p: page + 1, o: 0, n: perPage }) } : {}
1300
+ });
1301
+ }
1302
+ },
1303
+ {
1304
+ name: "get_article",
1305
+ kind: "read",
1306
+ title: "Get a dev.to article with its Markdown",
1307
+ description: "Returns one article with its Markdown body, to read it or to edit it with update_article: one of the account's drafts, or a published article by id. A long body comes in parts: pass nextCursor back as cursor for the rest.",
1308
+ inputSchema: {
1309
+ type: "object",
1310
+ properties: {
1311
+ id: { type: "integer", minimum: 1, description: "The article id, from list_my_articles." },
1312
+ cursor: { type: "string", description: "nextCursor from the previous result, for the next part of the body." }
1313
+ },
1314
+ required: ["id"],
1315
+ additionalProperties: false
1316
+ },
1317
+ async run(args, h) {
1318
+ const state = h.cursor(args.cursor);
1319
+ if (state && state["i"] !== args.id) {
1320
+ throw new ToolFailure("The cursor belongs to another article. Pass the same id as in the previous call, or leave cursor out.");
1321
+ }
1322
+ const offset = typeof state?.["o"] === "number" ? state["o"] : 0;
1323
+ const article = await findArticle(h, args.id);
1324
+ const body = typeof article?.body_markdown === "string" ? article.body_markdown : "";
1325
+ const part = bodyPart(body, Math.min(offset, body.length));
1326
+ return compact({
1327
+ ...trimArticle(article),
1328
+ author: article?.user?.username,
1329
+ ai_disclosure_level: article?.ai_disclosure_level,
1330
+ cover_image: article?.cover_image,
1331
+ body_markdown: part.text,
1332
+ body_part: { start: Math.min(offset, body.length), end: part.end, length: body.length },
1333
+ nextCursor: part.end < body.length ? h.makeCursor({ i: args.id, o: part.end }) : void 0
818
1334
  });
819
1335
  }
820
1336
  },
@@ -828,7 +1344,11 @@ var connector = defineConnector({
828
1344
  type: "object",
829
1345
  properties: {
830
1346
  ...ARTICLE_FIELDS,
831
- organization_id: { type: "integer", minimum: 1, description: "Post under this dev.to organization (the account must be a member)." },
1347
+ organization_id: {
1348
+ type: "integer",
1349
+ minimum: 1,
1350
+ description: "Post under this dev.to organization (the account must be a member). Its id comes from api_get /api/organizations/<username>."
1351
+ },
832
1352
  ai_disclosure_level: { type: "string", enum: [...DISCLOSURE_LEVELS], description: DISCLOSURE_HELP }
833
1353
  },
834
1354
  required: ["title", "body_markdown", "ai_disclosure_level"],
@@ -845,7 +1365,7 @@ var connector = defineConnector({
845
1365
  kind: "update",
846
1366
  check: "list_my_articles",
847
1367
  title: "Publish or update a dev.to article",
848
- description: "Changes one of the account's dev.to articles: only the fields given are changed. published: true publishes a draft (it goes live and gets its final URL); published: false turns a published article back into a draft. Editing a published article changes it live.",
1368
+ description: "Changes one of the account's dev.to articles: only the fields given are changed (tags, when given, replace all tags). published: true publishes a draft (it goes live and gets its final URL); published: false turns a published article back into a draft. Editing a published article changes it live. Read the current body first with get_article.",
849
1369
  inputSchema: {
850
1370
  type: "object",
851
1371
  properties: {
@@ -867,7 +1387,80 @@ var connector = defineConnector({
867
1387
  const { data } = await saveArticle(h, "PUT", `/api/articles/${args.id}`, article);
868
1388
  return trimSaved(data, args);
869
1389
  }
870
- }
1390
+ },
1391
+ {
1392
+ name: "get_analytics",
1393
+ kind: "read",
1394
+ title: "Get dev.to analytics",
1395
+ description: "The account's dev.to statistics: with start, page views, reactions, comments, new followers and the average read time per day (dev.to groups days older than 180 days by week) and their totals; without start, the lifetime totals. For one article with article_id, or an organization's articles with organization_id. Pass nextCursor back as cursor for more days.",
1396
+ inputSchema: {
1397
+ type: "object",
1398
+ properties: {
1399
+ start: { ...DATE_SCHEMA, description: "The first day, YYYY-MM-DD. Leave out for the lifetime totals." },
1400
+ end: { ...DATE_SCHEMA, description: "The last day, YYYY-MM-DD (default today); only with start." },
1401
+ article_id: { type: "integer", minimum: 1, description: "Only this article of the account." },
1402
+ organization_id: { type: "integer", minimum: 1, description: "Only this organization's articles (one the account may see)." },
1403
+ cursor: { type: "string", description: "nextCursor from the previous result." }
1404
+ },
1405
+ additionalProperties: false
1406
+ },
1407
+ async run(args, h) {
1408
+ const state = h.cursor(args.cursor);
1409
+ const text = (key, fallback) => state ? typeof state[key] === "string" ? state[key] : void 0 : fallback;
1410
+ const number = (key, fallback) => state ? typeof state[key] === "number" ? state[key] : void 0 : fallback;
1411
+ const start = text("s", args.start);
1412
+ const end = text("e", args.end);
1413
+ const articleId = number("a", args.article_id);
1414
+ const organizationId = number("g", args.organization_id);
1415
+ const skip = number("o", 0) ?? 0;
1416
+ if (end !== void 0 && start === void 0) throw new ToolFailure("end needs start: give the first day too, or leave both out for the lifetime totals.");
1417
+ if (start !== void 0 && end !== void 0 && end < start) throw new ToolFailure("end is before start.");
1418
+ if (articleId !== void 0 && organizationId !== void 0) throw new ToolFailure("Give article_id or organization_id, not both.");
1419
+ const scope = {};
1420
+ if (articleId !== void 0) scope["article_id"] = articleId;
1421
+ if (organizationId !== void 0) scope["organization_id"] = organizationId;
1422
+ const errors = {
1423
+ 404: "dev.to's analytics are not available here: the account may not have them yet, or the article or organization is not one it may see",
1424
+ 422: "dev.to did not accept the dates (use YYYY-MM-DD)"
1425
+ };
1426
+ if (start === void 0) {
1427
+ const { data: data2 } = await h.api({ path: "/api/analytics/totals", query: { ...scope }, errors });
1428
+ const stats = dayStats("", data2);
1429
+ const { date: _date, read_seconds: _read, ...totals2 } = stats;
1430
+ return { scope: Object.keys(scope).length ? scope : "account", period: "lifetime", totals: totals2 };
1431
+ }
1432
+ const { data } = await h.api({ path: "/api/analytics/historical", query: { start, end, ...scope }, errors });
1433
+ const rows = Object.entries(data && typeof data === "object" && !Array.isArray(data) ? data : {}).filter(([date, entry]) => /^\d{4}-\d{2}-\d{2}$/.test(date) && entry && typeof entry === "object").map(([date, entry]) => dayStats(date, entry)).sort((a, b) => a.date.localeCompare(b.date));
1434
+ const views = rows.reduce((sum, row) => sum + row.page_views, 0);
1435
+ const readSeconds = rows.reduce((sum, row) => sum + (row.read_seconds ?? 0), 0);
1436
+ const totals = compact({
1437
+ page_views: views,
1438
+ reactions: rows.reduce((sum, row) => sum + row.reactions, 0),
1439
+ comments: rows.reduce((sum, row) => sum + row.comments, 0),
1440
+ follows: rows.reduce((sum, row) => sum + row.follows, 0),
1441
+ average_read_time_seconds: views > 0 && readSeconds > 0 ? Math.round(readSeconds / views) : void 0
1442
+ });
1443
+ const state0 = { s: start, ...end ? { e: end } : {}, ...articleId ? { a: articleId } : {}, ...organizationId ? { g: organizationId } : {} };
1444
+ return h.page({
1445
+ key: "days",
1446
+ items: rows.slice(skip).map(({ read_seconds: _read, ...row }) => row),
1447
+ extra: {
1448
+ scope: Object.keys(scope).length ? scope : "account",
1449
+ range: compact({ start, end: end ?? rows[rows.length - 1]?.date }),
1450
+ totals,
1451
+ days_count: rows.length
1452
+ },
1453
+ resumeAt: (index) => h.makeCursor({ ...state0, o: skip + index })
1454
+ });
1455
+ }
1456
+ },
1457
+ // The rest of the Forem API: followers, comments, reactions, reading list, organizations.
1458
+ ...apiTools({
1459
+ label: "dev.to",
1460
+ description: "The dev.to (Forem) API v1 at https://dev.to/api, with the connected API key: paths start with /api/, such as /api/articles/me/published, /api/followers/users, /api/readinglist, /api/organizations/<username> (an organization's id) or /api/comments (with a_id in query). Reference: https://developers.forem.com/api/v1.",
1461
+ basePath: "/api/",
1462
+ methods: ["POST", "PUT", "DELETE"]
1463
+ })
871
1464
  ]
872
1465
  });
873
1466
  module.exports = connector;