@wiro-ai/wiro-agent-connectors 0.1.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.
- package/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +190 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +69 -0
- package/dist/host/env.d.ts +16 -0
- package/dist/host/env.js +52 -0
- package/dist/host/guarded-fetch.d.ts +40 -0
- package/dist/host/guarded-fetch.js +236 -0
- package/dist/host/index.d.ts +9 -0
- package/dist/host/index.js +24 -0
- package/dist/host/ip.d.ts +1 -0
- package/dist/host/ip.js +81 -0
- package/dist/host/load.d.ts +12 -0
- package/dist/host/load.js +70 -0
- package/dist/host/server.d.ts +21 -0
- package/dist/host/server.js +54 -0
- package/dist/types.d.ts +82 -0
- package/dist/types.js +6 -0
- package/dist/vendors/bluesky.js +1187 -0
- package/dist/vendors/devto.js +873 -0
- package/dist/vendors/serper.js +771 -0
- package/package.json +64 -0
|
@@ -0,0 +1,1187 @@
|
|
|
1
|
+
/* bluesky connector module (MIT License). Built from src/vendors/bluesky; do not edit. */
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/core/errors.ts
|
|
5
|
+
var ToolFailure = class extends Error {
|
|
6
|
+
details;
|
|
7
|
+
constructor(message, details = {}) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "ToolFailure";
|
|
10
|
+
this.details = details;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
var OutcomeUnknown = class extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "OutcomeUnknown";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// src/core/text.ts
|
|
21
|
+
var encoder = new TextEncoder();
|
|
22
|
+
var decoder = new TextDecoder();
|
|
23
|
+
function utf8Bytes(text) {
|
|
24
|
+
return encoder.encode(text);
|
|
25
|
+
}
|
|
26
|
+
function utf8Length(text) {
|
|
27
|
+
return encoder.encode(text).length;
|
|
28
|
+
}
|
|
29
|
+
function utf8Decode(bytes) {
|
|
30
|
+
return decoder.decode(bytes);
|
|
31
|
+
}
|
|
32
|
+
function base64UrlEncode(bytes) {
|
|
33
|
+
let binary = "";
|
|
34
|
+
for (let i = 0; i < bytes.length; i += 32768) {
|
|
35
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
36
|
+
}
|
|
37
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
38
|
+
}
|
|
39
|
+
function base64UrlDecode(text) {
|
|
40
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
|
|
41
|
+
const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
|
|
42
|
+
const binary = atob(padded);
|
|
43
|
+
const bytes = new Uint8Array(binary.length);
|
|
44
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
45
|
+
return bytes;
|
|
46
|
+
}
|
|
47
|
+
function truncate(text, max) {
|
|
48
|
+
if (text.length <= max) return text;
|
|
49
|
+
const points = Array.from(text);
|
|
50
|
+
if (points.length <= max) return text;
|
|
51
|
+
return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
|
|
52
|
+
}
|
|
53
|
+
function cleanVendorText(text, max = 300) {
|
|
54
|
+
if (typeof text !== "string") return void 0;
|
|
55
|
+
if (/^\s*</.test(text)) return void 0;
|
|
56
|
+
const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
57
|
+
return line ? truncate(line, max) : void 0;
|
|
58
|
+
}
|
|
59
|
+
function formatNumber(value) {
|
|
60
|
+
return value.toLocaleString("en-US");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/core/http.ts
|
|
64
|
+
var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
65
|
+
var USER_AGENT = "agent-connectors";
|
|
66
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
67
|
+
function errorCode(error) {
|
|
68
|
+
const code = error?.code;
|
|
69
|
+
return typeof code === "string" ? code : void 0;
|
|
70
|
+
}
|
|
71
|
+
function describe(error) {
|
|
72
|
+
const name2 = error?.name;
|
|
73
|
+
const code = errorCode(error);
|
|
74
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
75
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
76
|
+
if (code === "TOO_LARGE") return "the reply was too large";
|
|
77
|
+
return cleanVendorText(error?.message, 200) ?? "a network error";
|
|
78
|
+
}
|
|
79
|
+
function retryAfterSeconds(headers, now = Date.now()) {
|
|
80
|
+
const retryAfter = headers.get("retry-after");
|
|
81
|
+
if (retryAfter) {
|
|
82
|
+
const seconds = Number(retryAfter);
|
|
83
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
84
|
+
const date = Date.parse(retryAfter);
|
|
85
|
+
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
|
|
86
|
+
}
|
|
87
|
+
const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
|
|
88
|
+
if (reset) {
|
|
89
|
+
const value = Number(reset);
|
|
90
|
+
if (Number.isFinite(value) && value >= 0) {
|
|
91
|
+
return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return void 0;
|
|
95
|
+
}
|
|
96
|
+
function vendorCode(data) {
|
|
97
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
98
|
+
for (const key of ["error", "code"]) {
|
|
99
|
+
const value = data[key];
|
|
100
|
+
if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
|
|
101
|
+
}
|
|
102
|
+
return void 0;
|
|
103
|
+
}
|
|
104
|
+
function vendorMessage(data) {
|
|
105
|
+
if (typeof data === "string") return cleanVendorText(data);
|
|
106
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
107
|
+
const record = data;
|
|
108
|
+
for (const key of ["message", "error_description", "error", "detail", "title"]) {
|
|
109
|
+
const value = record[key];
|
|
110
|
+
if (typeof value === "string" && value.trim()) return cleanVendorText(value);
|
|
111
|
+
const nested = value?.message;
|
|
112
|
+
if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
|
|
113
|
+
}
|
|
114
|
+
if (Array.isArray(record["errors"])) {
|
|
115
|
+
const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
|
|
116
|
+
if (messages.length) return cleanVendorText(messages.join("; "));
|
|
117
|
+
}
|
|
118
|
+
return void 0;
|
|
119
|
+
}
|
|
120
|
+
var TooLarge = class extends Error {
|
|
121
|
+
constructor(limit) {
|
|
122
|
+
super(`the reply is larger than ${formatNumber(limit)} bytes`);
|
|
123
|
+
this.limit = limit;
|
|
124
|
+
}
|
|
125
|
+
limit;
|
|
126
|
+
};
|
|
127
|
+
async function readCapped(response, maxBytes) {
|
|
128
|
+
const declared = Number(response.headers.get("content-length"));
|
|
129
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
130
|
+
await response.body?.cancel().catch(() => {
|
|
131
|
+
});
|
|
132
|
+
throw new TooLarge(maxBytes);
|
|
133
|
+
}
|
|
134
|
+
if (!response.body) return new Uint8Array(0);
|
|
135
|
+
const reader = response.body.getReader();
|
|
136
|
+
const chunks = [];
|
|
137
|
+
let total = 0;
|
|
138
|
+
for (; ; ) {
|
|
139
|
+
const { done, value } = await reader.read();
|
|
140
|
+
if (done) break;
|
|
141
|
+
total += value.byteLength;
|
|
142
|
+
if (total > maxBytes) {
|
|
143
|
+
await reader.cancel().catch(() => {
|
|
144
|
+
});
|
|
145
|
+
throw new TooLarge(maxBytes);
|
|
146
|
+
}
|
|
147
|
+
chunks.push(value);
|
|
148
|
+
}
|
|
149
|
+
const bytes = new Uint8Array(total);
|
|
150
|
+
let offset = 0;
|
|
151
|
+
for (const chunk of chunks) {
|
|
152
|
+
bytes.set(chunk, offset);
|
|
153
|
+
offset += chunk.byteLength;
|
|
154
|
+
}
|
|
155
|
+
return bytes;
|
|
156
|
+
}
|
|
157
|
+
function parseBody(bytes, contentType) {
|
|
158
|
+
if (bytes.length === 0) return null;
|
|
159
|
+
const text = utf8Decode(bytes);
|
|
160
|
+
if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
|
|
161
|
+
try {
|
|
162
|
+
return JSON.parse(text);
|
|
163
|
+
} catch {
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return text;
|
|
167
|
+
}
|
|
168
|
+
function createHttp(env) {
|
|
169
|
+
const { label, ctx } = env;
|
|
170
|
+
const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
|
|
171
|
+
function failureFor(status, headers, data, request) {
|
|
172
|
+
const message = vendorMessage(data);
|
|
173
|
+
const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
|
|
174
|
+
const retryAfter = retryAfterSeconds(headers);
|
|
175
|
+
const code = vendorCode(data);
|
|
176
|
+
const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
|
|
177
|
+
const custom = request.errors?.[status];
|
|
178
|
+
const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
|
|
179
|
+
if (status >= 500) {
|
|
180
|
+
if (request.write) {
|
|
181
|
+
return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
|
|
182
|
+
}
|
|
183
|
+
return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
|
|
184
|
+
}
|
|
185
|
+
if (status === 429) {
|
|
186
|
+
return new ToolFailure(
|
|
187
|
+
`${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
|
|
188
|
+
{ status, ...extra }
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
if (status === 401) {
|
|
192
|
+
return new ToolFailure(
|
|
193
|
+
withCustom(`${label} rejected the credentials (HTTP 401)${said}. Check that the ${env.credentialLabel} is correct and still active.${nothingChanged}`),
|
|
194
|
+
{ status, ...extra }
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
|
|
198
|
+
if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
|
|
199
|
+
if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
|
|
200
|
+
return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
|
|
201
|
+
}
|
|
202
|
+
async function api(request) {
|
|
203
|
+
const method = request.method ?? "GET";
|
|
204
|
+
if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
|
|
205
|
+
throw new Error(`read-only tool sent ${method}`);
|
|
206
|
+
}
|
|
207
|
+
const origin = request.origin ?? env.origins[0];
|
|
208
|
+
if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
|
|
209
|
+
const url = new URL(request.path, origin);
|
|
210
|
+
if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
|
|
211
|
+
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
212
|
+
if (value !== void 0 && value !== null) url.searchParams.set(key, String(value));
|
|
213
|
+
}
|
|
214
|
+
const headers = {
|
|
215
|
+
accept: "application/json",
|
|
216
|
+
"user-agent": USER_AGENT,
|
|
217
|
+
...request.auth === false ? {} : env.authHeaders(),
|
|
218
|
+
...request.headers
|
|
219
|
+
};
|
|
220
|
+
let body;
|
|
221
|
+
if (request.json !== void 0) {
|
|
222
|
+
body = JSON.stringify(request.json);
|
|
223
|
+
headers["content-type"] = "application/json";
|
|
224
|
+
} else if (request.body) {
|
|
225
|
+
body = request.body;
|
|
226
|
+
headers["content-type"] = request.contentType ?? "application/octet-stream";
|
|
227
|
+
}
|
|
228
|
+
const started = Date.now();
|
|
229
|
+
if (request.write) env.onWriteSent();
|
|
230
|
+
let response;
|
|
231
|
+
try {
|
|
232
|
+
response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
|
|
233
|
+
} catch (error) {
|
|
234
|
+
env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
|
|
235
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
236
|
+
throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
|
|
237
|
+
}
|
|
238
|
+
if (request.write) {
|
|
239
|
+
throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
|
|
240
|
+
}
|
|
241
|
+
throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
|
|
242
|
+
}
|
|
243
|
+
env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
|
|
244
|
+
let bytes;
|
|
245
|
+
try {
|
|
246
|
+
bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
if (request.write && (response.ok || response.status >= 500)) {
|
|
249
|
+
throw new OutcomeUnknown(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}), so it is not known whether the change was made.`);
|
|
250
|
+
}
|
|
251
|
+
throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
|
|
252
|
+
}
|
|
253
|
+
const data = parseBody(bytes, response.headers.get("content-type"));
|
|
254
|
+
if (response.ok) return { status: response.status, headers: response.headers, data };
|
|
255
|
+
throw failureFor(response.status, response.headers, data, request);
|
|
256
|
+
}
|
|
257
|
+
async function media(rawUrl, options) {
|
|
258
|
+
const { what } = options;
|
|
259
|
+
let url;
|
|
260
|
+
try {
|
|
261
|
+
url = new URL(rawUrl);
|
|
262
|
+
} catch {
|
|
263
|
+
throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
|
|
264
|
+
}
|
|
265
|
+
if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
|
|
266
|
+
const started = Date.now();
|
|
267
|
+
let response;
|
|
268
|
+
try {
|
|
269
|
+
response = await ctx.fetch(url.toString(), {
|
|
270
|
+
method: "GET",
|
|
271
|
+
headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
|
|
272
|
+
...ctx.signal ? { signal: ctx.signal } : {}
|
|
273
|
+
});
|
|
274
|
+
} catch (error) {
|
|
275
|
+
env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
|
|
276
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
277
|
+
throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
|
|
278
|
+
}
|
|
279
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
280
|
+
}
|
|
281
|
+
env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
|
|
282
|
+
if (!response.ok) {
|
|
283
|
+
await response.body?.cancel().catch(() => {
|
|
284
|
+
});
|
|
285
|
+
throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
|
|
286
|
+
}
|
|
287
|
+
try {
|
|
288
|
+
const bytes = await readCapped(response, options.maxBytes);
|
|
289
|
+
return { bytes, contentType: response.headers.get("content-type") };
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (error instanceof TooLarge) {
|
|
292
|
+
throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
|
|
293
|
+
}
|
|
294
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return { api, media };
|
|
298
|
+
}
|
|
299
|
+
|
|
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;
|
|
352
|
+
try {
|
|
353
|
+
const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
|
|
354
|
+
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
355
|
+
return state;
|
|
356
|
+
}
|
|
357
|
+
} catch {
|
|
358
|
+
}
|
|
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
|
+
);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// src/core/schema.ts
|
|
365
|
+
var patterns = /* @__PURE__ */ new Map();
|
|
366
|
+
function patternOf(source) {
|
|
367
|
+
let compiled = patterns.get(source);
|
|
368
|
+
if (!compiled) {
|
|
369
|
+
compiled = new RegExp(source, "u");
|
|
370
|
+
patterns.set(source, compiled);
|
|
371
|
+
}
|
|
372
|
+
return compiled;
|
|
373
|
+
}
|
|
374
|
+
function isPlainObject(value) {
|
|
375
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
376
|
+
}
|
|
377
|
+
function isHttpUrl(value) {
|
|
378
|
+
try {
|
|
379
|
+
const url = new URL(value);
|
|
380
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
381
|
+
} catch {
|
|
382
|
+
return false;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
function name(path) {
|
|
386
|
+
return `\`${path}\``;
|
|
387
|
+
}
|
|
388
|
+
function child(path, key) {
|
|
389
|
+
return path ? `${path}.${key}` : key;
|
|
390
|
+
}
|
|
391
|
+
function checkValue(schema, value, path, issues) {
|
|
392
|
+
switch (schema.type) {
|
|
393
|
+
case "object":
|
|
394
|
+
checkObject(schema, value, path, issues);
|
|
395
|
+
return;
|
|
396
|
+
case "array": {
|
|
397
|
+
if (!Array.isArray(value)) {
|
|
398
|
+
issues.push(`${name(path)} must be an array`);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
402
|
+
issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
|
|
403
|
+
}
|
|
404
|
+
if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
|
|
405
|
+
issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
|
|
406
|
+
}
|
|
407
|
+
if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
|
|
408
|
+
issues.push(`${name(path)} must not repeat an item`);
|
|
409
|
+
}
|
|
410
|
+
if (schema.items) {
|
|
411
|
+
value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
|
|
412
|
+
}
|
|
413
|
+
break;
|
|
414
|
+
}
|
|
415
|
+
case "string": {
|
|
416
|
+
if (typeof value !== "string") {
|
|
417
|
+
issues.push(`${name(path)} must be a string`);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
const length = Array.from(value).length;
|
|
421
|
+
if (schema.minLength !== void 0 && length < schema.minLength) {
|
|
422
|
+
issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
|
|
423
|
+
}
|
|
424
|
+
if (schema.maxLength !== void 0 && length > schema.maxLength) {
|
|
425
|
+
issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
|
|
426
|
+
}
|
|
427
|
+
if (schema.format === "uri" && !isHttpUrl(value)) {
|
|
428
|
+
issues.push(`${name(path)} must be an absolute http(s) URL`);
|
|
429
|
+
} else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
|
|
430
|
+
issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
|
|
431
|
+
}
|
|
432
|
+
break;
|
|
433
|
+
}
|
|
434
|
+
case "integer":
|
|
435
|
+
case "number": {
|
|
436
|
+
if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
|
|
437
|
+
issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
441
|
+
issues.push(`${name(path)} must be at least ${schema.minimum}`);
|
|
442
|
+
}
|
|
443
|
+
if (schema.maximum !== void 0 && value > schema.maximum) {
|
|
444
|
+
issues.push(`${name(path)} must be at most ${schema.maximum}`);
|
|
445
|
+
}
|
|
446
|
+
break;
|
|
447
|
+
}
|
|
448
|
+
case "boolean":
|
|
449
|
+
if (typeof value !== "boolean") {
|
|
450
|
+
issues.push(`${name(path)} must be true or false`);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
break;
|
|
454
|
+
default:
|
|
455
|
+
break;
|
|
456
|
+
}
|
|
457
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
458
|
+
issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
function checkObject(schema, value, path, issues) {
|
|
462
|
+
if (!isPlainObject(value)) {
|
|
463
|
+
issues.push(`${path ? name(path) : "the arguments"} must be an object`);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const properties = schema.properties ?? {};
|
|
467
|
+
for (const key of schema.required ?? []) {
|
|
468
|
+
if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
|
|
469
|
+
}
|
|
470
|
+
const unknown = [];
|
|
471
|
+
for (const [key, item] of Object.entries(value)) {
|
|
472
|
+
const property = properties[key];
|
|
473
|
+
if (!property) {
|
|
474
|
+
if (schema.additionalProperties === false) unknown.push(key);
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
if (item === void 0 || item === null) continue;
|
|
478
|
+
checkValue(property, item, child(path, key), issues);
|
|
479
|
+
}
|
|
480
|
+
if (unknown.length) {
|
|
481
|
+
const known = Object.keys(properties);
|
|
482
|
+
issues.push(`unknown ${path ? `field${unknown.length > 1 ? "s" : ""} in ${name(path)}` : `argument${unknown.length > 1 ? "s" : ""}`} ${unknown.map((key) => JSON.stringify(key)).join(", ")}` + (known.length ? ` (expected: ${known.join(", ")})` : ""));
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
function copyDefault(value) {
|
|
486
|
+
return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
|
|
487
|
+
}
|
|
488
|
+
function validateArguments(schema, args) {
|
|
489
|
+
const input = args === void 0 || args === null ? {} : args;
|
|
490
|
+
if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
|
|
491
|
+
const value = { ...input };
|
|
492
|
+
if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
|
|
493
|
+
const issues = [];
|
|
494
|
+
checkObject(schema, value, "", issues);
|
|
495
|
+
if (issues.length) return { ok: false, issues };
|
|
496
|
+
for (const [key, property] of Object.entries(schema.properties ?? {})) {
|
|
497
|
+
if (value[key] === null) delete value[key];
|
|
498
|
+
if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
|
|
499
|
+
}
|
|
500
|
+
return { ok: true, value };
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// src/core/connector.ts
|
|
504
|
+
var ANNOTATIONS = {
|
|
505
|
+
read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
506
|
+
create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
507
|
+
update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
508
|
+
delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true }
|
|
509
|
+
};
|
|
510
|
+
var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
|
|
511
|
+
var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
512
|
+
var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
513
|
+
function deepFreeze(value) {
|
|
514
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
515
|
+
Object.freeze(value);
|
|
516
|
+
for (const item of Object.values(value)) deepFreeze(item);
|
|
517
|
+
}
|
|
518
|
+
return value;
|
|
519
|
+
}
|
|
520
|
+
function assertDefinition(def) {
|
|
521
|
+
const problem = (message) => {
|
|
522
|
+
throw new Error(`connector "${def.vendor}": ${message}`);
|
|
523
|
+
};
|
|
524
|
+
if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
|
|
525
|
+
if (!def.label?.trim()) problem("label is required");
|
|
526
|
+
if (!def.origins.length) problem("at least one origin is required");
|
|
527
|
+
for (const origin of def.origins) {
|
|
528
|
+
let url;
|
|
529
|
+
try {
|
|
530
|
+
url = new URL(origin);
|
|
531
|
+
} catch {
|
|
532
|
+
}
|
|
533
|
+
if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
|
|
534
|
+
}
|
|
535
|
+
for (const name2 of def.credentials) {
|
|
536
|
+
if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
|
|
537
|
+
}
|
|
538
|
+
const names = /* @__PURE__ */ new Set();
|
|
539
|
+
for (const tool of def.tools) {
|
|
540
|
+
if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
541
|
+
if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
|
|
542
|
+
names.add(tool.name);
|
|
543
|
+
if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
|
|
544
|
+
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`);
|
|
546
|
+
if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
|
|
547
|
+
problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
for (const tool of def.tools) {
|
|
551
|
+
if (tool.kind === "read") continue;
|
|
552
|
+
const check = def.tools.find((candidate) => candidate.name === tool.check);
|
|
553
|
+
if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
function result(payload, isError) {
|
|
557
|
+
return { content: [{ type: "text", text: JSON.stringify(payload) }], ...isError ? { isError: true } : {} };
|
|
558
|
+
}
|
|
559
|
+
function failure(message, details = {}) {
|
|
560
|
+
return result({ error: message, ...details }, true);
|
|
561
|
+
}
|
|
562
|
+
function trimmed(values) {
|
|
563
|
+
const out = {};
|
|
564
|
+
if (typeof values !== "object" || values === null) return out;
|
|
565
|
+
for (const [key, value] of Object.entries(values)) {
|
|
566
|
+
if (value === void 0 || value === null) continue;
|
|
567
|
+
const text = String(value).trim();
|
|
568
|
+
if (text) out[key] = text;
|
|
569
|
+
}
|
|
570
|
+
return out;
|
|
571
|
+
}
|
|
572
|
+
function defineConnector(def) {
|
|
573
|
+
assertDefinition(def);
|
|
574
|
+
const { label } = def;
|
|
575
|
+
const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
|
|
576
|
+
const toolList = def.tools.map((tool) => tool.name).join(", ");
|
|
577
|
+
const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
|
|
578
|
+
const descriptors = def.tools.map((tool) => ({
|
|
579
|
+
name: tool.name,
|
|
580
|
+
title: tool.title,
|
|
581
|
+
description: tool.description,
|
|
582
|
+
inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
|
|
583
|
+
annotations: { ...ANNOTATIONS[tool.kind] }
|
|
584
|
+
}));
|
|
585
|
+
async function call(toolName, args, ctx) {
|
|
586
|
+
const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
|
|
587
|
+
if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
|
|
588
|
+
if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
|
|
589
|
+
const log = (text) => {
|
|
590
|
+
try {
|
|
591
|
+
ctx.log?.(text);
|
|
592
|
+
} catch {
|
|
593
|
+
}
|
|
594
|
+
};
|
|
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.`);
|
|
600
|
+
}
|
|
601
|
+
const parsed = validateArguments(tool.inputSchema, args);
|
|
602
|
+
if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
|
|
603
|
+
const frozenCredentials = Object.freeze({ ...credentials });
|
|
604
|
+
let writeSent = false;
|
|
605
|
+
const http = createHttp({
|
|
606
|
+
vendor: def.vendor,
|
|
607
|
+
label,
|
|
608
|
+
tool: tool.name,
|
|
609
|
+
readOnly: tool.kind === "read",
|
|
610
|
+
origins: def.origins,
|
|
611
|
+
credentialLabel: def.credentials.map(credentialLabel).join(" and "),
|
|
612
|
+
ctx,
|
|
613
|
+
authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
|
|
614
|
+
log,
|
|
615
|
+
onWriteSent: () => {
|
|
616
|
+
writeSent = true;
|
|
617
|
+
}
|
|
618
|
+
});
|
|
619
|
+
const helpers = {
|
|
620
|
+
tool: tool.name,
|
|
621
|
+
credentials: frozenCredentials,
|
|
622
|
+
ctx,
|
|
623
|
+
api: http.api,
|
|
624
|
+
media: http.media,
|
|
625
|
+
page: (input) => fitPage(input),
|
|
626
|
+
cursor: (cursor) => decodeCursor(tool.name, cursor),
|
|
627
|
+
makeCursor: (state) => encodeCursor(tool.name, state),
|
|
628
|
+
log
|
|
629
|
+
};
|
|
630
|
+
try {
|
|
631
|
+
const data = await tool.run(parsed.value, helpers);
|
|
632
|
+
const fitted = shrinkToFit(data ?? {});
|
|
633
|
+
if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
|
|
634
|
+
const payload = fitted.value;
|
|
635
|
+
return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false);
|
|
636
|
+
} catch (error) {
|
|
637
|
+
if (error instanceof OutcomeUnknown) {
|
|
638
|
+
return result({
|
|
639
|
+
outcome: "unknown",
|
|
640
|
+
check: tool.check,
|
|
641
|
+
error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
|
|
642
|
+
}, true);
|
|
643
|
+
}
|
|
644
|
+
if (error instanceof ToolFailure) return failure(error.message, error.details);
|
|
645
|
+
log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
|
|
646
|
+
if (writeSent) {
|
|
647
|
+
return result({
|
|
648
|
+
outcome: "unknown",
|
|
649
|
+
check: tool.check,
|
|
650
|
+
error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
|
|
651
|
+
}, true);
|
|
652
|
+
}
|
|
653
|
+
return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
return deepFreeze({
|
|
657
|
+
vendor: def.vendor,
|
|
658
|
+
origins: [...def.origins],
|
|
659
|
+
credentials: [...def.credentials],
|
|
660
|
+
tools: descriptors,
|
|
661
|
+
call
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// src/vendors/bluesky/image.ts
|
|
666
|
+
function ascii(bytes, start, length) {
|
|
667
|
+
return String.fromCharCode(...bytes.subarray(start, start + length));
|
|
668
|
+
}
|
|
669
|
+
function sniffImage(bytes) {
|
|
670
|
+
if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
|
|
671
|
+
if (bytes.length >= 8 && [137, 80, 78, 71, 13, 10, 26, 10].every((value, index) => bytes[index] === value)) return "image/png";
|
|
672
|
+
if (bytes.length >= 12 && ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WEBP") return "image/webp";
|
|
673
|
+
return void 0;
|
|
674
|
+
}
|
|
675
|
+
function valid(size) {
|
|
676
|
+
return size.width > 0 && size.height > 0 ? size : void 0;
|
|
677
|
+
}
|
|
678
|
+
function jpegSize(bytes) {
|
|
679
|
+
let offset = 2;
|
|
680
|
+
while (offset + 9 < bytes.length) {
|
|
681
|
+
if (bytes[offset] !== 255) return void 0;
|
|
682
|
+
const marker = bytes[offset + 1];
|
|
683
|
+
if (marker === 255) {
|
|
684
|
+
offset++;
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
|
|
688
|
+
return valid({
|
|
689
|
+
height: bytes[offset + 5] << 8 | bytes[offset + 6],
|
|
690
|
+
width: bytes[offset + 7] << 8 | bytes[offset + 8]
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
if (marker >= 208 && marker <= 217 || marker === 1) {
|
|
694
|
+
offset += 2;
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
697
|
+
const length = bytes[offset + 2] << 8 | bytes[offset + 3];
|
|
698
|
+
if (length < 2) return void 0;
|
|
699
|
+
offset += 2 + length;
|
|
700
|
+
}
|
|
701
|
+
return void 0;
|
|
702
|
+
}
|
|
703
|
+
function webpSize(bytes) {
|
|
704
|
+
if (bytes.length < 30) return void 0;
|
|
705
|
+
const chunk = ascii(bytes, 12, 4);
|
|
706
|
+
const at = (index) => bytes[index];
|
|
707
|
+
if (chunk === "VP8 ") {
|
|
708
|
+
return valid({ width: (at(26) | at(27) << 8) & 16383, height: (at(28) | at(29) << 8) & 16383 });
|
|
709
|
+
}
|
|
710
|
+
if (chunk === "VP8L" && at(20) === 47) {
|
|
711
|
+
const bits = at(21) | at(22) << 8 | at(23) << 16 | at(24) << 24;
|
|
712
|
+
return valid({ width: (bits & 16383) + 1, height: (bits >>> 14 & 16383) + 1 });
|
|
713
|
+
}
|
|
714
|
+
if (chunk === "VP8X") {
|
|
715
|
+
return valid({ width: 1 + (at(24) | at(25) << 8 | at(26) << 16), height: 1 + (at(27) | at(28) << 8 | at(29) << 16) });
|
|
716
|
+
}
|
|
717
|
+
return void 0;
|
|
718
|
+
}
|
|
719
|
+
function imageSize(bytes, type) {
|
|
720
|
+
if (type === "image/png") {
|
|
721
|
+
if (bytes.length < 24 || ascii(bytes, 12, 4) !== "IHDR") return void 0;
|
|
722
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
723
|
+
return valid({ width: view.getUint32(16), height: view.getUint32(20) });
|
|
724
|
+
}
|
|
725
|
+
if (type === "image/jpeg") return jpegSize(bytes);
|
|
726
|
+
return webpSize(bytes);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// src/vendors/bluesky/richtext.ts
|
|
730
|
+
var MAX_GRAPHEMES = 300;
|
|
731
|
+
var MAX_TEXT_BYTES = 3e3;
|
|
732
|
+
var MAX_TAG_GRAPHEMES = 64;
|
|
733
|
+
var MAX_MENTIONS = 10;
|
|
734
|
+
var segmenter = typeof Intl !== "undefined" && typeof Intl.Segmenter === "function" ? new Intl.Segmenter(void 0, { granularity: "grapheme" }) : void 0;
|
|
735
|
+
function graphemeLength(text) {
|
|
736
|
+
if (!segmenter) return Array.from(text).length;
|
|
737
|
+
let count = 0;
|
|
738
|
+
for (const _segment of segmenter.segment(text)) count++;
|
|
739
|
+
return count;
|
|
740
|
+
}
|
|
741
|
+
var LINK = /(^|[\s(\[])(https?:\/\/[^\s<>"]+)/gu;
|
|
742
|
+
var MENTION = /(^|[\s(\[])@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+)/gu;
|
|
743
|
+
var TAG = /(^|\s)[##]([^\s##]+)/gu;
|
|
744
|
+
function trimLink(url) {
|
|
745
|
+
let trimmed2 = url.replace(/[.,;:!?'"’”]+$/u, "");
|
|
746
|
+
while (trimmed2.endsWith(")") && (trimmed2.match(/\(/g)?.length ?? 0) < (trimmed2.match(/\)/g)?.length ?? 0)) {
|
|
747
|
+
trimmed2 = trimmed2.slice(0, -1).replace(/[.,;:!?'"’”]+$/u, "");
|
|
748
|
+
}
|
|
749
|
+
return trimmed2;
|
|
750
|
+
}
|
|
751
|
+
function findLinks(text) {
|
|
752
|
+
const found = [];
|
|
753
|
+
for (const match of text.matchAll(LINK)) {
|
|
754
|
+
const url = trimLink(match[2]);
|
|
755
|
+
try {
|
|
756
|
+
new URL(url);
|
|
757
|
+
} catch {
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
const start = match.index + match[1].length;
|
|
761
|
+
found.push({ kind: "link", value: url, start, end: start + url.length });
|
|
762
|
+
}
|
|
763
|
+
return found;
|
|
764
|
+
}
|
|
765
|
+
function findMentions(text) {
|
|
766
|
+
const found = [];
|
|
767
|
+
for (const match of text.matchAll(MENTION)) {
|
|
768
|
+
const handle = match[2];
|
|
769
|
+
const tld = handle.slice(handle.lastIndexOf(".") + 1);
|
|
770
|
+
if (!/^[a-zA-Z]/.test(tld)) continue;
|
|
771
|
+
const start = match.index + match[1].length;
|
|
772
|
+
found.push({ kind: "mention", value: handle.toLowerCase(), start, end: start + 1 + handle.length });
|
|
773
|
+
}
|
|
774
|
+
return found;
|
|
775
|
+
}
|
|
776
|
+
function findTags(text) {
|
|
777
|
+
const found = [];
|
|
778
|
+
for (const match of text.matchAll(TAG)) {
|
|
779
|
+
const tag = match[2].replace(/\p{P}+$/u, "");
|
|
780
|
+
if (!tag || /^\d+$/.test(tag) || graphemeLength(tag) > MAX_TAG_GRAPHEMES) continue;
|
|
781
|
+
const start = match.index + match[1].length;
|
|
782
|
+
found.push({ kind: "tag", value: tag, start, end: start + 1 + tag.length });
|
|
783
|
+
}
|
|
784
|
+
return found;
|
|
785
|
+
}
|
|
786
|
+
function overlaps(a, b) {
|
|
787
|
+
return a.start < b.end && b.start < a.end;
|
|
788
|
+
}
|
|
789
|
+
async function buildFacets(text, resolveHandle) {
|
|
790
|
+
const candidates = [...findLinks(text), ...findMentions(text), ...findTags(text)].sort((a, b) => a.start - b.start);
|
|
791
|
+
const chosen = [];
|
|
792
|
+
for (const candidate of candidates) {
|
|
793
|
+
if (!chosen.some((other) => overlaps(other, candidate))) chosen.push(candidate);
|
|
794
|
+
}
|
|
795
|
+
const handles = [...new Set(chosen.filter((item) => item.kind === "mention").map((item) => item.value))].slice(0, MAX_MENTIONS);
|
|
796
|
+
const dids = /* @__PURE__ */ new Map();
|
|
797
|
+
for (const handle of handles) dids.set(handle, await resolveHandle(handle));
|
|
798
|
+
const result2 = { facets: [], links: 0, mentions: 0, tags: 0, unresolvedMentions: [] };
|
|
799
|
+
for (const item of chosen) {
|
|
800
|
+
let feature;
|
|
801
|
+
if (item.kind === "link") {
|
|
802
|
+
feature = { $type: "app.bsky.richtext.facet#link", uri: item.value };
|
|
803
|
+
result2.links++;
|
|
804
|
+
} else if (item.kind === "tag") {
|
|
805
|
+
feature = { $type: "app.bsky.richtext.facet#tag", tag: item.value };
|
|
806
|
+
result2.tags++;
|
|
807
|
+
} else {
|
|
808
|
+
const did = dids.get(item.value);
|
|
809
|
+
if (!did) {
|
|
810
|
+
if (!result2.unresolvedMentions.includes(item.value)) result2.unresolvedMentions.push(item.value);
|
|
811
|
+
continue;
|
|
812
|
+
}
|
|
813
|
+
feature = { $type: "app.bsky.richtext.facet#mention", did };
|
|
814
|
+
result2.mentions++;
|
|
815
|
+
}
|
|
816
|
+
const byteStart = utf8Length(text.slice(0, item.start));
|
|
817
|
+
result2.facets.push({
|
|
818
|
+
index: { byteStart, byteEnd: byteStart + utf8Length(text.slice(item.start, item.end)) },
|
|
819
|
+
features: [feature]
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
return result2;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// src/vendors/bluesky/session.ts
|
|
826
|
+
var SESSION_TTL_MS = 10 * 60 * 1e3;
|
|
827
|
+
var MINUTE = 60 * 1e3;
|
|
828
|
+
var DAY = 24 * 60 * MINUTE;
|
|
829
|
+
var SIGN_IN_LIMITS = [
|
|
830
|
+
{ windowMs: 5 * MINUTE, max: 30, words: "30 sign-ins per 5 minutes" },
|
|
831
|
+
{ windowMs: DAY, max: 300, words: "300 sign-ins per day" }
|
|
832
|
+
];
|
|
833
|
+
var MAX_CACHED_SESSIONS = 64;
|
|
834
|
+
var JWT_PATTERN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
835
|
+
var sessions = /* @__PURE__ */ new Map();
|
|
836
|
+
var pending = /* @__PURE__ */ new Map();
|
|
837
|
+
var signIns = /* @__PURE__ */ new Map();
|
|
838
|
+
async function credentialKey(identifier, password) {
|
|
839
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(`${identifier}
|
|
840
|
+
${password}`)));
|
|
841
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
842
|
+
}
|
|
843
|
+
function jwtExpiry(jwt) {
|
|
844
|
+
try {
|
|
845
|
+
const payload = JSON.parse(utf8Decode(base64UrlDecode(jwt.split(".")[1] ?? "")));
|
|
846
|
+
return typeof payload?.exp === "number" ? payload.exp * 1e3 : void 0;
|
|
847
|
+
} catch {
|
|
848
|
+
return void 0;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
function remember(key, session) {
|
|
852
|
+
const now = Date.now();
|
|
853
|
+
for (const [other, cached] of sessions) if (cached.expiresAt <= now) sessions.delete(other);
|
|
854
|
+
while (sessions.size >= MAX_CACHED_SESSIONS) {
|
|
855
|
+
const oldest = sessions.keys().next().value;
|
|
856
|
+
if (oldest === void 0) break;
|
|
857
|
+
sessions.delete(oldest);
|
|
858
|
+
}
|
|
859
|
+
sessions.set(key, session);
|
|
860
|
+
}
|
|
861
|
+
function countSignIn(key) {
|
|
862
|
+
const now = Date.now();
|
|
863
|
+
const recent = (signIns.get(key) ?? []).filter((time) => time > now - DAY);
|
|
864
|
+
for (const limit of SIGN_IN_LIMITS) {
|
|
865
|
+
const inWindow = recent.filter((time) => time > now - limit.windowMs);
|
|
866
|
+
if (inWindow.length >= limit.max) {
|
|
867
|
+
const retryAfter = Math.max(1, Math.ceil((inWindow[0] + limit.windowMs - now) / 1e3));
|
|
868
|
+
throw new ToolFailure(
|
|
869
|
+
`Bluesky allows ${limit.words} for one account, and this connection has used them. Nothing was sent to Bluesky. Retry after ${retryAfter} seconds.`,
|
|
870
|
+
{ retryAfter }
|
|
871
|
+
);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
recent.push(now);
|
|
875
|
+
signIns.set(key, recent);
|
|
876
|
+
}
|
|
877
|
+
function signInFailure(error) {
|
|
878
|
+
if (!(error instanceof ToolFailure)) return error;
|
|
879
|
+
const { status, vendorCode: vendorCode2, retryAfter } = error.details;
|
|
880
|
+
const keep = { ...status !== void 0 ? { status } : {}, ...vendorCode2 ? { vendorCode: vendorCode2 } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
|
|
881
|
+
if (vendorCode2 === "AuthFactorTokenRequired") {
|
|
882
|
+
return new ToolFailure("Bluesky asked for an email sign-in code: the password given is the account password, not an app password. Create an app password in Bluesky's settings and use that.", keep);
|
|
883
|
+
}
|
|
884
|
+
if (vendorCode2 === "AccountTakedown") return new ToolFailure("Bluesky reports this account as taken down or suspended.", keep);
|
|
885
|
+
if (status === 401 || vendorCode2 === "AuthenticationRequired") {
|
|
886
|
+
return new ToolFailure(
|
|
887
|
+
"Bluesky refused the handle or app password: the app password may have been deleted or mistyped, or the account is not hosted by Bluesky.",
|
|
888
|
+
keep
|
|
889
|
+
);
|
|
890
|
+
}
|
|
891
|
+
if (status === 429) {
|
|
892
|
+
return new ToolFailure(
|
|
893
|
+
`Bluesky's sign-in limit for this account was reached (30 per 5 minutes, 300 per day). ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
|
|
894
|
+
keep
|
|
895
|
+
);
|
|
896
|
+
}
|
|
897
|
+
return error;
|
|
898
|
+
}
|
|
899
|
+
async function signIn(h, key) {
|
|
900
|
+
countSignIn(key);
|
|
901
|
+
let response;
|
|
902
|
+
try {
|
|
903
|
+
response = await h.api({
|
|
904
|
+
method: "POST",
|
|
905
|
+
path: "/xrpc/com.atproto.server.createSession",
|
|
906
|
+
json: { identifier: h.credentials["identifier"], password: h.credentials["app_password"] },
|
|
907
|
+
safe: true
|
|
908
|
+
});
|
|
909
|
+
} catch (error) {
|
|
910
|
+
throw signInFailure(error);
|
|
911
|
+
}
|
|
912
|
+
const data = response.data;
|
|
913
|
+
if (typeof data?.accessJwt !== "string" || !JWT_PATTERN.test(data.accessJwt) || typeof data?.did !== "string") {
|
|
914
|
+
throw new ToolFailure("Bluesky signed in but sent no usable session.");
|
|
915
|
+
}
|
|
916
|
+
if (data.active === false) {
|
|
917
|
+
throw new ToolFailure(`Bluesky reports this account as ${typeof data.status === "string" ? data.status : "inactive"}.`);
|
|
918
|
+
}
|
|
919
|
+
const now = Date.now();
|
|
920
|
+
const expiry = jwtExpiry(data.accessJwt);
|
|
921
|
+
const session = {
|
|
922
|
+
did: data.did,
|
|
923
|
+
handle: typeof data.handle === "string" ? data.handle : String(h.credentials["identifier"]),
|
|
924
|
+
accessJwt: data.accessJwt,
|
|
925
|
+
expiresAt: Math.min(now + SESSION_TTL_MS, expiry !== void 0 ? expiry - MINUTE : Infinity)
|
|
926
|
+
};
|
|
927
|
+
remember(key, session);
|
|
928
|
+
return session;
|
|
929
|
+
}
|
|
930
|
+
async function getSession(h) {
|
|
931
|
+
const key = await credentialKey(String(h.credentials["identifier"]), String(h.credentials["app_password"]));
|
|
932
|
+
const cached = sessions.get(key);
|
|
933
|
+
if (cached && cached.expiresAt > Date.now()) return cached;
|
|
934
|
+
sessions.delete(key);
|
|
935
|
+
const inFlight = pending.get(key);
|
|
936
|
+
if (inFlight) return inFlight;
|
|
937
|
+
const started = signIn(h, key).finally(() => pending.delete(key));
|
|
938
|
+
pending.set(key, started);
|
|
939
|
+
return started;
|
|
940
|
+
}
|
|
941
|
+
function forget(session) {
|
|
942
|
+
for (const [key, cached] of sessions) if (cached === session) sessions.delete(key);
|
|
943
|
+
}
|
|
944
|
+
function isExpired(error) {
|
|
945
|
+
if (!(error instanceof ToolFailure)) return false;
|
|
946
|
+
const { status, vendorCode: vendorCode2 } = error.details;
|
|
947
|
+
return (status === 400 || status === 401) && (vendorCode2 === "ExpiredToken" || vendorCode2 === "InvalidToken");
|
|
948
|
+
}
|
|
949
|
+
function xrpc(h, session, request) {
|
|
950
|
+
return h.api({ ...request, headers: { ...request.headers, authorization: `Bearer ${session.accessJwt}` } });
|
|
951
|
+
}
|
|
952
|
+
async function withSession(h, readOnly, work) {
|
|
953
|
+
const session = await getSession(h);
|
|
954
|
+
try {
|
|
955
|
+
return await work(session);
|
|
956
|
+
} catch (error) {
|
|
957
|
+
if (!isExpired(error)) throw error;
|
|
958
|
+
forget(session);
|
|
959
|
+
if (!readOnly) {
|
|
960
|
+
throw new ToolFailure("The Bluesky session expired before the request was accepted, so nothing was changed. Call the tool again.");
|
|
961
|
+
}
|
|
962
|
+
return work(await getSession(h));
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// src/vendors/bluesky/index.ts
|
|
967
|
+
var MAX_IMAGE_BYTES = 2e6;
|
|
968
|
+
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-]*)$";
|
|
969
|
+
function compact(value) {
|
|
970
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
|
|
971
|
+
}
|
|
972
|
+
function profileUrl(actor) {
|
|
973
|
+
return `https://bsky.app/profile/${encodeURIComponent(actor)}`;
|
|
974
|
+
}
|
|
975
|
+
function postUrl(handleOrDid, uri) {
|
|
976
|
+
const match = typeof uri === "string" ? /^at:\/\/[^/]+\/app\.bsky\.feed\.post\/([^/]+)$/.exec(uri) : null;
|
|
977
|
+
return match ? `${profileUrl(handleOrDid)}/post/${match[1]}` : void 0;
|
|
978
|
+
}
|
|
979
|
+
function trimProfile(profile) {
|
|
980
|
+
const handle = typeof profile?.handle === "string" ? profile.handle : void 0;
|
|
981
|
+
return compact({
|
|
982
|
+
did: profile?.did,
|
|
983
|
+
handle,
|
|
984
|
+
displayName: profile?.displayName || void 0,
|
|
985
|
+
description: typeof profile?.description === "string" && profile.description ? truncate(profile.description, 600) : void 0,
|
|
986
|
+
avatar: profile?.avatar,
|
|
987
|
+
followersCount: profile?.followersCount,
|
|
988
|
+
followsCount: profile?.followsCount,
|
|
989
|
+
postsCount: profile?.postsCount,
|
|
990
|
+
createdAt: profile?.createdAt,
|
|
991
|
+
url: handle ? profileUrl(handle) : void 0
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
function embedKind(embed) {
|
|
995
|
+
const type = typeof embed?.$type === "string" ? embed.$type : "";
|
|
996
|
+
const match = /^app\.bsky\.embed\.(\w+)/.exec(type);
|
|
997
|
+
return match ? match[1] : void 0;
|
|
998
|
+
}
|
|
999
|
+
function trimPost(post, session) {
|
|
1000
|
+
return compact({
|
|
1001
|
+
uri: post?.uri,
|
|
1002
|
+
cid: post?.cid,
|
|
1003
|
+
url: postUrl(post?.author?.handle ?? session.handle, post?.uri),
|
|
1004
|
+
text: typeof post?.record?.text === "string" ? post.record.text : void 0,
|
|
1005
|
+
createdAt: post?.record?.createdAt,
|
|
1006
|
+
likeCount: post?.likeCount,
|
|
1007
|
+
repostCount: post?.repostCount,
|
|
1008
|
+
replyCount: post?.replyCount,
|
|
1009
|
+
quoteCount: post?.quoteCount,
|
|
1010
|
+
isReply: post?.record?.reply ? true : void 0,
|
|
1011
|
+
embed: embedKind(post?.embed ?? post?.record?.embed)
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
async function resolver(h, handle) {
|
|
1015
|
+
try {
|
|
1016
|
+
const { data } = await h.api({ path: "/xrpc/com.atproto.identity.resolveHandle", query: { handle } });
|
|
1017
|
+
return typeof data?.did === "string" ? data.did : void 0;
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
if (error instanceof ToolFailure) return void 0;
|
|
1020
|
+
throw error;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
var connector = defineConnector({
|
|
1024
|
+
vendor: "bluesky",
|
|
1025
|
+
label: "Bluesky",
|
|
1026
|
+
origins: ["https://bsky.social"],
|
|
1027
|
+
credentials: ["identifier", "app_password"],
|
|
1028
|
+
credentialLabels: { identifier: "Bluesky handle", app_password: "Bluesky app password" },
|
|
1029
|
+
normalizeCredentials: (credentials) => {
|
|
1030
|
+
const identifier = (credentials["identifier"] ?? "").replace(/^@/, "");
|
|
1031
|
+
return { ...credentials, identifier: identifier.startsWith("did:") ? identifier : identifier.toLowerCase() };
|
|
1032
|
+
},
|
|
1033
|
+
tools: [
|
|
1034
|
+
{
|
|
1035
|
+
name: "get_profile",
|
|
1036
|
+
kind: "read",
|
|
1037
|
+
title: "Get a Bluesky profile",
|
|
1038
|
+
description: "Returns a Bluesky profile: DID, handle, display name, bio, avatar, and follower, following and post counts. Without actor it returns the connected account.",
|
|
1039
|
+
inputSchema: {
|
|
1040
|
+
type: "object",
|
|
1041
|
+
properties: {
|
|
1042
|
+
actor: {
|
|
1043
|
+
type: "string",
|
|
1044
|
+
minLength: 3,
|
|
1045
|
+
maxLength: 253,
|
|
1046
|
+
pattern: ACTOR_PATTERN,
|
|
1047
|
+
description: "A handle such as alice.bsky.social, or a DID. Leave out for the connected account."
|
|
1048
|
+
}
|
|
1049
|
+
},
|
|
1050
|
+
additionalProperties: false
|
|
1051
|
+
},
|
|
1052
|
+
async run(args, h) {
|
|
1053
|
+
const { data } = await withSession(h, true, (session) => xrpc(h, session, {
|
|
1054
|
+
path: "/xrpc/app.bsky.actor.getProfile",
|
|
1055
|
+
query: { actor: args.actor?.replace(/^@/, "") ?? session.did },
|
|
1056
|
+
errors: { 400: "Bluesky found no such profile" }
|
|
1057
|
+
}));
|
|
1058
|
+
return trimProfile(data);
|
|
1059
|
+
}
|
|
1060
|
+
},
|
|
1061
|
+
{
|
|
1062
|
+
name: "list_my_posts",
|
|
1063
|
+
kind: "read",
|
|
1064
|
+
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.",
|
|
1066
|
+
inputSchema: {
|
|
1067
|
+
type: "object",
|
|
1068
|
+
properties: {
|
|
1069
|
+
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)." },
|
|
1071
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1072
|
+
},
|
|
1073
|
+
additionalProperties: false
|
|
1074
|
+
},
|
|
1075
|
+
async run(args, h) {
|
|
1076
|
+
const state = h.cursor(args.cursor);
|
|
1077
|
+
const vendorCursor = typeof state?.["c"] === "string" ? state["c"] : void 0;
|
|
1078
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1079
|
+
const limit = typeof state?.["n"] === "number" ? state["n"] : args.limit;
|
|
1080
|
+
return withSession(h, true, async (session) => {
|
|
1081
|
+
const { data } = await xrpc(h, session, {
|
|
1082
|
+
path: "/xrpc/app.bsky.feed.getAuthorFeed",
|
|
1083
|
+
query: { actor: session.did, limit, filter: args.include_replies ? "posts_with_replies" : "posts_no_replies", cursor: vendorCursor }
|
|
1084
|
+
});
|
|
1085
|
+
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 });
|
|
1088
|
+
return h.page({
|
|
1089
|
+
key: "posts",
|
|
1090
|
+
items: posts,
|
|
1091
|
+
extra: { handle: session.handle },
|
|
1092
|
+
resumeAt: (index) => here(skip + index),
|
|
1093
|
+
...typeof data?.cursor === "string" && data.cursor ? { nextPage: h.makeCursor({ c: data.cursor, o: 0, n: limit }) } : {}
|
|
1094
|
+
});
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
},
|
|
1098
|
+
{
|
|
1099
|
+
name: "create_post",
|
|
1100
|
+
kind: "create",
|
|
1101
|
+
check: "list_my_posts",
|
|
1102
|
+
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.`,
|
|
1104
|
+
inputSchema: {
|
|
1105
|
+
type: "object",
|
|
1106
|
+
properties: {
|
|
1107
|
+
text: { type: "string", minLength: 1, maxLength: 3e3, description: "The post text, up to 300 characters." },
|
|
1108
|
+
langs: {
|
|
1109
|
+
type: "array",
|
|
1110
|
+
items: { type: "string", pattern: "^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*$" },
|
|
1111
|
+
maxItems: 3,
|
|
1112
|
+
uniqueItems: true,
|
|
1113
|
+
description: 'Up to 3 language codes of the text, e.g. ["en"].'
|
|
1114
|
+
},
|
|
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." }
|
|
1117
|
+
},
|
|
1118
|
+
required: ["text"],
|
|
1119
|
+
additionalProperties: false
|
|
1120
|
+
},
|
|
1121
|
+
async run(args, h) {
|
|
1122
|
+
const graphemes = graphemeLength(args.text);
|
|
1123
|
+
if (graphemes > MAX_GRAPHEMES || utf8Length(args.text) > MAX_TEXT_BYTES) {
|
|
1124
|
+
throw new ToolFailure(`The text has ${graphemes} characters; Bluesky allows ${MAX_GRAPHEMES} (and ${formatNumber(MAX_TEXT_BYTES)} bytes). Shorten it. Nothing was changed.`);
|
|
1125
|
+
}
|
|
1126
|
+
if (args.image_url && args.image_alt === void 0) {
|
|
1127
|
+
throw new ToolFailure("image_alt is required with image_url: describe the image for people who cannot see it. Nothing was changed.");
|
|
1128
|
+
}
|
|
1129
|
+
if (!args.image_url && args.image_alt !== void 0) {
|
|
1130
|
+
throw new ToolFailure("image_alt was given without image_url. Nothing was changed.");
|
|
1131
|
+
}
|
|
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 } : {} };
|
|
1139
|
+
}
|
|
1140
|
+
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 } : {} }]
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
const facets = await buildFacets(args.text, (handle) => resolver(h, handle));
|
|
1156
|
+
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1157
|
+
const record = compact({
|
|
1158
|
+
$type: "app.bsky.feed.post",
|
|
1159
|
+
text: args.text,
|
|
1160
|
+
createdAt,
|
|
1161
|
+
langs: args.langs,
|
|
1162
|
+
facets: facets.facets.length ? facets.facets : void 0,
|
|
1163
|
+
embed
|
|
1164
|
+
});
|
|
1165
|
+
const { data } = await xrpc(h, session, {
|
|
1166
|
+
method: "POST",
|
|
1167
|
+
path: "/xrpc/com.atproto.repo.createRecord",
|
|
1168
|
+
json: { repo: session.did, collection: "app.bsky.feed.post", record },
|
|
1169
|
+
write: true
|
|
1170
|
+
});
|
|
1171
|
+
return compact({
|
|
1172
|
+
uri: data?.uri,
|
|
1173
|
+
cid: data?.cid,
|
|
1174
|
+
url: postUrl(session.handle, data?.uri),
|
|
1175
|
+
createdAt,
|
|
1176
|
+
links: facets.links,
|
|
1177
|
+
mentions: facets.mentions,
|
|
1178
|
+
hashtags: facets.tags,
|
|
1179
|
+
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
|
|
1181
|
+
});
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
]
|
|
1186
|
+
});
|
|
1187
|
+
module.exports = connector;
|