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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1185 -34
  3. package/dist/cli.js +15 -12
  4. package/dist/core/credentials.d.ts +21 -0
  5. package/dist/core/credentials.js +45 -0
  6. package/dist/core/origins.d.ts +18 -0
  7. package/dist/core/origins.js +40 -0
  8. package/dist/core/upload-hosts.d.ts +15 -0
  9. package/dist/core/upload-hosts.js +43 -0
  10. package/dist/host/describe.d.ts +10 -0
  11. package/dist/host/describe.js +38 -0
  12. package/dist/host/env.d.ts +25 -2
  13. package/dist/host/env.js +24 -7
  14. package/dist/host/guarded-fetch.d.ts +36 -9
  15. package/dist/host/guarded-fetch.js +175 -52
  16. package/dist/host/index.d.ts +8 -5
  17. package/dist/host/index.js +12 -1
  18. package/dist/host/load.js +31 -1
  19. package/dist/host/server.d.ts +13 -2
  20. package/dist/host/server.js +15 -2
  21. package/dist/types.d.ts +96 -5
  22. package/dist/vendors/adapty.js +1303 -0
  23. package/dist/vendors/adjust.js +1372 -0
  24. package/dist/vendors/apollo.js +2499 -0
  25. package/dist/vendors/apple-appstore.js +2798 -0
  26. package/dist/vendors/beehiiv.js +1965 -0
  27. package/dist/vendors/blogger.js +1687 -0
  28. package/dist/vendors/bluesky.js +850 -127
  29. package/dist/vendors/brevo.js +2195 -0
  30. package/dist/vendors/calendarific.js +1116 -0
  31. package/dist/vendors/devto.js +685 -92
  32. package/dist/vendors/facebook-pages.js +2185 -0
  33. package/dist/vendors/firebase.js +1333 -0
  34. package/dist/vendors/ga4.js +1585 -0
  35. package/dist/vendors/gmail.js +1962 -0
  36. package/dist/vendors/google-ads.js +2201 -0
  37. package/dist/vendors/google-business.js +1621 -0
  38. package/dist/vendors/google-calendar.js +1936 -0
  39. package/dist/vendors/google-drive.js +2654 -0
  40. package/dist/vendors/google-merchant-center.js +1742 -0
  41. package/dist/vendors/google-play.js +1856 -0
  42. package/dist/vendors/google-search-console.js +1572 -0
  43. package/dist/vendors/hashnode.js +1722 -0
  44. package/dist/vendors/instagram.js +2249 -0
  45. package/dist/vendors/kaggle.js +2043 -0
  46. package/dist/vendors/keepa.js +2087 -0
  47. package/dist/vendors/linkedin.js +1588 -0
  48. package/dist/vendors/mailchimp.js +2402 -0
  49. package/dist/vendors/mastodon.js +1836 -0
  50. package/dist/vendors/meta-ads.js +2375 -0
  51. package/dist/vendors/notion.js +1950 -0
  52. package/dist/vendors/pinterest.js +1744 -0
  53. package/dist/vendors/qiita.js +1552 -0
  54. package/dist/vendors/reddit.js +1791 -0
  55. package/dist/vendors/revenuecat.js +1593 -0
  56. package/dist/vendors/roasit.js +1460 -0
  57. package/dist/vendors/sendgrid.js +2188 -0
  58. package/dist/vendors/serper.js +901 -179
  59. package/dist/vendors/shopify.js +2511 -0
  60. package/dist/vendors/threads.js +1869 -0
  61. package/dist/vendors/tiktok.js +2199 -0
  62. package/dist/vendors/tumblr.js +1793 -0
  63. package/dist/vendors/twitter.js +1650 -0
  64. package/dist/vendors/woocommerce.js +2258 -0
  65. package/dist/vendors/wordpress.js +1904 -0
  66. package/dist/vendors/youtube.js +2542 -0
  67. package/package.json +12 -1
@@ -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 clean2 = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
356
+ const points = Array.from(clean2);
357
+ if (points.length <= MAX_NAME) return clean2 || "file";
358
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean2)?.[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";
@@ -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 total = fileBytes + bytes.byteLength;
1038
+ if (total > fileLimit) {
1039
+ throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total)} bytes in all, more than the ${formatNumber(fileLimit)} bytes this host takes from one call.` : `The file has ${formatNumber(bytes.byteLength)} bytes, more than the ${formatNumber(fileLimit)} bytes this host takes.`);
1040
+ }
1041
+ fileBytes = total;
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,12 +1074,19 @@ 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/bluesky/image.ts
666
1091
  function ascii(bytes, start, length) {
667
1092
  return String.fromCharCode(...bytes.subarray(start, start + length));
@@ -726,6 +1151,73 @@ function imageSize(bytes, type) {
726
1151
  return webpSize(bytes);
727
1152
  }
728
1153
 
1154
+ // src/vendors/bluesky/links.ts
1155
+ var ACTOR = "(did:[a-z]+:[A-Za-z0-9._:%-]+|(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)";
1156
+ var RKEY = "([A-Za-z0-9._:~-]{1,512})";
1157
+ var WEB_LINK = new RegExp(`^https://(?:www\\.)?bsky\\.app/profile/${ACTOR}/post/${RKEY}/?(?:[?#].*)?$`);
1158
+ var AT_URI = new RegExp(`^at://${ACTOR}/app\\.bsky\\.feed\\.post/${RKEY}$`);
1159
+ function parsePostRef(value) {
1160
+ const text = value.trim();
1161
+ const match = WEB_LINK.exec(text) ?? AT_URI.exec(text);
1162
+ if (!match) return void 0;
1163
+ const actor = match[1];
1164
+ return { actor: actor.startsWith("did:") ? actor : actor.toLowerCase(), rkey: match[2] };
1165
+ }
1166
+ function postUri(did, rkey) {
1167
+ return `at://${did}/app.bsky.feed.post/${rkey}`;
1168
+ }
1169
+ var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
1170
+ function decodeEntities(text) {
1171
+ return text.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (whole, name2) => {
1172
+ if (name2[0] === "#") {
1173
+ const code = name2[1] === "x" || name2[1] === "X" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10);
1174
+ return Number.isFinite(code) && code > 0 && code <= 1114111 ? String.fromCodePoint(code) : whole;
1175
+ }
1176
+ return ENTITIES[name2.toLowerCase()] ?? whole;
1177
+ });
1178
+ }
1179
+ function clean(text, max) {
1180
+ if (text === void 0) return void 0;
1181
+ const line = decodeEntities(text).replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
1182
+ return line ? truncate(line, max) : void 0;
1183
+ }
1184
+ function attributes(tag) {
1185
+ const found = {};
1186
+ for (const match of tag.matchAll(/([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g)) {
1187
+ const name2 = match[1].toLowerCase();
1188
+ if (!(name2 in found)) found[name2] = match[2] ?? match[3] ?? match[4] ?? "";
1189
+ }
1190
+ return found;
1191
+ }
1192
+ function readPageCard(bytes, pageUrl) {
1193
+ const html = utf8Decode(bytes.subarray(0, 512 * 1024));
1194
+ const headEnd = html.search(/<\/head\s*>/i);
1195
+ const head = headEnd === -1 ? html : html.slice(0, headEnd);
1196
+ const meta = {};
1197
+ for (const match of head.matchAll(/<meta\b[^>]*>/gi)) {
1198
+ const attrs = attributes(match[0]);
1199
+ const key = (attrs["property"] ?? attrs["name"] ?? "").toLowerCase();
1200
+ if (key && attrs["content"] !== void 0 && !(key in meta)) meta[key] = attrs["content"];
1201
+ }
1202
+ const titleTag = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(head)?.[1];
1203
+ let image;
1204
+ const imageValue = meta["og:image"] ?? meta["og:image:url"] ?? meta["og:image:secure_url"] ?? meta["twitter:image"];
1205
+ if (imageValue) {
1206
+ try {
1207
+ const url = new URL(decodeEntities(imageValue.trim()), pageUrl);
1208
+ if (url.protocol === "https:") image = url.toString();
1209
+ } catch {
1210
+ }
1211
+ }
1212
+ const card = {};
1213
+ const title = clean(meta["og:title"] ?? meta["twitter:title"] ?? titleTag, 300);
1214
+ const description = clean(meta["og:description"] ?? meta["twitter:description"] ?? meta["description"], 1e3);
1215
+ if (title) card.title = title;
1216
+ if (description) card.description = description;
1217
+ if (image) card.image = image;
1218
+ return card;
1219
+ }
1220
+
729
1221
  // src/vendors/bluesky/richtext.ts
730
1222
  var MAX_GRAPHEMES = 300;
731
1223
  var MAX_TEXT_BYTES = 3e3;
@@ -835,8 +1327,8 @@ var JWT_PATTERN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
835
1327
  var sessions = /* @__PURE__ */ new Map();
836
1328
  var pending = /* @__PURE__ */ new Map();
837
1329
  var signIns = /* @__PURE__ */ new Map();
838
- async function credentialKey(identifier, password) {
839
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(`${identifier}
1330
+ async function credentialKey(handle, password) {
1331
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(`${handle}
840
1332
  ${password}`)));
841
1333
  return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
842
1334
  }
@@ -903,7 +1395,7 @@ async function signIn(h, key) {
903
1395
  response = await h.api({
904
1396
  method: "POST",
905
1397
  path: "/xrpc/com.atproto.server.createSession",
906
- json: { identifier: h.credentials["identifier"], password: h.credentials["app_password"] },
1398
+ json: { identifier: h.credentials["handle"], password: h.credentials["apppassword"] },
907
1399
  safe: true
908
1400
  });
909
1401
  } catch (error) {
@@ -920,7 +1412,7 @@ async function signIn(h, key) {
920
1412
  const expiry = jwtExpiry(data.accessJwt);
921
1413
  const session = {
922
1414
  did: data.did,
923
- handle: typeof data.handle === "string" ? data.handle : String(h.credentials["identifier"]),
1415
+ handle: typeof data.handle === "string" ? data.handle : String(h.credentials["handle"]),
924
1416
  accessJwt: data.accessJwt,
925
1417
  expiresAt: Math.min(now + SESSION_TTL_MS, expiry !== void 0 ? expiry - MINUTE : Infinity)
926
1418
  };
@@ -928,7 +1420,7 @@ async function signIn(h, key) {
928
1420
  return session;
929
1421
  }
930
1422
  async function getSession(h) {
931
- const key = await credentialKey(String(h.credentials["identifier"]), String(h.credentials["app_password"]));
1423
+ const key = await credentialKey(String(h.credentials["handle"]), String(h.credentials["apppassword"]));
932
1424
  const cached = sessions.get(key);
933
1425
  if (cached && cached.expiresAt > Date.now()) return cached;
934
1426
  sessions.delete(key);
@@ -965,7 +1457,13 @@ async function withSession(h, readOnly, work) {
965
1457
 
966
1458
  // src/vendors/bluesky/index.ts
967
1459
  var MAX_IMAGE_BYTES = 2e6;
1460
+ var MAX_THUMB_BYTES = 1e6;
1461
+ var MAX_PAGE_BYTES = 1e6;
1462
+ var MAX_IMAGES = 4;
1463
+ var MAX_GET_POSTS = 25;
968
1464
  var ACTOR_PATTERN = "^(did:[a-z]+:[A-Za-z0-9._:%-]+|@?[A-Za-z0-9][A-Za-z0-9.-]*\\.[A-Za-z][A-Za-z0-9-]*)$";
1465
+ var POST_REF_DESCRIPTION = "A post's bsky.app link (https://bsky.app/profile/<handle>/post/<id>) or its at:// URI.";
1466
+ var FILTERS = ["posts_with_replies", "posts_no_replies", "posts_and_author_threads", "posts_with_media"];
969
1467
  function compact(value) {
970
1468
  return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
971
1469
  }
@@ -996,17 +1494,21 @@ function embedKind(embed) {
996
1494
  const match = /^app\.bsky\.embed\.(\w+)/.exec(type);
997
1495
  return match ? match[1] : void 0;
998
1496
  }
999
- function trimPost(post, session) {
1497
+ function trimPost(post, fallbackHandle, withAuthor = false) {
1498
+ const author = post?.author?.handle ?? post?.author?.did;
1000
1499
  return compact({
1001
1500
  uri: post?.uri,
1002
1501
  cid: post?.cid,
1003
- url: postUrl(post?.author?.handle ?? session.handle, post?.uri),
1502
+ url: postUrl(author ?? fallbackHandle, post?.uri),
1503
+ author: withAuthor ? author : void 0,
1004
1504
  text: typeof post?.record?.text === "string" ? post.record.text : void 0,
1005
1505
  createdAt: post?.record?.createdAt,
1006
1506
  likeCount: post?.likeCount,
1007
1507
  repostCount: post?.repostCount,
1008
1508
  replyCount: post?.replyCount,
1009
1509
  quoteCount: post?.quoteCount,
1510
+ // Bluesky shows views to the post's author only, and only from 100.
1511
+ viewCount: post?.viewCount,
1010
1512
  isReply: post?.record?.reply ? true : void 0,
1011
1513
  embed: embedKind(post?.embed ?? post?.record?.embed)
1012
1514
  });
@@ -1020,15 +1522,53 @@ async function resolver(h, handle) {
1020
1522
  throw error;
1021
1523
  }
1022
1524
  }
1525
+ async function didOf(h, ref) {
1526
+ if (ref.actor.startsWith("did:")) return ref.actor;
1527
+ const did = await resolver(h, ref.actor);
1528
+ if (!did) throw new ToolFailure(`Bluesky found no account with the handle ${ref.actor}.`);
1529
+ return did;
1530
+ }
1531
+ function postRef(value, argument) {
1532
+ const ref = parsePostRef(value);
1533
+ if (!ref) {
1534
+ throw new ToolFailure(`${argument} is not a Bluesky post: use its bsky.app link (https://bsky.app/profile/<handle>/post/<id>) or its at:// URI. Nothing was sent.`);
1535
+ }
1536
+ return ref;
1537
+ }
1538
+ async function downloadPicture(h, url, what, maxBytes) {
1539
+ const { bytes } = await h.media(url, { what, maxBytes, accept: "image/jpeg,image/png,image/webp" });
1540
+ const type = sniffImage(bytes);
1541
+ if (!type) throw new ToolFailure(`The ${what} URL did not return a JPEG, PNG or WebP image. Nothing was changed.`);
1542
+ const size = imageSize(bytes, type);
1543
+ return { bytes, type, ...size ? { size } : {} };
1544
+ }
1545
+ async function uploadBlob(h, session, picture) {
1546
+ const { data } = await xrpc(h, session, {
1547
+ method: "POST",
1548
+ path: "/xrpc/com.atproto.repo.uploadBlob",
1549
+ body: picture.bytes,
1550
+ contentType: picture.type
1551
+ });
1552
+ if (!data?.blob) throw new ToolFailure("Bluesky accepted an image upload but sent back no blob. Nothing was posted.");
1553
+ return data.blob;
1554
+ }
1555
+ function accountMethodGuard(request) {
1556
+ const method = (request.segments[1] ?? "").toLowerCase();
1557
+ if (method.startsWith("com.atproto.server.") || request.method !== "GET" && method.startsWith("com.atproto.identity.")) {
1558
+ throw new ToolFailure(
1559
+ "Bluesky account, session and identity methods (com.atproto.server.* and com.atproto.identity.*) are not available here: manage the account in the Bluesky app. Nothing was sent."
1560
+ );
1561
+ }
1562
+ }
1023
1563
  var connector = defineConnector({
1024
1564
  vendor: "bluesky",
1025
1565
  label: "Bluesky",
1026
1566
  origins: ["https://bsky.social"],
1027
- credentials: ["identifier", "app_password"],
1028
- credentialLabels: { identifier: "Bluesky handle", app_password: "Bluesky app password" },
1567
+ credentials: ["handle", "apppassword"],
1568
+ credentialLabels: { handle: "Bluesky handle", apppassword: "Bluesky app password" },
1029
1569
  normalizeCredentials: (credentials) => {
1030
- const identifier = (credentials["identifier"] ?? "").replace(/^@/, "");
1031
- return { ...credentials, identifier: identifier.startsWith("did:") ? identifier : identifier.toLowerCase() };
1570
+ const handle = (credentials["handle"] ?? "").replace(/^@/, "");
1571
+ return { ...credentials, handle: handle.startsWith("did:") ? handle : handle.toLowerCase() };
1032
1572
  },
1033
1573
  tools: [
1034
1574
  {
@@ -1062,12 +1602,17 @@ var connector = defineConnector({
1062
1602
  name: "list_my_posts",
1063
1603
  kind: "read",
1064
1604
  title: "List my recent Bluesky posts",
1065
- description: "Lists the connected account's own recent posts, newest first (reposts of other people's posts are left out), with each post's URL, text, time, and like, repost, reply and quote counts. Pass nextCursor back as cursor for older posts.",
1605
+ description: "Lists the connected account's own recent posts and replies, newest first (reposts of other people's posts are left out), with each post's URL, text, time, like, repost, reply and quote counts, and views where Bluesky shows them (to the author, from 100). filter narrows it to posts without replies, posts and the account's own threads, or posts with media. Pass nextCursor back as cursor for older posts.",
1066
1606
  inputSchema: {
1067
1607
  type: "object",
1068
1608
  properties: {
1069
1609
  limit: { type: "integer", minimum: 1, maximum: 100, default: 25, description: "Posts to fetch, 1 to 100 (default 25)." },
1070
- include_replies: { type: "boolean", default: false, description: "Include the account's replies to other posts (default false)." },
1610
+ filter: {
1611
+ type: "string",
1612
+ enum: [...FILTERS],
1613
+ description: "posts_with_replies (default: posts and replies), posts_no_replies, posts_and_author_threads (posts and the account's own threads) or posts_with_media."
1614
+ },
1615
+ include_replies: { type: "boolean", description: "false is the same as filter posts_no_replies; true, or leaving it out, keeps the replies." },
1071
1616
  cursor: { type: "string", description: "nextCursor from the previous result." }
1072
1617
  },
1073
1618
  additionalProperties: false
@@ -1077,20 +1622,72 @@ var connector = defineConnector({
1077
1622
  const vendorCursor = typeof state?.["c"] === "string" ? state["c"] : void 0;
1078
1623
  const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
1079
1624
  const limit = typeof state?.["n"] === "number" ? state["n"] : args.limit;
1625
+ const chosen = args.filter ?? (args.include_replies === void 0 ? void 0 : args.include_replies ? "posts_with_replies" : "posts_no_replies");
1626
+ const carried = typeof state?.["f"] === "string" && FILTERS.includes(state["f"]) ? state["f"] : void 0;
1627
+ const filter = chosen ?? carried ?? "posts_with_replies";
1080
1628
  return withSession(h, true, async (session) => {
1081
1629
  const { data } = await xrpc(h, session, {
1082
1630
  path: "/xrpc/app.bsky.feed.getAuthorFeed",
1083
- query: { actor: session.did, limit, filter: args.include_replies ? "posts_with_replies" : "posts_no_replies", cursor: vendorCursor }
1631
+ query: { actor: session.did, limit, filter, cursor: vendorCursor }
1084
1632
  });
1085
1633
  const feed = Array.isArray(data?.feed) ? data.feed : [];
1086
- const posts = feed.filter((item) => !item?.reason && item?.post?.author?.did === session.did).map((item) => trimPost(item.post, session)).slice(skip);
1087
- const here = (offset) => h.makeCursor({ ...vendorCursor ? { c: vendorCursor } : {}, o: offset, n: limit });
1634
+ const posts = feed.filter((item) => !item?.reason && item?.post?.author?.did === session.did).map((item) => trimPost(item.post, session.handle)).slice(skip);
1635
+ const here = (offset) => h.makeCursor({ ...vendorCursor ? { c: vendorCursor } : {}, o: offset, n: limit, f: filter });
1088
1636
  return h.page({
1089
1637
  key: "posts",
1090
1638
  items: posts,
1091
1639
  extra: { handle: session.handle },
1092
1640
  resumeAt: (index) => here(skip + index),
1093
- ...typeof data?.cursor === "string" && data.cursor ? { nextPage: h.makeCursor({ c: data.cursor, o: 0, n: limit }) } : {}
1641
+ ...typeof data?.cursor === "string" && data.cursor ? { nextPage: h.makeCursor({ c: data.cursor, o: 0, n: limit, f: filter }) } : {}
1642
+ });
1643
+ });
1644
+ }
1645
+ },
1646
+ {
1647
+ name: "get_posts",
1648
+ kind: "read",
1649
+ title: "Get Bluesky posts by link",
1650
+ description: "Returns up to 25 posts, the account's own or anyone's, by their bsky.app links or at:// URIs: author, text, time, and like, repost, reply and quote counts, with views on the account's own posts from 100. Use it to check how known posts are doing, or whether a post went out or is gone (notFound).",
1651
+ inputSchema: {
1652
+ type: "object",
1653
+ properties: {
1654
+ posts: {
1655
+ type: "array",
1656
+ minItems: 1,
1657
+ maxItems: MAX_GET_POSTS,
1658
+ uniqueItems: true,
1659
+ items: { type: "string", minLength: 10, maxLength: 600, description: POST_REF_DESCRIPTION },
1660
+ description: "Up to 25 post links or at:// URIs."
1661
+ },
1662
+ cursor: { type: "string", description: "nextCursor from the previous result, with the same posts." }
1663
+ },
1664
+ required: ["posts"],
1665
+ additionalProperties: false
1666
+ },
1667
+ async run(args, h) {
1668
+ const state = h.cursor(args.cursor);
1669
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
1670
+ const refs = args.posts.map((value, index) => postRef(value, `posts[${index}]`));
1671
+ return withSession(h, true, async (session) => {
1672
+ const dids = /* @__PURE__ */ new Map([[session.handle, session.did]]);
1673
+ const uris = [];
1674
+ for (const ref of refs) {
1675
+ let did = ref.actor.startsWith("did:") ? ref.actor : dids.get(ref.actor);
1676
+ if (!did) {
1677
+ did = await didOf(h, ref);
1678
+ dids.set(ref.actor, did);
1679
+ }
1680
+ uris.push(postUri(did, ref.rkey));
1681
+ }
1682
+ const { data } = await xrpc(h, session, { path: "/xrpc/app.bsky.feed.getPosts", query: { uris } });
1683
+ const posts = Array.isArray(data?.posts) ? data.posts : [];
1684
+ const found = new Set(posts.map((post) => post?.uri));
1685
+ const missing = uris.filter((uri) => !found.has(uri));
1686
+ return h.page({
1687
+ key: "posts",
1688
+ items: posts.map((post) => trimPost(post, session.handle, true)).slice(skip),
1689
+ extra: missing.length ? { notFound: missing } : {},
1690
+ resumeAt: (index) => h.makeCursor({ o: skip + index })
1094
1691
  });
1095
1692
  });
1096
1693
  }
@@ -1100,11 +1697,11 @@ var connector = defineConnector({
1100
1697
  kind: "create",
1101
1698
  check: "list_my_posts",
1102
1699
  title: "Create a Bluesky post",
1103
- description: `Publishes a post on the connected Bluesky account right away: text up to 300 characters (Bluesky counts each emoji as one), with links, @handles and #hashtags made clickable, and optionally one image from a public https URL (JPEG, PNG or WebP, up to ${formatNumber(MAX_IMAGE_BYTES)} bytes) with alt text. Returns the post's URL. Bluesky has no edits.`,
1700
+ description: `Publishes a post on the connected Bluesky account right away: text up to 300 characters (Bluesky counts each emoji as one), with links, @handles and #hashtags made clickable; up to 4 images from public https URLs (JPEG, PNG or WebP, up to ${formatNumber(MAX_IMAGE_BYTES)} bytes each) with alt text, or one link card (title, description and picture from the page). reply_to makes it a reply, or the next post of a thread: pass the post above it. Returns the post's URL. Bluesky has no edits and no scheduling.`,
1104
1701
  inputSchema: {
1105
1702
  type: "object",
1106
1703
  properties: {
1107
- text: { type: "string", minLength: 1, maxLength: 3e3, description: "The post text, up to 300 characters." },
1704
+ text: { type: "string", maxLength: 3e3, description: "The post text, up to 300 characters. May be empty only with images or a link card." },
1108
1705
  langs: {
1109
1706
  type: "array",
1110
1707
  items: { type: "string", pattern: "^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*$" },
@@ -1112,55 +1709,133 @@ var connector = defineConnector({
1112
1709
  uniqueItems: true,
1113
1710
  description: 'Up to 3 language codes of the text, e.g. ["en"].'
1114
1711
  },
1115
- image_url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "A public https URL of one image to attach." },
1116
- image_alt: { type: "string", maxLength: 2e3, description: "Alt text describing the image; required with image_url." }
1712
+ images: {
1713
+ type: "array",
1714
+ minItems: 1,
1715
+ maxItems: MAX_IMAGES,
1716
+ items: {
1717
+ type: "object",
1718
+ properties: {
1719
+ url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "A public https URL of the image." },
1720
+ alt: { type: "string", minLength: 1, maxLength: 2e3, description: "Alt text: what the image shows, for people who cannot see it." }
1721
+ },
1722
+ required: ["url", "alt"],
1723
+ additionalProperties: false
1724
+ },
1725
+ description: "Up to 4 images, in order, each with alt text."
1726
+ },
1727
+ image_url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "One image to attach (the same as images with one item)." },
1728
+ image_alt: { type: "string", maxLength: 2e3, description: "Alt text for image_url; required with it." },
1729
+ link_card: {
1730
+ type: "object",
1731
+ properties: {
1732
+ url: { type: "string", format: "uri", maxLength: 2e3, description: "The page the card opens." },
1733
+ title: { type: "string", maxLength: 300, description: "The card title. Left out, it comes from the page itself." },
1734
+ description: { type: "string", maxLength: 1e3, description: "The card text. Left out, it comes from the page itself." },
1735
+ thumb_url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "A picture for the card (up to 1,000,000 bytes). Left out, the page's own picture is used when the page is read." }
1736
+ },
1737
+ required: ["url"],
1738
+ additionalProperties: false,
1739
+ description: "A link card under the text, only on a post without images."
1740
+ },
1741
+ reply_to: { type: "string", minLength: 10, maxLength: 600, description: `The post this one answers: ${POST_REF_DESCRIPTION}` }
1117
1742
  },
1118
- required: ["text"],
1119
1743
  additionalProperties: false
1120
1744
  },
1121
1745
  async run(args, h) {
1122
- const graphemes = graphemeLength(args.text);
1123
- if (graphemes > MAX_GRAPHEMES || utf8Length(args.text) > MAX_TEXT_BYTES) {
1746
+ const text = args.text ?? "";
1747
+ const graphemes = graphemeLength(text);
1748
+ if (graphemes > MAX_GRAPHEMES || utf8Length(text) > MAX_TEXT_BYTES) {
1124
1749
  throw new ToolFailure(`The text has ${graphemes} characters; Bluesky allows ${MAX_GRAPHEMES} (and ${formatNumber(MAX_TEXT_BYTES)} bytes). Shorten it. Nothing was changed.`);
1125
1750
  }
1126
1751
  if (args.image_url && args.image_alt === void 0) {
1127
1752
  throw new ToolFailure("image_alt is required with image_url: describe the image for people who cannot see it. Nothing was changed.");
1128
1753
  }
1129
- if (!args.image_url && args.image_alt !== void 0) {
1130
- throw new ToolFailure("image_alt was given without image_url. Nothing was changed.");
1754
+ if (!args.image_url && args.image_alt !== void 0) throw new ToolFailure("image_alt was given without image_url. Nothing was changed.");
1755
+ if (args.image_url && args.images) throw new ToolFailure("Give images or image_url, not both. Nothing was changed.");
1756
+ const images = args.images ?? (args.image_url ? [{ url: args.image_url, alt: args.image_alt ?? "" }] : []);
1757
+ if (images.length && args.link_card) {
1758
+ throw new ToolFailure("A Bluesky post has images or a link card, not both: leave out link_card (a link in the text stays clickable). Nothing was changed.");
1131
1759
  }
1132
- let image;
1133
- if (args.image_url) {
1134
- const { bytes } = await h.media(args.image_url, { what: "image", maxBytes: MAX_IMAGE_BYTES, accept: "image/jpeg,image/png,image/webp" });
1135
- const type = sniffImage(bytes);
1136
- if (!type) throw new ToolFailure("The image URL did not return a JPEG, PNG or WebP image. Nothing was changed.");
1137
- const size = imageSize(bytes, type);
1138
- image = { bytes, type, ...size ? { size } : {} };
1760
+ if (!text.trim() && !images.length && !args.link_card) throw new ToolFailure("The post needs text, images or a link card. Nothing was changed.");
1761
+ const replyRef = args.reply_to !== void 0 ? postRef(args.reply_to, "reply_to") : void 0;
1762
+ const pictures = [];
1763
+ for (const [index, image] of images.entries()) {
1764
+ pictures.push(await downloadPicture(h, image.url, images.length > 1 ? `image ${index + 1}` : "image", MAX_IMAGE_BYTES));
1765
+ }
1766
+ let card;
1767
+ if (args.link_card) {
1768
+ const { url } = args.link_card;
1769
+ if (!/^https?:\/\//i.test(url)) throw new ToolFailure("link_card.url must be an http or https address. Nothing was changed.");
1770
+ let title = args.link_card.title;
1771
+ let description = args.link_card.description;
1772
+ let thumbUrl = args.link_card.thumb_url;
1773
+ if (title === void 0) {
1774
+ if (!/^https:\/\//i.test(url)) throw new ToolFailure("The link card page is not https, so it is not read: give link_card.title and description. Nothing was changed.");
1775
+ let page;
1776
+ try {
1777
+ page = readPageCard((await h.media(url, { what: "link card page", maxBytes: MAX_PAGE_BYTES, accept: "text/html" })).bytes, url);
1778
+ } catch (error) {
1779
+ if (!(error instanceof ToolFailure)) throw error;
1780
+ throw new ToolFailure(
1781
+ `${error.message.replace(/ Nothing was changed\.$/, "")} Give link_card.title and link_card.description, or leave link_card out (a link in the text stays clickable). Nothing was changed.`
1782
+ );
1783
+ }
1784
+ if (!page.title) {
1785
+ throw new ToolFailure("The link card page names no title: give link_card.title and link_card.description, or leave link_card out. Nothing was changed.");
1786
+ }
1787
+ title = page.title;
1788
+ description = description ?? page.description;
1789
+ thumbUrl = thumbUrl ?? page.image;
1790
+ }
1791
+ card = { uri: url, title, description: description ?? "" };
1792
+ if (thumbUrl) {
1793
+ try {
1794
+ card.thumb = await downloadPicture(h, thumbUrl, "link card picture", MAX_THUMB_BYTES);
1795
+ } catch (error) {
1796
+ if (args.link_card.thumb_url || !(error instanceof ToolFailure)) throw error;
1797
+ card.thumbNote = "The page's picture could not be used, so the card has none.";
1798
+ }
1799
+ }
1139
1800
  }
1140
1801
  return withSession(h, false, async (session) => {
1141
- let embed;
1142
- if (image) {
1143
- const { data: data2 } = await xrpc(h, session, {
1144
- method: "POST",
1145
- path: "/xrpc/com.atproto.repo.uploadBlob",
1146
- body: image.bytes,
1147
- contentType: image.type
1148
- });
1149
- if (!data2?.blob) throw new ToolFailure("Bluesky accepted the image upload but sent back no blob. Nothing was posted.");
1150
- embed = {
1151
- $type: "app.bsky.embed.images",
1152
- images: [{ alt: args.image_alt ?? "", image: data2.blob, ...image.size ? { aspectRatio: image.size } : {} }]
1802
+ let reply;
1803
+ if (replyRef) {
1804
+ const did = replyRef.actor === session.handle ? session.did : await didOf(h, replyRef);
1805
+ const uri = postUri(did, replyRef.rkey);
1806
+ const { data: data2 } = await xrpc(h, session, { path: "/xrpc/app.bsky.feed.getPosts", query: { uris: [uri] } });
1807
+ const parent = Array.isArray(data2?.posts) ? data2.posts[0] : void 0;
1808
+ if (typeof parent?.uri !== "string" || typeof parent?.cid !== "string") {
1809
+ throw new ToolFailure("Bluesky found no post at reply_to (it may have been deleted). Nothing was posted.");
1810
+ }
1811
+ const root = parent.record?.reply?.root;
1812
+ reply = {
1813
+ root: typeof root?.uri === "string" && typeof root?.cid === "string" ? { uri: root.uri, cid: root.cid } : { uri: parent.uri, cid: parent.cid },
1814
+ parent: { uri: parent.uri, cid: parent.cid }
1153
1815
  };
1154
1816
  }
1155
- const facets = await buildFacets(args.text, (handle) => resolver(h, handle));
1817
+ let embed;
1818
+ if (pictures.length) {
1819
+ const uploaded = [];
1820
+ for (const [index, picture] of pictures.entries()) {
1821
+ const blob = await uploadBlob(h, session, picture);
1822
+ uploaded.push({ alt: images[index]?.alt ?? "", image: blob, ...picture.size ? { aspectRatio: picture.size } : {} });
1823
+ }
1824
+ embed = { $type: "app.bsky.embed.images", images: uploaded };
1825
+ } else if (card) {
1826
+ const thumb = card.thumb ? await uploadBlob(h, session, card.thumb) : void 0;
1827
+ embed = { $type: "app.bsky.embed.external", external: compact({ uri: card.uri, title: card.title, description: card.description, thumb }) };
1828
+ }
1829
+ const facets = await buildFacets(text, (handle) => resolver(h, handle));
1156
1830
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
1157
1831
  const record = compact({
1158
1832
  $type: "app.bsky.feed.post",
1159
- text: args.text,
1833
+ text,
1160
1834
  createdAt,
1161
1835
  langs: args.langs,
1162
1836
  facets: facets.facets.length ? facets.facets : void 0,
1163
- embed
1837
+ embed,
1838
+ reply
1164
1839
  });
1165
1840
  const { data } = await xrpc(h, session, {
1166
1841
  method: "POST",
@@ -1177,11 +1852,59 @@ var connector = defineConnector({
1177
1852
  mentions: facets.mentions,
1178
1853
  hashtags: facets.tags,
1179
1854
  unresolvedMentions: facets.unresolvedMentions.length ? facets.unresolvedMentions : void 0,
1180
- image: image ? compact({ type: image.type, bytes: image.bytes.length, width: image.size?.width, height: image.size?.height }) : void 0
1855
+ replyTo: reply ? reply["parent"].uri : void 0,
1856
+ images: pictures.length ? pictures.map((picture) => compact({ type: picture.type, bytes: picture.bytes.length, width: picture.size?.width, height: picture.size?.height })) : void 0,
1857
+ linkCard: card ? compact({ url: card.uri, title: card.title, picture: card.thumb ? true : void 0, note: card.thumbNote }) : void 0
1181
1858
  });
1182
1859
  });
1183
1860
  }
1184
- }
1861
+ },
1862
+ {
1863
+ name: "delete_post",
1864
+ kind: "delete",
1865
+ check: "get_posts",
1866
+ title: "Delete a Bluesky post",
1867
+ description: "Deletes one of the connected account's own posts, by its bsky.app link or at:// URI. It cannot be undone, and the post's replies stay. Other accounts' posts are refused before anything is sent.",
1868
+ inputSchema: {
1869
+ type: "object",
1870
+ properties: {
1871
+ post: { type: "string", minLength: 10, maxLength: 600, description: POST_REF_DESCRIPTION }
1872
+ },
1873
+ required: ["post"],
1874
+ additionalProperties: false
1875
+ },
1876
+ async run(args, h) {
1877
+ const ref = postRef(args.post, "post");
1878
+ return withSession(h, false, async (session) => {
1879
+ const did = ref.actor === session.handle ? session.did : await didOf(h, ref);
1880
+ if (did !== session.did) {
1881
+ throw new ToolFailure(`Only the connected account's own posts can be deleted, and this post belongs to ${ref.actor}. Nothing was sent.`);
1882
+ }
1883
+ try {
1884
+ await xrpc(h, session, {
1885
+ method: "POST",
1886
+ path: "/xrpc/com.atproto.repo.deleteRecord",
1887
+ json: { repo: session.did, collection: "app.bsky.feed.post", rkey: ref.rkey },
1888
+ write: true
1889
+ });
1890
+ } catch (error) {
1891
+ if (error instanceof OutcomeUnknown) throw new OutcomeUnknown(`${error.message} Once it is deleted, get_posts with the same link lists it under notFound.`);
1892
+ throw error;
1893
+ }
1894
+ return { deleted: true, uri: postUri(session.did, ref.rkey) };
1895
+ });
1896
+ }
1897
+ },
1898
+ // Any other XRPC method, with the account's session: a read may sign in
1899
+ // again once after the session expired, a procedure never runs twice.
1900
+ ...apiTools({
1901
+ label: "Bluesky",
1902
+ description: "The Bluesky (AT Protocol) XRPC API on https://bsky.social, with the connected account's session: a path is /xrpc/ and a method id. Queries are GET with their parameters in query, such as /xrpc/app.bsky.feed.getTimeline, /xrpc/app.bsky.feed.getPostThread (a post's replies) or /xrpc/app.bsky.notification.listNotifications; procedures are POST with a JSON body, such as /xrpc/com.atproto.repo.createRecord for a like or a repost. Reference: https://docs.bsky.app.",
1903
+ basePath: "/xrpc/",
1904
+ methods: ["POST"],
1905
+ guard: accountMethodGuard,
1906
+ send: (request, h) => withSession(h, !request.write, (session) => xrpc(h, session, request))
1907
+ })
1185
1908
  ]
1186
1909
  });
1187
1910
  module.exports = connector;