@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,873 @@
|
|
|
1
|
+
/* devto connector module (MIT License). Built from src/vendors/devto; 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/devto/index.ts
|
|
666
|
+
var DISCLOSURE_LEVELS = ["fully_autonomous", "some_ai", "no_ai"];
|
|
667
|
+
var DISCLOSURE_HELP = "dev.to's AI disclosure for the article: fully_autonomous when an AI wrote it (even if a person asked for it or approved it), some_ai when a person wrote it and AI helped with drafting, editing, code or translation, no_ai only when a person wrote it with no AI help.";
|
|
668
|
+
var TAG_SCHEMA = { type: "string", pattern: "^[A-Za-z0-9]{1,30}$", description: "Letters and digits only, up to 30." };
|
|
669
|
+
var ARTICLE_FIELDS = {
|
|
670
|
+
title: { type: "string", minLength: 1, maxLength: 128, description: "The article title, up to 128 characters." },
|
|
671
|
+
body_markdown: {
|
|
672
|
+
type: "string",
|
|
673
|
+
minLength: 1,
|
|
674
|
+
maxLength: 4e5,
|
|
675
|
+
description: "The article body in Markdown, without a YAML front matter block (pass title, tags and the rest as arguments)."
|
|
676
|
+
},
|
|
677
|
+
tags: { type: "array", items: TAG_SCHEMA, maxItems: 4, uniqueItems: true, description: 'Up to 4 tags, letters and digits only, e.g. ["javascript", "webdev"].' },
|
|
678
|
+
description: { type: "string", maxLength: 1e3, description: "A short summary shown in previews and search results." },
|
|
679
|
+
canonical_url: { type: "string", format: "uri", maxLength: 2e3, description: "The original URL when the article first appeared elsewhere, so search engines credit it." },
|
|
680
|
+
cover_image_url: { type: "string", format: "uri", maxLength: 2e3, description: "A public URL of the cover image (shown at 1000 x 420)." },
|
|
681
|
+
series: { type: "string", minLength: 1, maxLength: 128, description: "A series name; dev.to creates the series if it does not exist." }
|
|
682
|
+
};
|
|
683
|
+
function assertNoFrontMatter(body) {
|
|
684
|
+
if (body !== void 0 && /^?\s*---[ \t]*\r?\n/.test(body)) {
|
|
685
|
+
throw new ToolFailure(
|
|
686
|
+
"body_markdown starts with a YAML front matter block, which dev.to would read as article settings (it can even publish the article). Remove the block and pass title, tags, series, cover_image_url and canonical_url as arguments. Nothing was changed."
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function articleBody(args) {
|
|
691
|
+
const article = {};
|
|
692
|
+
if (args.title !== void 0) article["title"] = args.title;
|
|
693
|
+
if (args.body_markdown !== void 0) article["body_markdown"] = args.body_markdown;
|
|
694
|
+
if (args.tags !== void 0) article["tags"] = args.tags;
|
|
695
|
+
if (args.description !== void 0) article["description"] = args.description;
|
|
696
|
+
if (args.canonical_url !== void 0) article["canonical_url"] = args.canonical_url;
|
|
697
|
+
if (args.cover_image_url !== void 0) article["main_image"] = args.cover_image_url;
|
|
698
|
+
if (args.series !== void 0) article["series"] = args.series;
|
|
699
|
+
if (args.organization_id !== void 0) article["organization_id"] = args.organization_id;
|
|
700
|
+
if (args.ai_disclosure_level !== void 0) article["ai_disclosure_level"] = args.ai_disclosure_level;
|
|
701
|
+
return article;
|
|
702
|
+
}
|
|
703
|
+
function tagsOf(article) {
|
|
704
|
+
if (Array.isArray(article?.tags)) return article.tags.map(String);
|
|
705
|
+
if (Array.isArray(article?.tag_list)) return article.tag_list.map(String);
|
|
706
|
+
if (typeof article?.tag_list === "string") return article.tag_list.split(",").map((tag) => tag.trim()).filter(Boolean);
|
|
707
|
+
return void 0;
|
|
708
|
+
}
|
|
709
|
+
function editUrl(article) {
|
|
710
|
+
try {
|
|
711
|
+
const path = typeof article?.path === "string" && article.path ? article.path : new URL(String(article?.url)).pathname;
|
|
712
|
+
return path.startsWith("/") ? `https://dev.to${path}/edit` : void 0;
|
|
713
|
+
} catch {
|
|
714
|
+
return void 0;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
function compact(value) {
|
|
718
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
|
|
719
|
+
}
|
|
720
|
+
function trimArticle(article) {
|
|
721
|
+
return compact({
|
|
722
|
+
id: article?.id,
|
|
723
|
+
title: typeof article?.title === "string" ? truncate(article.title, 300) : void 0,
|
|
724
|
+
published: typeof article?.published === "boolean" ? article.published : Boolean(article?.published_at),
|
|
725
|
+
published_at: article?.published_at || void 0,
|
|
726
|
+
url: article?.url,
|
|
727
|
+
edit_url: editUrl(article),
|
|
728
|
+
tags: tagsOf(article),
|
|
729
|
+
description: typeof article?.description === "string" && article.description ? truncate(article.description, 300) : void 0,
|
|
730
|
+
page_views_count: article?.page_views_count,
|
|
731
|
+
public_reactions_count: article?.public_reactions_count,
|
|
732
|
+
comments_count: article?.comments_count,
|
|
733
|
+
reading_time_minutes: article?.reading_time_minutes,
|
|
734
|
+
canonical_url: article?.canonical_url,
|
|
735
|
+
organization: article?.organization?.username
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
function trimSaved(article, args) {
|
|
739
|
+
const warnings = Array.isArray(article?.warnings) ? article.warnings.map((item) => truncate(String(item), 300)) : [];
|
|
740
|
+
if (args.organization_id !== void 0 && !article?.organization) {
|
|
741
|
+
warnings.push(
|
|
742
|
+
`dev.to saved the article under the account itself, not organization ${args.organization_id}: the account must be a member of that organization to post there.`
|
|
743
|
+
);
|
|
744
|
+
}
|
|
745
|
+
return compact({
|
|
746
|
+
...trimArticle(article),
|
|
747
|
+
ai_disclosure_level: article?.ai_disclosure_level,
|
|
748
|
+
cover_image: article?.cover_image,
|
|
749
|
+
series: article?.series ?? void 0,
|
|
750
|
+
warnings: warnings.length ? warnings : void 0
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
async function saveArticle(h, method, path, article) {
|
|
754
|
+
try {
|
|
755
|
+
return await h.api({
|
|
756
|
+
method,
|
|
757
|
+
path,
|
|
758
|
+
json: { article },
|
|
759
|
+
write: true,
|
|
760
|
+
errors: {
|
|
761
|
+
404: "dev.to found no article with that id that this API key may edit.",
|
|
762
|
+
422: "dev.to did not accept the article."
|
|
763
|
+
}
|
|
764
|
+
});
|
|
765
|
+
} catch (error) {
|
|
766
|
+
if (error instanceof ToolFailure && error.details.status === 422 && /already been used/i.test(error.message)) {
|
|
767
|
+
throw new ToolFailure(
|
|
768
|
+
`${error.message} An earlier attempt may already have saved this article: check list_my_articles (status unpublished) before trying again.`,
|
|
769
|
+
error.details
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
throw error;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
var connector = defineConnector({
|
|
776
|
+
vendor: "devto",
|
|
777
|
+
label: "dev.to",
|
|
778
|
+
origins: ["https://dev.to"],
|
|
779
|
+
credentials: ["api_key"],
|
|
780
|
+
credentialLabels: { api_key: "dev.to API key" },
|
|
781
|
+
authHeaders: (credentials) => ({
|
|
782
|
+
"api-key": credentials["api_key"],
|
|
783
|
+
accept: "application/vnd.forem.api-v1+json"
|
|
784
|
+
}),
|
|
785
|
+
tools: [
|
|
786
|
+
{
|
|
787
|
+
name: "list_my_articles",
|
|
788
|
+
kind: "read",
|
|
789
|
+
title: "List my dev.to articles",
|
|
790
|
+
description: "Lists the account's own dev.to articles, newest first: drafts and published articles, or one of the two. Each has its id, title, URL, edit URL, tags, and for published articles the page views, reactions and comments (dev.to shows page views to the author only). Pass nextCursor back as cursor for more.",
|
|
791
|
+
inputSchema: {
|
|
792
|
+
type: "object",
|
|
793
|
+
properties: {
|
|
794
|
+
status: {
|
|
795
|
+
type: "string",
|
|
796
|
+
enum: ["all", "published", "unpublished"],
|
|
797
|
+
default: "all",
|
|
798
|
+
description: "all (default), published, or unpublished (drafts)."
|
|
799
|
+
},
|
|
800
|
+
per_page: { type: "integer", minimum: 1, maximum: 100, default: 30, description: "Articles per page, 1 to 100 (default 30)." },
|
|
801
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
802
|
+
},
|
|
803
|
+
additionalProperties: false
|
|
804
|
+
},
|
|
805
|
+
async run(args, h) {
|
|
806
|
+
const state = h.cursor(args.cursor);
|
|
807
|
+
const page = typeof state?.["p"] === "number" ? state["p"] : 1;
|
|
808
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
809
|
+
const perPage = typeof state?.["n"] === "number" ? state["n"] : args.per_page;
|
|
810
|
+
const { data } = await h.api({ path: `/api/articles/me/${args.status}`, query: { page, per_page: perPage } });
|
|
811
|
+
const articles = Array.isArray(data) ? data : [];
|
|
812
|
+
return h.page({
|
|
813
|
+
key: "articles",
|
|
814
|
+
items: articles.map(trimArticle).slice(skip),
|
|
815
|
+
extra: { status: args.status, page },
|
|
816
|
+
resumeAt: (index) => h.makeCursor({ p: page, o: skip + index, n: perPage }),
|
|
817
|
+
...articles.length >= perPage ? { nextPage: h.makeCursor({ p: page + 1, o: 0, n: perPage }) } : {}
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
},
|
|
821
|
+
{
|
|
822
|
+
name: "create_draft_article",
|
|
823
|
+
kind: "create",
|
|
824
|
+
check: "list_my_articles",
|
|
825
|
+
title: "Create a dev.to draft article",
|
|
826
|
+
description: "Saves a new article on dev.to as an unpublished draft; nothing becomes public. Returns its id, preview URL and edit URL. Publish it later with update_article and published: true. dev.to refuses a title the account already used in the last 5 minutes, and allows about one write per second.",
|
|
827
|
+
inputSchema: {
|
|
828
|
+
type: "object",
|
|
829
|
+
properties: {
|
|
830
|
+
...ARTICLE_FIELDS,
|
|
831
|
+
organization_id: { type: "integer", minimum: 1, description: "Post under this dev.to organization (the account must be a member)." },
|
|
832
|
+
ai_disclosure_level: { type: "string", enum: [...DISCLOSURE_LEVELS], description: DISCLOSURE_HELP }
|
|
833
|
+
},
|
|
834
|
+
required: ["title", "body_markdown", "ai_disclosure_level"],
|
|
835
|
+
additionalProperties: false
|
|
836
|
+
},
|
|
837
|
+
async run(args, h) {
|
|
838
|
+
assertNoFrontMatter(args.body_markdown);
|
|
839
|
+
const { data } = await saveArticle(h, "POST", "/api/articles", { ...articleBody(args), published: false });
|
|
840
|
+
return trimSaved(data, args);
|
|
841
|
+
}
|
|
842
|
+
},
|
|
843
|
+
{
|
|
844
|
+
name: "update_article",
|
|
845
|
+
kind: "update",
|
|
846
|
+
check: "list_my_articles",
|
|
847
|
+
title: "Publish or update a dev.to article",
|
|
848
|
+
description: "Changes one of the account's dev.to articles: only the fields given are changed. published: true publishes a draft (it goes live and gets its final URL); published: false turns a published article back into a draft. Editing a published article changes it live.",
|
|
849
|
+
inputSchema: {
|
|
850
|
+
type: "object",
|
|
851
|
+
properties: {
|
|
852
|
+
id: { type: "integer", minimum: 1, description: "The article id, from list_my_articles or create_draft_article." },
|
|
853
|
+
published: { type: "boolean", description: "true to publish, false to turn it back into a draft. Leave out to keep it as it is." },
|
|
854
|
+
...ARTICLE_FIELDS,
|
|
855
|
+
ai_disclosure_level: { type: "string", enum: [...DISCLOSURE_LEVELS], description: DISCLOSURE_HELP }
|
|
856
|
+
},
|
|
857
|
+
required: ["id"],
|
|
858
|
+
additionalProperties: false
|
|
859
|
+
},
|
|
860
|
+
async run(args, h) {
|
|
861
|
+
assertNoFrontMatter(args.body_markdown);
|
|
862
|
+
const article = articleBody(args);
|
|
863
|
+
if (args.published !== void 0) article["published"] = args.published;
|
|
864
|
+
if (!Object.keys(article).length) {
|
|
865
|
+
throw new ToolFailure("Nothing to change: give published or at least one article field besides id. Nothing was changed.");
|
|
866
|
+
}
|
|
867
|
+
const { data } = await saveArticle(h, "PUT", `/api/articles/${args.id}`, article);
|
|
868
|
+
return trimSaved(data, args);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
]
|
|
872
|
+
});
|
|
873
|
+
module.exports = connector;
|