@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +1131 -34
- package/dist/cli.js +15 -12
- package/dist/core/credentials.d.ts +21 -0
- package/dist/core/credentials.js +45 -0
- package/dist/core/origins.d.ts +18 -0
- package/dist/core/origins.js +40 -0
- package/dist/core/upload-hosts.d.ts +15 -0
- package/dist/core/upload-hosts.js +43 -0
- package/dist/host/describe.d.ts +10 -0
- package/dist/host/describe.js +38 -0
- package/dist/host/env.d.ts +25 -2
- package/dist/host/env.js +24 -7
- package/dist/host/guarded-fetch.d.ts +36 -9
- package/dist/host/guarded-fetch.js +175 -52
- package/dist/host/index.d.ts +8 -5
- package/dist/host/index.js +12 -1
- package/dist/host/load.js +31 -1
- package/dist/host/server.d.ts +13 -2
- package/dist/host/server.js +15 -2
- package/dist/types.d.ts +96 -5
- package/dist/vendors/adapty.js +1303 -0
- package/dist/vendors/adjust.js +1372 -0
- package/dist/vendors/apollo.js +2499 -0
- package/dist/vendors/apple-appstore.js +2798 -0
- package/dist/vendors/beehiiv.js +1965 -0
- package/dist/vendors/blogger.js +1687 -0
- package/dist/vendors/bluesky.js +850 -127
- package/dist/vendors/brevo.js +2195 -0
- package/dist/vendors/calendarific.js +1116 -0
- package/dist/vendors/devto.js +685 -92
- package/dist/vendors/facebook-pages.js +2185 -0
- package/dist/vendors/firebase.js +1333 -0
- package/dist/vendors/ga4.js +1585 -0
- package/dist/vendors/gmail.js +1962 -0
- package/dist/vendors/google-ads.js +2201 -0
- package/dist/vendors/google-business.js +1621 -0
- package/dist/vendors/google-calendar.js +1936 -0
- package/dist/vendors/google-drive.js +2654 -0
- package/dist/vendors/google-merchant-center.js +1742 -0
- package/dist/vendors/google-play.js +1856 -0
- package/dist/vendors/google-search-console.js +1572 -0
- package/dist/vendors/hashnode.js +1722 -0
- package/dist/vendors/instagram.js +2249 -0
- package/dist/vendors/kaggle.js +2043 -0
- package/dist/vendors/keepa.js +2087 -0
- package/dist/vendors/linkedin.js +1588 -0
- package/dist/vendors/mailchimp.js +2402 -0
- package/dist/vendors/mastodon.js +1836 -0
- package/dist/vendors/meta-ads.js +2375 -0
- package/dist/vendors/notion.js +1950 -0
- package/dist/vendors/pinterest.js +1744 -0
- package/dist/vendors/qiita.js +1552 -0
- package/dist/vendors/reddit.js +1791 -0
- package/dist/vendors/revenuecat.js +1593 -0
- package/dist/vendors/roasit.js +1460 -0
- package/dist/vendors/sendgrid.js +2188 -0
- package/dist/vendors/serper.js +901 -179
- package/dist/vendors/shopify.js +2511 -0
- package/dist/vendors/threads.js +1869 -0
- package/dist/vendors/tiktok.js +2199 -0
- package/dist/vendors/tumblr.js +1793 -0
- package/dist/vendors/twitter.js +1650 -0
- package/dist/vendors/woocommerce.js +2258 -0
- package/dist/vendors/wordpress.js +1904 -0
- package/dist/vendors/youtube.js +2542 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1904 @@
|
|
|
1
|
+
/* wordpress connector module (MIT License). Built from src/vendors/wordpress; do not edit. */
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/core/errors.ts
|
|
5
|
+
var ToolFailure = class extends Error {
|
|
6
|
+
details;
|
|
7
|
+
constructor(message, details = {}) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "ToolFailure";
|
|
10
|
+
this.details = details;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
var OutcomeUnknown = class extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "OutcomeUnknown";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// src/core/accounts.ts
|
|
21
|
+
function allowedAccounts(accounts, key) {
|
|
22
|
+
if (accounts === null) return null;
|
|
23
|
+
const list = accounts?.[key];
|
|
24
|
+
return Array.isArray(list) ? list.map(String) : [];
|
|
25
|
+
}
|
|
26
|
+
function requireAccounts(accounts, key, ids, label = "account") {
|
|
27
|
+
const allowed = allowedAccounts(accounts, key);
|
|
28
|
+
if (allowed === null) return;
|
|
29
|
+
const requested = (Array.isArray(ids) ? ids : [ids]).map(String);
|
|
30
|
+
const refused = requested.filter((id) => !allowed.includes(id));
|
|
31
|
+
if (!refused.length) return;
|
|
32
|
+
throw new ToolFailure(
|
|
33
|
+
`The ${label} ${refused.join(", ")} ${refused.length > 1 ? "are" : "is"} not among the ${label}s chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`) + " Nothing was sent."
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/core/text.ts
|
|
38
|
+
var encoder = new TextEncoder();
|
|
39
|
+
var decoder = new TextDecoder();
|
|
40
|
+
function utf8Bytes(text) {
|
|
41
|
+
return encoder.encode(text);
|
|
42
|
+
}
|
|
43
|
+
function utf8Length(text) {
|
|
44
|
+
return encoder.encode(text).length;
|
|
45
|
+
}
|
|
46
|
+
function utf8Decode(bytes) {
|
|
47
|
+
return decoder.decode(bytes);
|
|
48
|
+
}
|
|
49
|
+
function base64Encode(bytes) {
|
|
50
|
+
let binary = "";
|
|
51
|
+
for (let i = 0; i < bytes.length; i += 32768) {
|
|
52
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
53
|
+
}
|
|
54
|
+
return btoa(binary);
|
|
55
|
+
}
|
|
56
|
+
function base64UrlEncode(bytes) {
|
|
57
|
+
return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
58
|
+
}
|
|
59
|
+
function base64UrlDecode(text) {
|
|
60
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
|
|
61
|
+
const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
|
|
62
|
+
const binary = atob(padded);
|
|
63
|
+
const bytes = new Uint8Array(binary.length);
|
|
64
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
65
|
+
return bytes;
|
|
66
|
+
}
|
|
67
|
+
function truncate(text, max) {
|
|
68
|
+
if (text.length <= max) return text;
|
|
69
|
+
const points = Array.from(text);
|
|
70
|
+
if (points.length <= max) return text;
|
|
71
|
+
return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
|
|
72
|
+
}
|
|
73
|
+
function cleanVendorText(text, max = 300) {
|
|
74
|
+
if (typeof text !== "string") return void 0;
|
|
75
|
+
if (/^\s*</.test(text)) return void 0;
|
|
76
|
+
const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
77
|
+
return line ? truncate(line, max) : void 0;
|
|
78
|
+
}
|
|
79
|
+
function formatNumber(value) {
|
|
80
|
+
return value.toLocaleString("en-US");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/core/output.ts
|
|
84
|
+
var OUTPUT_LIMIT_BYTES = 32 * 1024;
|
|
85
|
+
function jsonSize(value) {
|
|
86
|
+
return utf8Length(JSON.stringify(value) ?? "");
|
|
87
|
+
}
|
|
88
|
+
function cutStrings(value, max) {
|
|
89
|
+
if (typeof value === "string") return truncate(value, max);
|
|
90
|
+
if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
|
|
91
|
+
if (typeof value === "object" && value !== null) {
|
|
92
|
+
const out = {};
|
|
93
|
+
for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
|
|
99
|
+
if (jsonSize(value) <= limit) return { value, truncated: false };
|
|
100
|
+
for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
|
|
101
|
+
const cut = cutStrings(value, max);
|
|
102
|
+
if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
|
|
103
|
+
}
|
|
104
|
+
return void 0;
|
|
105
|
+
}
|
|
106
|
+
function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
|
|
107
|
+
const build = (count) => {
|
|
108
|
+
const cut = count < input.items.length;
|
|
109
|
+
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
|
|
110
|
+
const next = cut ? input.resumeAt(count) : input.nextPage;
|
|
111
|
+
if (next) result2["nextCursor"] = next;
|
|
112
|
+
if (cut) result2["truncated"] = true;
|
|
113
|
+
return result2;
|
|
114
|
+
};
|
|
115
|
+
const all = build(input.items.length);
|
|
116
|
+
if (jsonSize(all) <= limit) return all;
|
|
117
|
+
let low = 1;
|
|
118
|
+
let high = input.items.length - 1;
|
|
119
|
+
while (low < high) {
|
|
120
|
+
const middle = Math.ceil((low + high) / 2);
|
|
121
|
+
if (jsonSize(build(middle)) <= limit) low = middle;
|
|
122
|
+
else high = middle - 1;
|
|
123
|
+
}
|
|
124
|
+
const best = build(low);
|
|
125
|
+
if (jsonSize(best) <= limit) return best;
|
|
126
|
+
const shrunk = shrinkToFit(best, limit);
|
|
127
|
+
if (shrunk) return { ...shrunk.value, truncated: true };
|
|
128
|
+
throw new ToolFailure("The result is too large to return, even one item at a time.");
|
|
129
|
+
}
|
|
130
|
+
function encodeCursor(tool, state) {
|
|
131
|
+
return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
|
|
132
|
+
}
|
|
133
|
+
function decodeCursor(tool, cursor) {
|
|
134
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
135
|
+
try {
|
|
136
|
+
const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
|
|
137
|
+
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
138
|
+
return state;
|
|
139
|
+
}
|
|
140
|
+
} catch {
|
|
141
|
+
}
|
|
142
|
+
throw new ToolFailure(
|
|
143
|
+
"The cursor is not valid for this tool. Pass the nextCursor value of the previous result unchanged, or leave cursor out to start from the beginning."
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/core/api-tools.ts
|
|
148
|
+
var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
|
|
149
|
+
var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
|
|
150
|
+
var NOTE_ROOM = 400;
|
|
151
|
+
var MAX_CUT_POINTS = 4e4;
|
|
152
|
+
function isQueryValue(value) {
|
|
153
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
154
|
+
}
|
|
155
|
+
function nothingSent(sentence) {
|
|
156
|
+
return new ToolFailure(`${sentence} Nothing was sent.`);
|
|
157
|
+
}
|
|
158
|
+
function fitReply(reply) {
|
|
159
|
+
if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
|
|
160
|
+
const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
|
|
161
|
+
if (shrunk) {
|
|
162
|
+
return {
|
|
163
|
+
...shrunk.value,
|
|
164
|
+
truncated: true,
|
|
165
|
+
note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
const text = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
|
|
169
|
+
const points = Array.from(text.length > MAX_CUT_POINTS ? text.slice(0, MAX_CUT_POINTS) : text);
|
|
170
|
+
if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
|
|
171
|
+
const cut = (count) => ({
|
|
172
|
+
status: reply["status"],
|
|
173
|
+
...reply["headers"] ? { headers: reply["headers"] } : {},
|
|
174
|
+
truncated: true,
|
|
175
|
+
note: `The reply has ${formatNumber(utf8Length(text))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
|
|
176
|
+
text: points.slice(0, count).join("")
|
|
177
|
+
});
|
|
178
|
+
let low = 0;
|
|
179
|
+
let high = points.length;
|
|
180
|
+
while (low < high) {
|
|
181
|
+
const middle = Math.ceil((low + high) / 2);
|
|
182
|
+
if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
|
|
183
|
+
else high = middle - 1;
|
|
184
|
+
}
|
|
185
|
+
return cut(low);
|
|
186
|
+
}
|
|
187
|
+
function shapeReply(response, headerNames) {
|
|
188
|
+
const reply = { status: response.status };
|
|
189
|
+
const headers = {};
|
|
190
|
+
for (const name2 of headerNames) {
|
|
191
|
+
const value = response.headers.get(name2);
|
|
192
|
+
if (value) headers[name2] = truncate(value, 2e3);
|
|
193
|
+
}
|
|
194
|
+
if (Object.keys(headers).length) reply["headers"] = headers;
|
|
195
|
+
const type = response.headers.get("content-type") ?? "";
|
|
196
|
+
if (type && !TEXT_TYPES.test(type)) {
|
|
197
|
+
reply["contentType"] = truncate(type, 200);
|
|
198
|
+
reply["note"] = "The reply is a binary file and is not shown.";
|
|
199
|
+
return reply;
|
|
200
|
+
}
|
|
201
|
+
if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
|
|
202
|
+
return fitReply(reply);
|
|
203
|
+
}
|
|
204
|
+
function checkAccounts(rule, request, h) {
|
|
205
|
+
const label = rule.label ?? "account";
|
|
206
|
+
const allowed = allowedAccounts(h.ctx.accounts, rule.key);
|
|
207
|
+
if (allowed === null) return;
|
|
208
|
+
const namesNone = nothingSent(
|
|
209
|
+
`This request names none of the ${label}s chosen for this connection. ` + (allowed.length ? `It must name one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`)
|
|
210
|
+
);
|
|
211
|
+
if (rule.ids) {
|
|
212
|
+
const ids = rule.ids(request).map(String);
|
|
213
|
+
if (!ids.length) throw namesNone;
|
|
214
|
+
requireAccounts(h.ctx.accounts, rule.key, ids, label);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
|
|
218
|
+
}
|
|
219
|
+
function apiTools(options) {
|
|
220
|
+
const { label, basePath } = options;
|
|
221
|
+
const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
|
|
222
|
+
const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
|
|
223
|
+
const base = basePath?.replace(/\/+$/, "");
|
|
224
|
+
const pathSchema = {
|
|
225
|
+
type: "string",
|
|
226
|
+
minLength: 1,
|
|
227
|
+
maxLength: 2e3,
|
|
228
|
+
pattern: "^(?!.*//)/[^?#]*$",
|
|
229
|
+
description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
|
|
230
|
+
};
|
|
231
|
+
const querySchema = {
|
|
232
|
+
type: "object",
|
|
233
|
+
description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
|
|
234
|
+
};
|
|
235
|
+
const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
|
|
236
|
+
async function run(method, args, h) {
|
|
237
|
+
let origin = h.origins[0];
|
|
238
|
+
if (args.origin !== void 0) {
|
|
239
|
+
let wanted;
|
|
240
|
+
try {
|
|
241
|
+
wanted = new URL(args.origin).origin;
|
|
242
|
+
} catch {
|
|
243
|
+
}
|
|
244
|
+
if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
|
|
245
|
+
origin = wanted;
|
|
246
|
+
}
|
|
247
|
+
const url = new URL(args.path, origin);
|
|
248
|
+
if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
|
|
249
|
+
const path = url.pathname;
|
|
250
|
+
if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
|
|
251
|
+
let segments;
|
|
252
|
+
try {
|
|
253
|
+
segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
|
|
254
|
+
} catch {
|
|
255
|
+
throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
|
|
256
|
+
}
|
|
257
|
+
if (segments[segments.length - 1] === "") segments.pop();
|
|
258
|
+
const query = {};
|
|
259
|
+
const queryLists = {};
|
|
260
|
+
for (const [key, value] of Object.entries(args.query ?? {})) {
|
|
261
|
+
if (value === void 0 || value === null) continue;
|
|
262
|
+
const list = Array.isArray(value) ? value : [value];
|
|
263
|
+
if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
|
|
264
|
+
query[key] = Array.isArray(value) ? list : value;
|
|
265
|
+
queryLists[key] = list.map(String);
|
|
266
|
+
}
|
|
267
|
+
const request = { method, origin, path, query };
|
|
268
|
+
if (method !== "GET") {
|
|
269
|
+
if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
|
|
270
|
+
if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
|
|
271
|
+
if (args.json !== void 0 && !args.content_type) {
|
|
272
|
+
request.json = args.json;
|
|
273
|
+
} else if (args.json !== void 0 || args.body !== void 0) {
|
|
274
|
+
request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
|
|
275
|
+
request.contentType = args.content_type;
|
|
276
|
+
}
|
|
277
|
+
request.write = true;
|
|
278
|
+
}
|
|
279
|
+
const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
|
|
280
|
+
if (options.accounts) checkAccounts(options.accounts, info, h);
|
|
281
|
+
await options.guard?.(info, h);
|
|
282
|
+
const response = options.send ? await options.send(request, h) : await h.api(request);
|
|
283
|
+
return shapeReply(response, headerNames);
|
|
284
|
+
}
|
|
285
|
+
return [
|
|
286
|
+
{
|
|
287
|
+
name: "api_get",
|
|
288
|
+
kind: "read",
|
|
289
|
+
title: `Call the ${label} API (GET)`,
|
|
290
|
+
description: `${options.description} Sends one GET request with the connection's credentials and returns the HTTP status and the reply, JSON or text, cut to fit 32 KB (use the API's own paging and field parameters for long lists). It changes nothing.`,
|
|
291
|
+
inputSchema: {
|
|
292
|
+
type: "object",
|
|
293
|
+
properties: { path: pathSchema, query: querySchema, ...originSchema },
|
|
294
|
+
required: ["path"],
|
|
295
|
+
additionalProperties: false
|
|
296
|
+
},
|
|
297
|
+
run: (args, h) => run("GET", args, h)
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
name: "api_request",
|
|
301
|
+
kind: "write",
|
|
302
|
+
check: "api_get",
|
|
303
|
+
title: `Send a request to the ${label} API`,
|
|
304
|
+
description: `${options.description} Sends one ${methods.join(", ")} request with the connection's credentials, with a JSON body (json) or another body (body and content_type), and returns the HTTP status and the reply. It can create, change or delete data. It is never retried: when the outcome is unclear, check with api_get before sending it again.`,
|
|
305
|
+
inputSchema: {
|
|
306
|
+
type: "object",
|
|
307
|
+
properties: {
|
|
308
|
+
method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
|
|
309
|
+
path: pathSchema,
|
|
310
|
+
query: querySchema,
|
|
311
|
+
json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
|
|
312
|
+
body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
|
|
313
|
+
content_type: {
|
|
314
|
+
type: "string",
|
|
315
|
+
pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
|
|
316
|
+
maxLength: 200,
|
|
317
|
+
description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
|
|
318
|
+
},
|
|
319
|
+
...originSchema
|
|
320
|
+
},
|
|
321
|
+
required: ["method", "path"],
|
|
322
|
+
additionalProperties: false
|
|
323
|
+
},
|
|
324
|
+
run: (args, h) => run(args.method, args, h)
|
|
325
|
+
}
|
|
326
|
+
];
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// src/core/credentials.ts
|
|
330
|
+
function requiredAlternatives(module2) {
|
|
331
|
+
return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
|
|
332
|
+
}
|
|
333
|
+
function unmetAlternatives(alternatives, has) {
|
|
334
|
+
const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
|
|
335
|
+
if (lacking.some((list) => list.length === 0)) return [];
|
|
336
|
+
return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
|
|
337
|
+
}
|
|
338
|
+
function andList(items) {
|
|
339
|
+
if (items.length <= 2) return items.join(" and ");
|
|
340
|
+
return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
|
|
341
|
+
}
|
|
342
|
+
function orList(items) {
|
|
343
|
+
if (items.length <= 1) return items.join("");
|
|
344
|
+
return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// src/core/files.ts
|
|
348
|
+
var ATTACHMENT_URI = "attachment:///";
|
|
349
|
+
var MAX_NAME = 200;
|
|
350
|
+
function fileLimitOf(ctx) {
|
|
351
|
+
const maxBytes = ctx.files?.maxBytes;
|
|
352
|
+
return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
|
|
353
|
+
}
|
|
354
|
+
function fileName(name2) {
|
|
355
|
+
const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
|
|
356
|
+
const points = Array.from(clean);
|
|
357
|
+
if (points.length <= MAX_NAME) return clean || "file";
|
|
358
|
+
const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
|
|
359
|
+
return points.slice(0, MAX_NAME - extension.length).join("") + extension;
|
|
360
|
+
}
|
|
361
|
+
function fileType(mimeType) {
|
|
362
|
+
const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
|
|
363
|
+
return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
|
|
364
|
+
}
|
|
365
|
+
function resourceBlock(file) {
|
|
366
|
+
return {
|
|
367
|
+
type: "resource",
|
|
368
|
+
resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// src/core/http.ts
|
|
373
|
+
var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
374
|
+
var USER_AGENT = "agent-connectors";
|
|
375
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
376
|
+
function errorCode(error) {
|
|
377
|
+
const code = error?.code;
|
|
378
|
+
return typeof code === "string" ? code : void 0;
|
|
379
|
+
}
|
|
380
|
+
function describe(error) {
|
|
381
|
+
const name2 = error?.name;
|
|
382
|
+
const code = errorCode(error);
|
|
383
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
384
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
385
|
+
if (code === "TOO_LARGE") return "the reply was too large";
|
|
386
|
+
return cleanVendorText(error?.message, 200) ?? "a network error";
|
|
387
|
+
}
|
|
388
|
+
function retryAfterSeconds(headers, now = Date.now()) {
|
|
389
|
+
const retryAfter = headers.get("retry-after");
|
|
390
|
+
if (retryAfter) {
|
|
391
|
+
const seconds = Number(retryAfter);
|
|
392
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
393
|
+
const date = Date.parse(retryAfter);
|
|
394
|
+
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
|
|
395
|
+
}
|
|
396
|
+
const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
|
|
397
|
+
if (reset) {
|
|
398
|
+
const value = Number(reset);
|
|
399
|
+
if (Number.isFinite(value) && value >= 0) {
|
|
400
|
+
return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return void 0;
|
|
404
|
+
}
|
|
405
|
+
function vendorCode(data) {
|
|
406
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
407
|
+
for (const key of ["error", "code"]) {
|
|
408
|
+
const value = data[key];
|
|
409
|
+
if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
|
|
410
|
+
}
|
|
411
|
+
return void 0;
|
|
412
|
+
}
|
|
413
|
+
function vendorMessage(data) {
|
|
414
|
+
if (typeof data === "string") return cleanVendorText(data);
|
|
415
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
416
|
+
const record = data;
|
|
417
|
+
for (const key of ["message", "error_description", "error", "detail", "title"]) {
|
|
418
|
+
const value = record[key];
|
|
419
|
+
if (typeof value === "string" && value.trim()) return cleanVendorText(value);
|
|
420
|
+
const nested = value?.message;
|
|
421
|
+
if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
|
|
422
|
+
}
|
|
423
|
+
if (Array.isArray(record["errors"])) {
|
|
424
|
+
const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
|
|
425
|
+
if (messages.length) return cleanVendorText(messages.join("; "));
|
|
426
|
+
}
|
|
427
|
+
return void 0;
|
|
428
|
+
}
|
|
429
|
+
var TooLarge = class extends Error {
|
|
430
|
+
constructor(limit) {
|
|
431
|
+
super(`the reply is larger than ${formatNumber(limit)} bytes`);
|
|
432
|
+
this.limit = limit;
|
|
433
|
+
}
|
|
434
|
+
limit;
|
|
435
|
+
};
|
|
436
|
+
async function readCapped(response, maxBytes) {
|
|
437
|
+
const declared = Number(response.headers.get("content-length"));
|
|
438
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
439
|
+
await response.body?.cancel().catch(() => {
|
|
440
|
+
});
|
|
441
|
+
throw new TooLarge(maxBytes);
|
|
442
|
+
}
|
|
443
|
+
if (!response.body) return new Uint8Array(0);
|
|
444
|
+
const reader = response.body.getReader();
|
|
445
|
+
const chunks = [];
|
|
446
|
+
let total = 0;
|
|
447
|
+
for (; ; ) {
|
|
448
|
+
const { done, value } = await reader.read();
|
|
449
|
+
if (done) break;
|
|
450
|
+
total += value.byteLength;
|
|
451
|
+
if (total > maxBytes) {
|
|
452
|
+
await reader.cancel().catch(() => {
|
|
453
|
+
});
|
|
454
|
+
throw new TooLarge(maxBytes);
|
|
455
|
+
}
|
|
456
|
+
chunks.push(value);
|
|
457
|
+
}
|
|
458
|
+
const bytes = new Uint8Array(total);
|
|
459
|
+
let offset = 0;
|
|
460
|
+
for (const chunk of chunks) {
|
|
461
|
+
bytes.set(chunk, offset);
|
|
462
|
+
offset += chunk.byteLength;
|
|
463
|
+
}
|
|
464
|
+
return bytes;
|
|
465
|
+
}
|
|
466
|
+
function parseBody(bytes, contentType) {
|
|
467
|
+
if (bytes.length === 0) return null;
|
|
468
|
+
const text = utf8Decode(bytes);
|
|
469
|
+
if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
|
|
470
|
+
try {
|
|
471
|
+
return JSON.parse(text);
|
|
472
|
+
} catch {
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return text;
|
|
476
|
+
}
|
|
477
|
+
function createHttp(env) {
|
|
478
|
+
const { label, ctx } = env;
|
|
479
|
+
const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
|
|
480
|
+
const checkCredentials = env.credentialLabels.length ? `Check that the ${andList(env.credentialLabels)} ${env.credentialLabels.length > 1 ? "are" : "is"} correct and still active.` : `Check that the ${label} credentials are correct and still active.`;
|
|
481
|
+
function failureFor(status, headers, data, request) {
|
|
482
|
+
const message = vendorMessage(data);
|
|
483
|
+
const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
|
|
484
|
+
const retryAfter = retryAfterSeconds(headers);
|
|
485
|
+
const code = vendorCode(data);
|
|
486
|
+
const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
|
|
487
|
+
const custom = request.errors?.[status];
|
|
488
|
+
const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
|
|
489
|
+
if (status >= 500) {
|
|
490
|
+
if (request.write) {
|
|
491
|
+
return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
|
|
492
|
+
}
|
|
493
|
+
return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
|
|
494
|
+
}
|
|
495
|
+
if (status === 429) {
|
|
496
|
+
return new ToolFailure(
|
|
497
|
+
`${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
|
|
498
|
+
{ status, ...extra }
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
if (status === 401) {
|
|
502
|
+
return new ToolFailure(
|
|
503
|
+
withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
|
|
504
|
+
{ status, ...extra }
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
|
|
508
|
+
if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
|
|
509
|
+
if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
|
|
510
|
+
return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
|
|
511
|
+
}
|
|
512
|
+
async function api(request) {
|
|
513
|
+
const method = request.method ?? "GET";
|
|
514
|
+
if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
|
|
515
|
+
throw new Error(`read-only tool sent ${method}`);
|
|
516
|
+
}
|
|
517
|
+
const origin = request.origin ?? env.origins[0];
|
|
518
|
+
if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
|
|
519
|
+
const url = new URL(request.path, origin);
|
|
520
|
+
if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
|
|
521
|
+
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
522
|
+
if (value === void 0 || value === null) continue;
|
|
523
|
+
if (Array.isArray(value)) {
|
|
524
|
+
url.searchParams.delete(key);
|
|
525
|
+
for (const item of value) url.searchParams.append(key, String(item));
|
|
526
|
+
} else {
|
|
527
|
+
url.searchParams.set(key, String(value));
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
const headers = {
|
|
531
|
+
accept: "application/json",
|
|
532
|
+
"user-agent": USER_AGENT,
|
|
533
|
+
...request.auth === false ? {} : env.authHeaders(),
|
|
534
|
+
...request.headers
|
|
535
|
+
};
|
|
536
|
+
let body;
|
|
537
|
+
if (request.json !== void 0) {
|
|
538
|
+
body = JSON.stringify(request.json);
|
|
539
|
+
headers["content-type"] = "application/json";
|
|
540
|
+
} else if (request.body) {
|
|
541
|
+
body = request.body;
|
|
542
|
+
headers["content-type"] = request.contentType ?? "application/octet-stream";
|
|
543
|
+
}
|
|
544
|
+
const started = Date.now();
|
|
545
|
+
if (request.write) env.onWriteSent();
|
|
546
|
+
let response;
|
|
547
|
+
try {
|
|
548
|
+
response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
|
|
549
|
+
} catch (error) {
|
|
550
|
+
env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
|
|
551
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
552
|
+
throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
|
|
553
|
+
}
|
|
554
|
+
if (request.write) {
|
|
555
|
+
throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
|
|
556
|
+
}
|
|
557
|
+
if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
|
|
558
|
+
throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
|
|
559
|
+
}
|
|
560
|
+
env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
|
|
561
|
+
let bytes;
|
|
562
|
+
try {
|
|
563
|
+
bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
|
|
564
|
+
} catch (error) {
|
|
565
|
+
if (request.write && (response.ok || response.status >= 500)) {
|
|
566
|
+
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.`);
|
|
567
|
+
}
|
|
568
|
+
throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
|
|
569
|
+
}
|
|
570
|
+
const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
|
|
571
|
+
if (response.ok) return { status: response.status, headers: response.headers, data };
|
|
572
|
+
throw failureFor(response.status, response.headers, data, request);
|
|
573
|
+
}
|
|
574
|
+
async function media(rawUrl, options) {
|
|
575
|
+
const { what } = options;
|
|
576
|
+
let url;
|
|
577
|
+
try {
|
|
578
|
+
url = new URL(rawUrl);
|
|
579
|
+
} catch {
|
|
580
|
+
throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
|
|
581
|
+
}
|
|
582
|
+
if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
|
|
583
|
+
const started = Date.now();
|
|
584
|
+
let response;
|
|
585
|
+
try {
|
|
586
|
+
response = await ctx.fetch(url.toString(), {
|
|
587
|
+
method: "GET",
|
|
588
|
+
headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
|
|
589
|
+
...ctx.signal ? { signal: ctx.signal } : {}
|
|
590
|
+
});
|
|
591
|
+
} catch (error) {
|
|
592
|
+
env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
|
|
593
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
594
|
+
throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
|
|
595
|
+
}
|
|
596
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
597
|
+
}
|
|
598
|
+
env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
|
|
599
|
+
if (!response.ok) {
|
|
600
|
+
await response.body?.cancel().catch(() => {
|
|
601
|
+
});
|
|
602
|
+
throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
|
|
603
|
+
}
|
|
604
|
+
try {
|
|
605
|
+
const bytes = await readCapped(response, options.maxBytes);
|
|
606
|
+
return { bytes, contentType: response.headers.get("content-type") };
|
|
607
|
+
} catch (error) {
|
|
608
|
+
if (error instanceof TooLarge) {
|
|
609
|
+
throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
|
|
610
|
+
}
|
|
611
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
return { api, media };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/core/origins.ts
|
|
618
|
+
function parseSiteUrl(value) {
|
|
619
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
620
|
+
if (!text) return { ok: false, problem: "is empty" };
|
|
621
|
+
let url;
|
|
622
|
+
try {
|
|
623
|
+
url = new URL(text.includes("://") ? text : `https://${text}`);
|
|
624
|
+
} catch {
|
|
625
|
+
return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
|
|
626
|
+
}
|
|
627
|
+
if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
|
|
628
|
+
if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
|
|
629
|
+
if (!url.hostname) return { ok: false, problem: "has no host name" };
|
|
630
|
+
return { ok: true, url, origin: url.origin };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// src/core/schema.ts
|
|
634
|
+
var patterns = /* @__PURE__ */ new Map();
|
|
635
|
+
function patternOf(source) {
|
|
636
|
+
let compiled = patterns.get(source);
|
|
637
|
+
if (!compiled) {
|
|
638
|
+
compiled = new RegExp(source, "u");
|
|
639
|
+
patterns.set(source, compiled);
|
|
640
|
+
}
|
|
641
|
+
return compiled;
|
|
642
|
+
}
|
|
643
|
+
function isPlainObject(value) {
|
|
644
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
645
|
+
}
|
|
646
|
+
function isHttpUrl(value) {
|
|
647
|
+
try {
|
|
648
|
+
const url = new URL(value);
|
|
649
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
650
|
+
} catch {
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
function name(path) {
|
|
655
|
+
return `\`${path}\``;
|
|
656
|
+
}
|
|
657
|
+
function child(path, key) {
|
|
658
|
+
return path ? `${path}.${key}` : key;
|
|
659
|
+
}
|
|
660
|
+
function checkValue(schema, value, path, issues) {
|
|
661
|
+
switch (schema.type) {
|
|
662
|
+
case "object":
|
|
663
|
+
checkObject(schema, value, path, issues);
|
|
664
|
+
return;
|
|
665
|
+
case "array": {
|
|
666
|
+
if (!Array.isArray(value)) {
|
|
667
|
+
issues.push(`${name(path)} must be an array`);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
671
|
+
issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
|
|
672
|
+
}
|
|
673
|
+
if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
|
|
674
|
+
issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
|
|
675
|
+
}
|
|
676
|
+
if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
|
|
677
|
+
issues.push(`${name(path)} must not repeat an item`);
|
|
678
|
+
}
|
|
679
|
+
if (schema.items) {
|
|
680
|
+
value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
|
|
681
|
+
}
|
|
682
|
+
break;
|
|
683
|
+
}
|
|
684
|
+
case "string": {
|
|
685
|
+
if (typeof value !== "string") {
|
|
686
|
+
issues.push(`${name(path)} must be a string`);
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
const length = Array.from(value).length;
|
|
690
|
+
if (schema.minLength !== void 0 && length < schema.minLength) {
|
|
691
|
+
issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
|
|
692
|
+
}
|
|
693
|
+
if (schema.maxLength !== void 0 && length > schema.maxLength) {
|
|
694
|
+
issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
|
|
695
|
+
}
|
|
696
|
+
if (schema.format === "uri" && !isHttpUrl(value)) {
|
|
697
|
+
issues.push(`${name(path)} must be an absolute http(s) URL`);
|
|
698
|
+
} else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
|
|
699
|
+
issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
|
|
700
|
+
}
|
|
701
|
+
break;
|
|
702
|
+
}
|
|
703
|
+
case "integer":
|
|
704
|
+
case "number": {
|
|
705
|
+
if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
|
|
706
|
+
issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
710
|
+
issues.push(`${name(path)} must be at least ${schema.minimum}`);
|
|
711
|
+
}
|
|
712
|
+
if (schema.maximum !== void 0 && value > schema.maximum) {
|
|
713
|
+
issues.push(`${name(path)} must be at most ${schema.maximum}`);
|
|
714
|
+
}
|
|
715
|
+
break;
|
|
716
|
+
}
|
|
717
|
+
case "boolean":
|
|
718
|
+
if (typeof value !== "boolean") {
|
|
719
|
+
issues.push(`${name(path)} must be true or false`);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
break;
|
|
723
|
+
default:
|
|
724
|
+
break;
|
|
725
|
+
}
|
|
726
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
727
|
+
issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
function checkObject(schema, value, path, issues) {
|
|
731
|
+
if (!isPlainObject(value)) {
|
|
732
|
+
issues.push(`${path ? name(path) : "the arguments"} must be an object`);
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
const properties = schema.properties ?? {};
|
|
736
|
+
for (const key of schema.required ?? []) {
|
|
737
|
+
if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
|
|
738
|
+
}
|
|
739
|
+
const unknown = [];
|
|
740
|
+
for (const [key, item] of Object.entries(value)) {
|
|
741
|
+
const property = properties[key];
|
|
742
|
+
if (!property) {
|
|
743
|
+
if (schema.additionalProperties === false) unknown.push(key);
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
if (item === void 0 || item === null) continue;
|
|
747
|
+
checkValue(property, item, child(path, key), issues);
|
|
748
|
+
}
|
|
749
|
+
if (unknown.length) {
|
|
750
|
+
const known = Object.keys(properties);
|
|
751
|
+
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(", ")})` : ""));
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
function copyDefault(value) {
|
|
755
|
+
return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
|
|
756
|
+
}
|
|
757
|
+
function validateArguments(schema, args) {
|
|
758
|
+
const input = args === void 0 || args === null ? {} : args;
|
|
759
|
+
if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
|
|
760
|
+
const value = { ...input };
|
|
761
|
+
if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
|
|
762
|
+
const issues = [];
|
|
763
|
+
checkObject(schema, value, "", issues);
|
|
764
|
+
if (issues.length) return { ok: false, issues };
|
|
765
|
+
for (const [key, property] of Object.entries(schema.properties ?? {})) {
|
|
766
|
+
if (value[key] === null) delete value[key];
|
|
767
|
+
if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
|
|
768
|
+
}
|
|
769
|
+
return { ok: true, value };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/core/upload-hosts.ts
|
|
773
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
774
|
+
function uploadHostProblem(entry) {
|
|
775
|
+
if (typeof entry !== "string") return "must be a host name";
|
|
776
|
+
const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
|
|
777
|
+
const labels = name2.split(".");
|
|
778
|
+
if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
|
|
779
|
+
return "must be a lowercase host name like uploads.example.com, or one with a leading dot like .example.com for every host under it";
|
|
780
|
+
}
|
|
781
|
+
if (labels.length < 2) return "needs at least two labels, like example.com";
|
|
782
|
+
if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
|
|
783
|
+
return void 0;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// src/core/connector.ts
|
|
787
|
+
var ANNOTATIONS = {
|
|
788
|
+
read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
789
|
+
create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
790
|
+
update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
791
|
+
delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
792
|
+
write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
|
|
793
|
+
};
|
|
794
|
+
var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
|
|
795
|
+
var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
796
|
+
var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
797
|
+
var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
798
|
+
var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
|
|
799
|
+
var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
800
|
+
var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
|
|
801
|
+
function deepFreeze(value) {
|
|
802
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
803
|
+
Object.freeze(value);
|
|
804
|
+
for (const item of Object.values(value)) deepFreeze(item);
|
|
805
|
+
}
|
|
806
|
+
return value;
|
|
807
|
+
}
|
|
808
|
+
function assertDefinition(def) {
|
|
809
|
+
const problem = (message) => {
|
|
810
|
+
throw new Error(`connector "${def.vendor}": ${message}`);
|
|
811
|
+
};
|
|
812
|
+
if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
|
|
813
|
+
if (!def.label?.trim()) problem("label is required");
|
|
814
|
+
const originFields = def.originFields ?? [];
|
|
815
|
+
if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
|
|
816
|
+
for (const origin of def.origins) {
|
|
817
|
+
let url;
|
|
818
|
+
try {
|
|
819
|
+
url = new URL(origin);
|
|
820
|
+
} catch {
|
|
821
|
+
}
|
|
822
|
+
if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
|
|
823
|
+
}
|
|
824
|
+
for (const name2 of def.credentials) {
|
|
825
|
+
if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
|
|
826
|
+
}
|
|
827
|
+
for (const [index, name2] of originFields.entries()) {
|
|
828
|
+
if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
|
|
829
|
+
if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
|
|
830
|
+
}
|
|
831
|
+
const names = /* @__PURE__ */ new Set();
|
|
832
|
+
for (const tool of def.tools) {
|
|
833
|
+
if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
834
|
+
if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
|
|
835
|
+
names.add(tool.name);
|
|
836
|
+
if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
|
|
837
|
+
if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
|
|
838
|
+
if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
|
|
839
|
+
if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
|
|
840
|
+
problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
for (const tool of def.tools) {
|
|
844
|
+
if (tool.kind === "read") continue;
|
|
845
|
+
const check = def.tools.find((candidate) => candidate.name === tool.check);
|
|
846
|
+
if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
|
|
847
|
+
}
|
|
848
|
+
assertUploadHosts(def, problem);
|
|
849
|
+
assertRequiredCredentials(def, problem);
|
|
850
|
+
assertAccountPickers(def, problem);
|
|
851
|
+
}
|
|
852
|
+
function assertUploadHosts(def, problem) {
|
|
853
|
+
const hosts = def.uploadHosts;
|
|
854
|
+
if (hosts === void 0) return;
|
|
855
|
+
if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
|
|
856
|
+
hosts.forEach((entry, index) => {
|
|
857
|
+
const wrong = uploadHostProblem(entry);
|
|
858
|
+
if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
|
|
859
|
+
if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
function assertRequiredCredentials(def, problem) {
|
|
863
|
+
const required = def.requiredCredentials;
|
|
864
|
+
if (required === void 0) return;
|
|
865
|
+
if (!Array.isArray(required) || !required.length) {
|
|
866
|
+
problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
|
|
867
|
+
}
|
|
868
|
+
required.forEach((list, index) => {
|
|
869
|
+
const which = `requiredCredentials[${index}]`;
|
|
870
|
+
if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
|
|
871
|
+
list.forEach((name2, position) => {
|
|
872
|
+
if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
|
|
873
|
+
if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
|
|
874
|
+
});
|
|
875
|
+
});
|
|
876
|
+
const lists = required;
|
|
877
|
+
lists.forEach((list, index) => {
|
|
878
|
+
const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
|
|
879
|
+
if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
|
|
880
|
+
if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
|
|
881
|
+
problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
|
|
882
|
+
}
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
function isDotPath(value) {
|
|
886
|
+
return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
|
|
887
|
+
}
|
|
888
|
+
function assertAccountPickers(def, problem) {
|
|
889
|
+
const pickers = def.accountPickers;
|
|
890
|
+
if (pickers === void 0) return;
|
|
891
|
+
if (!Array.isArray(pickers)) problem("accountPickers must be a list");
|
|
892
|
+
const keys = /* @__PURE__ */ new Set();
|
|
893
|
+
for (const item of pickers) {
|
|
894
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
|
|
895
|
+
const picker = item;
|
|
896
|
+
const key = picker["key"];
|
|
897
|
+
if (typeof key !== "string" || !PICKER_KEY_PATTERN.test(key)) problem(`account picker ${JSON.stringify(key)}: key must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
898
|
+
if (keys.has(key)) problem(`account picker ${key} is defined twice`);
|
|
899
|
+
keys.add(key);
|
|
900
|
+
const fail = (message) => problem(`account picker ${key}: ${message}`);
|
|
901
|
+
const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
|
|
902
|
+
if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
|
|
903
|
+
const { label, description, multiple, legacyField } = picker;
|
|
904
|
+
if (typeof label !== "string" || !label.trim()) fail("label is required");
|
|
905
|
+
if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
|
|
906
|
+
fail("description, when given, must be a text of 1 to 1024 characters");
|
|
907
|
+
}
|
|
908
|
+
if (typeof multiple !== "boolean") fail("multiple must be true or false");
|
|
909
|
+
const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
|
|
910
|
+
if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
|
|
911
|
+
if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
|
|
912
|
+
for (const field of ["idField", "nameField"]) {
|
|
913
|
+
if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
|
|
914
|
+
}
|
|
915
|
+
if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
|
|
916
|
+
fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
function copyPicker(picker) {
|
|
921
|
+
return {
|
|
922
|
+
key: picker.key,
|
|
923
|
+
label: picker.label,
|
|
924
|
+
...picker.description !== void 0 ? { description: picker.description } : {},
|
|
925
|
+
multiple: picker.multiple,
|
|
926
|
+
tool: picker.tool,
|
|
927
|
+
idField: picker.idField,
|
|
928
|
+
nameField: picker.nameField,
|
|
929
|
+
...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
function result(payload, isError, files = []) {
|
|
933
|
+
return {
|
|
934
|
+
content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
|
|
935
|
+
...isError ? { isError: true } : {}
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
function failure(message, details = {}) {
|
|
939
|
+
return result({ error: message, ...details }, true);
|
|
940
|
+
}
|
|
941
|
+
function trimmed(values) {
|
|
942
|
+
const out = {};
|
|
943
|
+
if (typeof values !== "object" || values === null) return out;
|
|
944
|
+
for (const [key, value] of Object.entries(values)) {
|
|
945
|
+
if (value === void 0 || value === null) continue;
|
|
946
|
+
const text = String(value).trim();
|
|
947
|
+
if (text) out[key] = text;
|
|
948
|
+
}
|
|
949
|
+
return out;
|
|
950
|
+
}
|
|
951
|
+
function defineConnector(def) {
|
|
952
|
+
assertDefinition(def);
|
|
953
|
+
const { label } = def;
|
|
954
|
+
const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
|
|
955
|
+
const toolList = def.tools.map((tool) => tool.name).join(", ");
|
|
956
|
+
const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
|
|
957
|
+
const required = requiredAlternatives(def);
|
|
958
|
+
const notConnected = (unmet) => {
|
|
959
|
+
const [first] = unmet;
|
|
960
|
+
if (unmet.length === 1 && first) {
|
|
961
|
+
return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
|
|
962
|
+
}
|
|
963
|
+
return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
|
|
964
|
+
};
|
|
965
|
+
const descriptors = def.tools.map((tool) => ({
|
|
966
|
+
name: tool.name,
|
|
967
|
+
title: tool.title,
|
|
968
|
+
description: tool.description,
|
|
969
|
+
inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
|
|
970
|
+
annotations: { ...ANNOTATIONS[tool.kind] }
|
|
971
|
+
}));
|
|
972
|
+
async function call(toolName, args, ctx) {
|
|
973
|
+
const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
|
|
974
|
+
if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
|
|
975
|
+
if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
|
|
976
|
+
const log = (text) => {
|
|
977
|
+
try {
|
|
978
|
+
ctx.log?.(text);
|
|
979
|
+
} catch {
|
|
980
|
+
}
|
|
981
|
+
};
|
|
982
|
+
const given = trimmed(ctx.credentials);
|
|
983
|
+
const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
|
|
984
|
+
const has = (name2) => Boolean(credentials[name2]);
|
|
985
|
+
const unmet = unmetAlternatives(required, has);
|
|
986
|
+
if (unmet.length) return failure(notConnected(unmet));
|
|
987
|
+
const complete = required.filter((list) => list.every(has));
|
|
988
|
+
const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
|
|
989
|
+
const fieldOrigins = /* @__PURE__ */ new Map();
|
|
990
|
+
for (const name2 of def.originFields ?? []) {
|
|
991
|
+
if (!given[name2] && !inUse.includes(name2)) continue;
|
|
992
|
+
const site = parseSiteUrl(given[name2] ?? "");
|
|
993
|
+
if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
|
|
994
|
+
fieldOrigins.set(name2, site.origin);
|
|
995
|
+
}
|
|
996
|
+
const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
|
|
997
|
+
const parsed = validateArguments(tool.inputSchema, args);
|
|
998
|
+
if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
|
|
999
|
+
const frozenCredentials = Object.freeze({ ...credentials });
|
|
1000
|
+
let writeSent = false;
|
|
1001
|
+
const fileLimit = fileLimitOf(ctx);
|
|
1002
|
+
const files = [];
|
|
1003
|
+
let fileBytes = 0;
|
|
1004
|
+
const http = createHttp({
|
|
1005
|
+
vendor: def.vendor,
|
|
1006
|
+
label,
|
|
1007
|
+
tool: tool.name,
|
|
1008
|
+
readOnly: tool.kind === "read",
|
|
1009
|
+
origins,
|
|
1010
|
+
// A 401 names the credentials in use (for a module that needs none, the ones given).
|
|
1011
|
+
credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
|
|
1012
|
+
ctx,
|
|
1013
|
+
authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
|
|
1014
|
+
log,
|
|
1015
|
+
onWriteSent: () => {
|
|
1016
|
+
writeSent = true;
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
const helpers = {
|
|
1020
|
+
tool: tool.name,
|
|
1021
|
+
credentials: frozenCredentials,
|
|
1022
|
+
ctx,
|
|
1023
|
+
origins: Object.freeze([...origins]),
|
|
1024
|
+
originOf: (credential) => {
|
|
1025
|
+
const origin = fieldOrigins.get(credential);
|
|
1026
|
+
if (!origin) throw new Error(`${credential} gives no origin in this call`);
|
|
1027
|
+
return origin;
|
|
1028
|
+
},
|
|
1029
|
+
api: http.api,
|
|
1030
|
+
media: http.media,
|
|
1031
|
+
page: (input) => fitPage(input),
|
|
1032
|
+
cursor: (cursor) => decodeCursor(tool.name, cursor),
|
|
1033
|
+
makeCursor: (state) => encodeCursor(tool.name, state),
|
|
1034
|
+
fileLimit: () => fileLimit,
|
|
1035
|
+
file: ({ name: name2, mimeType, bytes }) => {
|
|
1036
|
+
if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
|
|
1037
|
+
const total = fileBytes + bytes.byteLength;
|
|
1038
|
+
if (total > fileLimit) {
|
|
1039
|
+
throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total)} bytes in all, more than the ${formatNumber(fileLimit)} bytes this host takes from one call.` : `The file has ${formatNumber(bytes.byteLength)} bytes, more than the ${formatNumber(fileLimit)} bytes this host takes.`);
|
|
1040
|
+
}
|
|
1041
|
+
fileBytes = total;
|
|
1042
|
+
const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
|
|
1043
|
+
files.push({ ...info, bytes });
|
|
1044
|
+
return { ...info };
|
|
1045
|
+
},
|
|
1046
|
+
log
|
|
1047
|
+
};
|
|
1048
|
+
try {
|
|
1049
|
+
const data = await tool.run(parsed.value, helpers);
|
|
1050
|
+
const fitted = shrinkToFit(data ?? {});
|
|
1051
|
+
if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
|
|
1052
|
+
const payload = fitted.value;
|
|
1053
|
+
return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
|
|
1054
|
+
} catch (error) {
|
|
1055
|
+
if (error instanceof OutcomeUnknown) {
|
|
1056
|
+
return result({
|
|
1057
|
+
outcome: "unknown",
|
|
1058
|
+
check: tool.check,
|
|
1059
|
+
error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
|
|
1060
|
+
}, true);
|
|
1061
|
+
}
|
|
1062
|
+
if (error instanceof ToolFailure) return failure(error.message, error.details);
|
|
1063
|
+
log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
|
|
1064
|
+
if (writeSent) {
|
|
1065
|
+
return result({
|
|
1066
|
+
outcome: "unknown",
|
|
1067
|
+
check: tool.check,
|
|
1068
|
+
error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
|
|
1069
|
+
}, true);
|
|
1070
|
+
}
|
|
1071
|
+
return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
return deepFreeze({
|
|
1075
|
+
vendor: def.vendor,
|
|
1076
|
+
origins: [...def.origins],
|
|
1077
|
+
originFields: [...def.originFields ?? []],
|
|
1078
|
+
uploadHosts: [...def.uploadHosts ?? []],
|
|
1079
|
+
credentials: [...def.credentials],
|
|
1080
|
+
requiredCredentials: required.map((list) => [...list]),
|
|
1081
|
+
accountPickers: (def.accountPickers ?? []).map(copyPicker),
|
|
1082
|
+
tools: descriptors,
|
|
1083
|
+
call
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
// src/core/jwt.ts
|
|
1088
|
+
var TOKEN_EARLY_MS = 5 * 60 * 1e3;
|
|
1089
|
+
|
|
1090
|
+
// src/vendors/wordpress/media.ts
|
|
1091
|
+
var MEDIA_TYPES_TEXT = "JPEG, PNG, GIF, WebP, AVIF or HEIC images, MP4, MOV, WebM or MKV video, MP3, WAV or OGG audio, and PDF";
|
|
1092
|
+
function ascii(bytes, start, length) {
|
|
1093
|
+
return String.fromCharCode(...bytes.subarray(start, start + length));
|
|
1094
|
+
}
|
|
1095
|
+
var MP4_BRANDS = /* @__PURE__ */ new Set(["isom", "iso2", "iso4", "iso5", "iso6", "mp41", "mp42", "avc1", "dash", "M4V ", "M4VP", "MSNV", "mmp4"]);
|
|
1096
|
+
function sniffFile(bytes) {
|
|
1097
|
+
if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return { mime: "image/jpeg", ext: "jpg" };
|
|
1098
|
+
if (bytes.length >= 8 && [137, 80, 78, 71, 13, 10, 26, 10].every((value, index) => bytes[index] === value)) {
|
|
1099
|
+
return { mime: "image/png", ext: "png" };
|
|
1100
|
+
}
|
|
1101
|
+
if (bytes.length >= 6 && /^GIF8[79]a$/.test(ascii(bytes, 0, 6))) return { mime: "image/gif", ext: "gif" };
|
|
1102
|
+
if (bytes.length >= 12 && ascii(bytes, 0, 4) === "RIFF") {
|
|
1103
|
+
const kind = ascii(bytes, 8, 4);
|
|
1104
|
+
if (kind === "WEBP") return { mime: "image/webp", ext: "webp" };
|
|
1105
|
+
if (kind === "WAVE") return { mime: "audio/wav", ext: "wav" };
|
|
1106
|
+
}
|
|
1107
|
+
if (bytes.length >= 5 && ascii(bytes, 0, 5) === "%PDF-") return { mime: "application/pdf", ext: "pdf" };
|
|
1108
|
+
if (bytes.length >= 12 && ascii(bytes, 4, 4) === "ftyp") {
|
|
1109
|
+
const brand = ascii(bytes, 8, 4);
|
|
1110
|
+
if (brand === "avif" || brand === "avis") return { mime: "image/avif", ext: "avif" };
|
|
1111
|
+
if (brand === "heic" || brand === "heix") return { mime: "image/heic", ext: "heic" };
|
|
1112
|
+
if (brand === "qt ") return { mime: "video/quicktime", ext: "mov" };
|
|
1113
|
+
if (MP4_BRANDS.has(brand)) return { mime: "video/mp4", ext: "mp4" };
|
|
1114
|
+
}
|
|
1115
|
+
if (bytes.length >= 4 && bytes[0] === 26 && bytes[1] === 69 && bytes[2] === 223 && bytes[3] === 163) {
|
|
1116
|
+
return ascii(bytes, 0, Math.min(bytes.length, 64)).includes("webm") ? { mime: "video/webm", ext: "webm" } : { mime: "video/x-matroska", ext: "mkv" };
|
|
1117
|
+
}
|
|
1118
|
+
if (bytes.length >= 3 && ascii(bytes, 0, 3) === "ID3") return { mime: "audio/mpeg", ext: "mp3" };
|
|
1119
|
+
if (bytes.length >= 2 && bytes[0] === 255 && (bytes[1] & 224) === 224 && (bytes[1] & 6) !== 0) {
|
|
1120
|
+
return { mime: "audio/mpeg", ext: "mp3" };
|
|
1121
|
+
}
|
|
1122
|
+
if (bytes.length >= 4 && ascii(bytes, 0, 4) === "OggS") return { mime: "audio/ogg", ext: "ogg" };
|
|
1123
|
+
return void 0;
|
|
1124
|
+
}
|
|
1125
|
+
function uploadName(given, url, ext) {
|
|
1126
|
+
let base = given ?? "";
|
|
1127
|
+
if (!base) {
|
|
1128
|
+
try {
|
|
1129
|
+
base = decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
|
|
1130
|
+
} catch {
|
|
1131
|
+
base = "";
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
base = base.replace(/\.[A-Za-z0-9]{1,5}$/, "").normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^A-Za-z0-9._-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[-._]+|[-._]+$/g, "").slice(0, 80);
|
|
1135
|
+
return `${base || "upload"}.${ext}`;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// src/vendors/wordpress/site.ts
|
|
1139
|
+
function basicAuth(user, password) {
|
|
1140
|
+
let binary = "";
|
|
1141
|
+
for (const byte of utf8Bytes(`${user}:${password}`)) binary += String.fromCharCode(byte);
|
|
1142
|
+
return `Basic ${btoa(binary)}`;
|
|
1143
|
+
}
|
|
1144
|
+
function installPath(value) {
|
|
1145
|
+
const site = parseSiteUrl(value ?? "");
|
|
1146
|
+
if (!site.ok) return "";
|
|
1147
|
+
return site.url.pathname.replace(/\/(?:wp-admin|wp-json|wp-login\.php)(?:\/.*)?$/i, "").replace(/\/+$/, "");
|
|
1148
|
+
}
|
|
1149
|
+
function siteAddress(h) {
|
|
1150
|
+
return `${h.originOf("url")}${installPath(h.credentials["url"])}`;
|
|
1151
|
+
}
|
|
1152
|
+
function editLink(h, id) {
|
|
1153
|
+
return typeof id === "number" ? `${siteAddress(h)}/wp-admin/post.php?post=${id}&action=edit` : void 0;
|
|
1154
|
+
}
|
|
1155
|
+
var NOT_FOUND = "Check that the WordPress URL is the site's address (with its subdirectory when WordPress is installed in one) and that its REST API answers at <address>/wp-json/ (permalinks other than Plain).";
|
|
1156
|
+
var HINTS = {
|
|
1157
|
+
rest_not_logged_in: "WordPress did not see the sign-in: the site's server may drop the Authorization header (some hosting setups do), or a security plugin may block application passwords.",
|
|
1158
|
+
incorrect_password: "Check the application password (WordPress \u2192 Users \u2192 Profile \u2192 Application Passwords): it is not the account password.",
|
|
1159
|
+
invalid_username: "Check the WordPress user name: it is the login name, not the display name or email address.",
|
|
1160
|
+
invalid_email: "Check the WordPress user name: it is the login name, not the display name or email address.",
|
|
1161
|
+
application_passwords_disabled: "Application passwords are turned off on this site (by a plugin or the site's settings, or because it is not served over https).",
|
|
1162
|
+
rest_cannot_create: "The WordPress user may not do this: it needs the Author, Editor or Administrator role.",
|
|
1163
|
+
rest_cannot_edit: "The WordPress user may not edit this item: an Author can edit only their own posts, an Editor any post.",
|
|
1164
|
+
rest_cannot_publish: "The WordPress user may not publish: save a draft instead, or give the user the Author, Editor or Administrator role.",
|
|
1165
|
+
rest_no_route: NOT_FOUND
|
|
1166
|
+
};
|
|
1167
|
+
function withHint(error) {
|
|
1168
|
+
if (!(error instanceof ToolFailure)) return error;
|
|
1169
|
+
const { vendorCode: vendorCode2, status } = error.details;
|
|
1170
|
+
const hint = (vendorCode2 !== void 0 ? HINTS[vendorCode2] : void 0) ?? (status === 404 && vendorCode2 === void 0 ? NOT_FOUND : void 0);
|
|
1171
|
+
return hint ? new ToolFailure(`${error.message} ${hint}`, error.details) : error;
|
|
1172
|
+
}
|
|
1173
|
+
async function rest(h, route, request = {}) {
|
|
1174
|
+
try {
|
|
1175
|
+
return await h.api({ ...request, origin: h.originOf("url"), path: `${installPath(h.credentials["url"])}/wp-json${route}` });
|
|
1176
|
+
} catch (error) {
|
|
1177
|
+
throw withHint(error);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
function totalPages(response) {
|
|
1181
|
+
const value = Number(response.headers.get("x-wp-totalpages"));
|
|
1182
|
+
return Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
1183
|
+
}
|
|
1184
|
+
function totalItems(response) {
|
|
1185
|
+
const value = Number(response.headers.get("x-wp-total"));
|
|
1186
|
+
return response.headers.has("x-wp-total") && Number.isFinite(value) ? value : void 0;
|
|
1187
|
+
}
|
|
1188
|
+
var NAMED = {
|
|
1189
|
+
amp: "&",
|
|
1190
|
+
lt: "<",
|
|
1191
|
+
gt: ">",
|
|
1192
|
+
quot: '"',
|
|
1193
|
+
apos: "'",
|
|
1194
|
+
nbsp: "\xA0",
|
|
1195
|
+
hellip: "\u2026",
|
|
1196
|
+
ndash: "\u2013",
|
|
1197
|
+
mdash: "\u2014",
|
|
1198
|
+
lsquo: "\u2018",
|
|
1199
|
+
rsquo: "\u2019",
|
|
1200
|
+
ldquo: "\u201C",
|
|
1201
|
+
rdquo: "\u201D",
|
|
1202
|
+
laquo: "\xAB",
|
|
1203
|
+
raquo: "\xBB",
|
|
1204
|
+
copy: "\xA9",
|
|
1205
|
+
reg: "\xAE",
|
|
1206
|
+
trade: "\u2122"
|
|
1207
|
+
};
|
|
1208
|
+
function decodeEntities(text) {
|
|
1209
|
+
return text.replace(/&(#[xX][0-9a-fA-F]{1,6}|#\d{1,7}|[A-Za-z]{2,8});/g, (whole, body) => {
|
|
1210
|
+
if (body.startsWith("#")) {
|
|
1211
|
+
const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
|
|
1212
|
+
return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : whole;
|
|
1213
|
+
}
|
|
1214
|
+
return NAMED[body.toLowerCase()] ?? whole;
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
function plainText(html, max) {
|
|
1218
|
+
if (typeof html !== "string") return void 0;
|
|
1219
|
+
const text = decodeEntities(html.replace(/<[^>]*>/g, " ")).replace(/\s+/g, " ").trim();
|
|
1220
|
+
if (!text) return void 0;
|
|
1221
|
+
return text.length > max ? `${Array.from(text).slice(0, max - 1).join("")}\u2026` : text;
|
|
1222
|
+
}
|
|
1223
|
+
function fieldText(value) {
|
|
1224
|
+
if (typeof value === "string") return value;
|
|
1225
|
+
if (typeof value?.raw === "string") return value.raw;
|
|
1226
|
+
if (typeof value?.rendered === "string") return decodeEntities(value.rendered);
|
|
1227
|
+
return void 0;
|
|
1228
|
+
}
|
|
1229
|
+
function dateFields(value, argument) {
|
|
1230
|
+
const match = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})(:\d{2})?(?:\.\d+)?(Z|[+-]\d{2}:?\d{2})?$/i.exec(value.trim());
|
|
1231
|
+
if (!match) {
|
|
1232
|
+
throw new ToolFailure(
|
|
1233
|
+
`${argument} must look like 2026-12-01T09:00:00, with Z or an offset such as +03:00 for a fixed moment, or without one for the site's own time zone. Nothing was sent.`
|
|
1234
|
+
);
|
|
1235
|
+
}
|
|
1236
|
+
const local = `${match[1]}T${match[2]}${match[3] ?? ":00"}`;
|
|
1237
|
+
if (!match[4]) return { date: local };
|
|
1238
|
+
const offset = match[4].toUpperCase() === "Z" ? "Z" : match[4].replace(/^([+-]\d{2})(\d{2})$/, "$1:$2");
|
|
1239
|
+
const moment = Date.parse(`${local}${offset}`);
|
|
1240
|
+
if (Number.isNaN(moment)) throw new ToolFailure(`${argument} is not a valid date and time. Nothing was sent.`);
|
|
1241
|
+
return { date_gmt: new Date(moment).toISOString().slice(0, 19) };
|
|
1242
|
+
}
|
|
1243
|
+
function compact(value) {
|
|
1244
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
|
|
1245
|
+
}
|
|
1246
|
+
function phpFieldName(name2) {
|
|
1247
|
+
return (name2.split("\0")[0] ?? "").replace(/^ +/, "").replace(/[ .[]/g, "_");
|
|
1248
|
+
}
|
|
1249
|
+
function isJsonBody(request) {
|
|
1250
|
+
if (request.body === void 0) return true;
|
|
1251
|
+
const media = (request.contentType ?? "").trim().toLowerCase().split(/[;,\s]/)[0] ?? "";
|
|
1252
|
+
return media === "application/json" || /^application\/[a-z0-9!#$&^_.-]+\+json$/.test(media);
|
|
1253
|
+
}
|
|
1254
|
+
function termSearch(name2) {
|
|
1255
|
+
const parts = name2.split(/[&<>]/).map((part) => part.trim()).filter(Boolean);
|
|
1256
|
+
return parts.sort((a, b) => b.length - a.length)[0];
|
|
1257
|
+
}
|
|
1258
|
+
function termKey(name2) {
|
|
1259
|
+
return decodeEntities(name2).replace(/\s+/g, " ").trim().toLowerCase();
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// src/vendors/wordpress/index.ts
|
|
1263
|
+
var MAX_MEDIA_BYTES = 50 * 1024 * 1024;
|
|
1264
|
+
var CONTENT_BYTES = 22e3;
|
|
1265
|
+
var TYPE_ROUTES = { post: "/wp/v2/posts", page: "/wp/v2/pages" };
|
|
1266
|
+
var LIST_FIELDS = "id,type,status,title,date,modified,slug,link,excerpt,author,categories,tags,featured_media,sticky,parent,menu_order";
|
|
1267
|
+
var MEDIA_FIELDS = "id,date,title,source_url,mime_type,media_type,alt_text,post,link,media_details.width,media_details.height,media_details.filesize";
|
|
1268
|
+
var TYPE_SCHEMA = { type: "string", enum: ["post", "page"], default: "post", description: "post (default) or page." };
|
|
1269
|
+
var CURSOR_SCHEMA = { type: "string", description: "nextCursor from the previous result; the other arguments then come from it." };
|
|
1270
|
+
var ID_LIST = (what) => ({ type: "array", items: { type: "integer", minimum: 1 }, maxItems: 100, uniqueItems: true, description: what });
|
|
1271
|
+
var POST_FIELDS = {
|
|
1272
|
+
title: { type: "string", maxLength: 1e3, description: "The title, as plain text." },
|
|
1273
|
+
content: {
|
|
1274
|
+
type: "string",
|
|
1275
|
+
maxLength: 2e6,
|
|
1276
|
+
description: 'The body as HTML (<h2>, <p>, <img src="..."> with media library URLs, <figure>, <table>, ...).'
|
|
1277
|
+
},
|
|
1278
|
+
excerpt: { type: "string", maxLength: 5e3, description: "A short summary shown in lists and feeds." },
|
|
1279
|
+
slug: { type: "string", pattern: "^[A-Za-z0-9%_-]{1,200}$", description: 'The URL slug, e.g. "my-first-post".' },
|
|
1280
|
+
status: {
|
|
1281
|
+
type: "string",
|
|
1282
|
+
enum: ["draft", "publish", "pending", "private", "future"],
|
|
1283
|
+
description: "draft (not public), publish (goes live now), pending (waits for an editor), private, or future (published at date)."
|
|
1284
|
+
},
|
|
1285
|
+
date: {
|
|
1286
|
+
type: "string",
|
|
1287
|
+
maxLength: 40,
|
|
1288
|
+
description: "Publication date: 2026-12-01T09:00:00 in the site's time zone, or with Z or an offset (+03:00). Needed with status future."
|
|
1289
|
+
},
|
|
1290
|
+
categories: ID_LIST("Category ids (posts only), from list_terms or create_term. Replaces the post's categories."),
|
|
1291
|
+
tags: ID_LIST("Tag ids (posts only), from list_terms or create_term. Replaces the post's tags."),
|
|
1292
|
+
featured_media: { type: "integer", minimum: 0, description: "The media id of the featured image (cover), from upload_media; 0 removes it." },
|
|
1293
|
+
author: { type: "integer", minimum: 1, description: "The author's user id (an Editor or Administrator may set another user)." },
|
|
1294
|
+
comment_status: { type: "string", enum: ["open", "closed"], description: "Whether comments are open." },
|
|
1295
|
+
sticky: { type: "boolean", description: "Posts only: keep it at the top of the blog page." },
|
|
1296
|
+
parent: { type: "integer", minimum: 0, description: "Pages only: the parent page id (0 for none)." },
|
|
1297
|
+
menu_order: { type: "integer", minimum: 0, description: "Pages only: the order among sibling pages." }
|
|
1298
|
+
};
|
|
1299
|
+
function invalidCursor() {
|
|
1300
|
+
return new ToolFailure("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.");
|
|
1301
|
+
}
|
|
1302
|
+
function listPosition(h, schema, args) {
|
|
1303
|
+
const state = h.cursor(args["cursor"]);
|
|
1304
|
+
if (!state) {
|
|
1305
|
+
const { cursor: _cursor, ...filters } = args;
|
|
1306
|
+
return { page: 1, skip: 0, filters };
|
|
1307
|
+
}
|
|
1308
|
+
let parsed;
|
|
1309
|
+
try {
|
|
1310
|
+
parsed = JSON.parse(String(state["f"] ?? "{}"));
|
|
1311
|
+
} catch {
|
|
1312
|
+
throw invalidCursor();
|
|
1313
|
+
}
|
|
1314
|
+
const checked = validateArguments(schema, parsed);
|
|
1315
|
+
const page = Number(state["p"]);
|
|
1316
|
+
const skip = Number(state["o"]);
|
|
1317
|
+
if (!checked.ok || "cursor" in checked.value || !Number.isInteger(page) || page < 1 || !Number.isInteger(skip) || skip < 0) throw invalidCursor();
|
|
1318
|
+
return { page, skip, filters: checked.value };
|
|
1319
|
+
}
|
|
1320
|
+
function pageCursors(h, position, more) {
|
|
1321
|
+
const f = JSON.stringify(position.filters);
|
|
1322
|
+
return {
|
|
1323
|
+
resumeAt: (index) => h.makeCursor({ p: position.page, o: position.skip + index, f }),
|
|
1324
|
+
...more ? { nextPage: h.makeCursor({ p: position.page + 1, o: 0, f }) } : {}
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
function hasMore(response, page, count, perPage) {
|
|
1328
|
+
const pages = totalPages(response);
|
|
1329
|
+
return pages !== void 0 ? page < pages : count >= perPage;
|
|
1330
|
+
}
|
|
1331
|
+
function chunkEnd(points, start, maxBytes) {
|
|
1332
|
+
let bytes = 0;
|
|
1333
|
+
let index = start;
|
|
1334
|
+
for (; index < points.length; index++) {
|
|
1335
|
+
const point = points[index];
|
|
1336
|
+
const code = point.codePointAt(0) ?? 0;
|
|
1337
|
+
const size = point === '"' || point === "\\" ? 2 : code < 32 ? 6 : code < 128 ? 1 : code < 2048 ? 2 : code < 65536 ? 3 : 4;
|
|
1338
|
+
if (bytes + size > maxBytes) break;
|
|
1339
|
+
bytes += size;
|
|
1340
|
+
}
|
|
1341
|
+
return index;
|
|
1342
|
+
}
|
|
1343
|
+
function trimPost(h, post) {
|
|
1344
|
+
const isPage = post?.type === "page";
|
|
1345
|
+
return compact({
|
|
1346
|
+
id: post?.id,
|
|
1347
|
+
type: post?.type,
|
|
1348
|
+
status: post?.status,
|
|
1349
|
+
title: truncate(fieldText(post?.title) ?? "", 300),
|
|
1350
|
+
date: post?.date,
|
|
1351
|
+
modified: post?.modified,
|
|
1352
|
+
slug: post?.slug,
|
|
1353
|
+
link: post?.link,
|
|
1354
|
+
edit_link: editLink(h, post?.id),
|
|
1355
|
+
excerpt: plainText(post?.excerpt?.rendered ?? post?.excerpt?.raw, 240),
|
|
1356
|
+
author: post?.author,
|
|
1357
|
+
categories: Array.isArray(post?.categories) && post.categories.length ? post.categories : void 0,
|
|
1358
|
+
tags: Array.isArray(post?.tags) && post.tags.length ? post.tags : void 0,
|
|
1359
|
+
featured_media: post?.featured_media || void 0,
|
|
1360
|
+
sticky: post?.sticky === true ? true : void 0,
|
|
1361
|
+
parent: isPage && post?.parent ? post.parent : void 0,
|
|
1362
|
+
menu_order: isPage && post?.menu_order ? post.menu_order : void 0
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
function trimMedia(media) {
|
|
1366
|
+
return compact({
|
|
1367
|
+
id: media?.id,
|
|
1368
|
+
date: media?.date,
|
|
1369
|
+
title: truncate(fieldText(media?.title) ?? "", 200),
|
|
1370
|
+
source_url: media?.source_url,
|
|
1371
|
+
mime_type: media?.mime_type,
|
|
1372
|
+
media_type: media?.media_type,
|
|
1373
|
+
alt_text: media?.alt_text,
|
|
1374
|
+
caption: plainText(media?.caption?.raw ?? media?.caption?.rendered, 300),
|
|
1375
|
+
width: media?.media_details?.width,
|
|
1376
|
+
height: media?.media_details?.height,
|
|
1377
|
+
filesize: media?.media_details?.filesize,
|
|
1378
|
+
attached_to: media?.post || void 0,
|
|
1379
|
+
link: media?.link
|
|
1380
|
+
});
|
|
1381
|
+
}
|
|
1382
|
+
function trimTerm(term) {
|
|
1383
|
+
return compact({
|
|
1384
|
+
id: term?.id,
|
|
1385
|
+
name: typeof term?.name === "string" ? decodeEntities(term.name) : void 0,
|
|
1386
|
+
slug: term?.slug,
|
|
1387
|
+
count: term?.count,
|
|
1388
|
+
parent: term?.parent || void 0,
|
|
1389
|
+
description: plainText(term?.description, 200),
|
|
1390
|
+
link: term?.link
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
function postBody(args) {
|
|
1394
|
+
const isPage = args.type === "page";
|
|
1395
|
+
const wrongType = (field, only) => {
|
|
1396
|
+
throw new ToolFailure(`${field} is for ${only} only. Nothing was sent.`);
|
|
1397
|
+
};
|
|
1398
|
+
if (isPage && (args.categories !== void 0 || args.tags !== void 0 || args.sticky !== void 0)) wrongType("categories, tags and sticky are", "posts");
|
|
1399
|
+
if (!isPage && (args.parent !== void 0 || args.menu_order !== void 0)) wrongType("parent and menu_order are", "pages");
|
|
1400
|
+
if (args.status === "future" && args.date === void 0) {
|
|
1401
|
+
throw new ToolFailure("status future needs date: the time the post goes live. Nothing was sent.");
|
|
1402
|
+
}
|
|
1403
|
+
const body = {};
|
|
1404
|
+
for (const field of ["title", "content", "excerpt", "slug", "status", "categories", "tags", "featured_media", "author", "comment_status", "sticky", "parent", "menu_order"]) {
|
|
1405
|
+
if (args[field] !== void 0) body[field] = args[field];
|
|
1406
|
+
}
|
|
1407
|
+
if (args.date !== void 0) Object.assign(body, dateFields(args.date, "date"));
|
|
1408
|
+
return body;
|
|
1409
|
+
}
|
|
1410
|
+
function savedPost(h, post) {
|
|
1411
|
+
return compact({
|
|
1412
|
+
...trimPost(h, post),
|
|
1413
|
+
date_gmt: post?.date_gmt,
|
|
1414
|
+
note: post?.status === "draft" || post?.status === "pending" ? "Not public yet: it goes live with update_post and status publish." : void 0
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
function refuseRequest(sentence) {
|
|
1418
|
+
throw new ToolFailure(`${sentence} Nothing was sent.`);
|
|
1419
|
+
}
|
|
1420
|
+
function restGuard(request) {
|
|
1421
|
+
for (const key of Object.keys(request.query)) {
|
|
1422
|
+
if (/^(?:_method|rest_route)/i.test(phpFieldName(key))) {
|
|
1423
|
+
refuseRequest(`The query parameter ${JSON.stringify(key)} is not allowed: WordPress would read it as _method or rest_route, which change a request's method or route. Give the route as the path and the method as method.`);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
if (request.segments.some((segment) => /[/\\]/.test(segment))) {
|
|
1427
|
+
refuseRequest("A path segment must not hold an encoded slash or backslash (%2F, %5C): give each part of the route as its own segment.");
|
|
1428
|
+
}
|
|
1429
|
+
const segments = request.segments.map((segment) => segment.toLowerCase());
|
|
1430
|
+
if (segments[0] === "batch") refuseRequest("Batch requests (/batch/v1) cannot be sent through this connector: send each request on its own.");
|
|
1431
|
+
if (segments.includes("application-passwords")) refuseRequest("Application passwords cannot be listed or changed through this connector.");
|
|
1432
|
+
if (request.method === "GET" || segments[0] !== "wp" || segments[1] !== "v2") return;
|
|
1433
|
+
const resource = segments[2];
|
|
1434
|
+
if (resource === "plugins" || resource === "themes") refuseRequest("Plugins and themes cannot be installed, changed or removed through this connector.");
|
|
1435
|
+
if (resource === "settings") refuseRequest("Site settings cannot be changed through this connector.");
|
|
1436
|
+
if (resource === "users") refuseRequest("Users cannot be created, changed or deleted through this connector.");
|
|
1437
|
+
}
|
|
1438
|
+
var LIST_POSTS_SCHEMA = {
|
|
1439
|
+
type: "object",
|
|
1440
|
+
properties: {
|
|
1441
|
+
type: TYPE_SCHEMA,
|
|
1442
|
+
status: {
|
|
1443
|
+
type: "string",
|
|
1444
|
+
enum: ["any", "publish", "draft", "pending", "future", "private"],
|
|
1445
|
+
default: "any",
|
|
1446
|
+
description: "any (default: every status but trash), publish, draft, pending, future (scheduled) or private."
|
|
1447
|
+
},
|
|
1448
|
+
search: { type: "string", minLength: 1, maxLength: 200, description: "Words to look for in the title and content." },
|
|
1449
|
+
categories: ID_LIST("Only posts in one of these category ids."),
|
|
1450
|
+
tags: ID_LIST("Only posts with one of these tag ids."),
|
|
1451
|
+
author: { type: "integer", minimum: 1, description: "Only items by this user id." },
|
|
1452
|
+
after: { type: "string", maxLength: 40, description: "Only items published after this date, e.g. 2026-11-01T00:00:00." },
|
|
1453
|
+
before: { type: "string", maxLength: 40, description: "Only items published before this date." },
|
|
1454
|
+
orderby: { type: "string", enum: ["date", "modified", "title", "id", "slug", "relevance"], default: "date", description: "Sort field (relevance needs search)." },
|
|
1455
|
+
order: { type: "string", enum: ["desc", "asc"], default: "desc", description: "desc (default, newest first) or asc." },
|
|
1456
|
+
per_page: { type: "integer", minimum: 1, maximum: 100, default: 20, description: "Items per page, 1 to 100 (default 20)." },
|
|
1457
|
+
cursor: CURSOR_SCHEMA
|
|
1458
|
+
},
|
|
1459
|
+
additionalProperties: false
|
|
1460
|
+
};
|
|
1461
|
+
var LIST_MEDIA_SCHEMA = {
|
|
1462
|
+
type: "object",
|
|
1463
|
+
properties: {
|
|
1464
|
+
search: { type: "string", minLength: 1, maxLength: 200, description: "Words to look for in the title, caption or file name." },
|
|
1465
|
+
media_type: { type: "string", enum: ["image", "video", "audio", "application", "text"], description: "Only this kind of file." },
|
|
1466
|
+
mime_type: { type: "string", pattern: "^[a-z]+/[A-Za-z0-9.+-]+$", description: "Only this MIME type, e.g. image/png." },
|
|
1467
|
+
attached_to: { type: "integer", minimum: 0, description: "Only files attached to this post id (0: unattached)." },
|
|
1468
|
+
orderby: { type: "string", enum: ["date", "title", "id"], default: "date", description: "Sort field." },
|
|
1469
|
+
order: { type: "string", enum: ["desc", "asc"], default: "desc", description: "desc (default, newest first) or asc." },
|
|
1470
|
+
per_page: { type: "integer", minimum: 1, maximum: 100, default: 20, description: "Files per page, 1 to 100 (default 20)." },
|
|
1471
|
+
cursor: CURSOR_SCHEMA
|
|
1472
|
+
},
|
|
1473
|
+
additionalProperties: false
|
|
1474
|
+
};
|
|
1475
|
+
var TAXONOMY_SCHEMA = { type: "string", enum: ["categories", "tags"], description: "categories or tags." };
|
|
1476
|
+
var LIST_TERMS_SCHEMA = {
|
|
1477
|
+
type: "object",
|
|
1478
|
+
properties: {
|
|
1479
|
+
taxonomy: { ...TAXONOMY_SCHEMA, default: "categories", description: "categories (default) or tags." },
|
|
1480
|
+
search: { type: "string", minLength: 1, maxLength: 200, description: "Part of the name to look for." },
|
|
1481
|
+
slug: { type: "string", pattern: "^[A-Za-z0-9%_-]{1,200}$", description: "An exact slug." },
|
|
1482
|
+
parent: { type: "integer", minimum: 0, description: "Categories only: only children of this category id (0: top level)." },
|
|
1483
|
+
hide_empty: { type: "boolean", default: false, description: "Leave out terms that no post uses." },
|
|
1484
|
+
orderby: { type: "string", enum: ["name", "count", "id", "slug"], default: "name", description: "Sort field." },
|
|
1485
|
+
per_page: { type: "integer", minimum: 1, maximum: 100, default: 100, description: "Terms per page, 1 to 100 (default 100)." },
|
|
1486
|
+
cursor: CURSOR_SCHEMA
|
|
1487
|
+
},
|
|
1488
|
+
additionalProperties: false
|
|
1489
|
+
};
|
|
1490
|
+
async function findTerm(h, taxonomy, name2, slug, parent) {
|
|
1491
|
+
const query = slug ? { slug, per_page: 10 } : { search: termSearch(name2), per_page: 100 };
|
|
1492
|
+
const { data } = await rest(h, `/wp/v2/${taxonomy}`, { query: { ...query, parent, _fields: "id,name,slug,count,parent,description,link" } });
|
|
1493
|
+
const terms = Array.isArray(data) ? data : [];
|
|
1494
|
+
const wanted = termKey(name2);
|
|
1495
|
+
return terms.find((term) => (parent === void 0 || Number(term?.parent ?? 0) === parent) && (slug !== void 0 && term?.slug === slug || termKey(String(term?.name ?? "")) === wanted));
|
|
1496
|
+
}
|
|
1497
|
+
var connector = defineConnector({
|
|
1498
|
+
vendor: "wordpress",
|
|
1499
|
+
label: "WordPress",
|
|
1500
|
+
origins: [],
|
|
1501
|
+
originFields: ["url"],
|
|
1502
|
+
credentials: ["url", "user", "apppassword"],
|
|
1503
|
+
credentialLabels: { url: "WordPress URL", user: "WordPress user name", apppassword: "WordPress application password" },
|
|
1504
|
+
authHeaders: (credentials) => ({ authorization: basicAuth(credentials["user"] ?? "", credentials["apppassword"] ?? "") }),
|
|
1505
|
+
tools: [
|
|
1506
|
+
{
|
|
1507
|
+
name: "get_site",
|
|
1508
|
+
kind: "read",
|
|
1509
|
+
title: "Get the WordPress site and the connected user",
|
|
1510
|
+
description: "The connected WordPress site (name, tagline, address, time zone) and the user the application password belongs to, with its roles and what it may do: publish posts, edit others' posts, publish pages, upload files, manage categories. It also says whether the Rank Math SEO plugin's API is there (for set_seo_meta). Use it to check the connection.",
|
|
1511
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
1512
|
+
async run(_args, h) {
|
|
1513
|
+
const { data: user } = await rest(h, "/wp/v2/users/me", { query: { context: "edit", _fields: "id,username,name,slug,roles,capabilities" } });
|
|
1514
|
+
const { data: index } = await rest(h, "/", { query: { _fields: "name,description,url,home,gmt_offset,timezone_string,namespaces" } });
|
|
1515
|
+
const namespaces = Array.isArray(index?.namespaces) ? index.namespaces.map(String) : [];
|
|
1516
|
+
const caps = typeof user?.capabilities === "object" && user.capabilities !== null ? user.capabilities : {};
|
|
1517
|
+
const can = (cap) => caps[cap] === true;
|
|
1518
|
+
const offset = typeof index?.gmt_offset === "number" || typeof index?.gmt_offset === "string" ? Number(index.gmt_offset) : void 0;
|
|
1519
|
+
return compact({
|
|
1520
|
+
site: compact({
|
|
1521
|
+
name: typeof index?.name === "string" ? decodeEntities(index.name) : void 0,
|
|
1522
|
+
tagline: typeof index?.description === "string" ? decodeEntities(index.description) : void 0,
|
|
1523
|
+
url: index?.home ?? index?.url,
|
|
1524
|
+
wordpress_address: index?.url !== index?.home ? index?.url : void 0,
|
|
1525
|
+
timezone: index?.timezone_string || (offset !== void 0 && Number.isFinite(offset) ? `UTC${offset >= 0 ? "+" : ""}${offset}` : void 0)
|
|
1526
|
+
}),
|
|
1527
|
+
rest_url: `${siteAddress(h)}/wp-json/`,
|
|
1528
|
+
user: compact({
|
|
1529
|
+
id: user?.id,
|
|
1530
|
+
username: user?.username,
|
|
1531
|
+
name: user?.name,
|
|
1532
|
+
roles: Array.isArray(user?.roles) ? user.roles : void 0,
|
|
1533
|
+
can: {
|
|
1534
|
+
publish_posts: can("publish_posts"),
|
|
1535
|
+
edit_others_posts: can("edit_others_posts"),
|
|
1536
|
+
publish_pages: can("publish_pages"),
|
|
1537
|
+
upload_files: can("upload_files"),
|
|
1538
|
+
manage_categories: can("manage_categories")
|
|
1539
|
+
}
|
|
1540
|
+
}),
|
|
1541
|
+
rank_math: namespaces.includes("rankmath/v1")
|
|
1542
|
+
});
|
|
1543
|
+
}
|
|
1544
|
+
},
|
|
1545
|
+
{
|
|
1546
|
+
name: "list_posts",
|
|
1547
|
+
kind: "read",
|
|
1548
|
+
title: "List WordPress posts or pages",
|
|
1549
|
+
description: "Lists the site's posts (or pages), newest first by default: drafts, scheduled and published ones, or one status. Each has its id, status, title, dates, link, editor link, excerpt, categories, tags and featured image id. Search words find posts on a topic (to avoid writing the same post twice). Pass nextCursor back as cursor for more.",
|
|
1550
|
+
inputSchema: LIST_POSTS_SCHEMA,
|
|
1551
|
+
async run(args, h) {
|
|
1552
|
+
const position = listPosition(h, LIST_POSTS_SCHEMA, args);
|
|
1553
|
+
const f = position.filters;
|
|
1554
|
+
const type = f["type"] ?? "post";
|
|
1555
|
+
if (type === "page" && (f["categories"] || f["tags"])) throw new ToolFailure("categories and tags are for posts only. Nothing was sent.");
|
|
1556
|
+
const response = await rest(h, TYPE_ROUTES[type], {
|
|
1557
|
+
query: {
|
|
1558
|
+
context: "view",
|
|
1559
|
+
_fields: LIST_FIELDS,
|
|
1560
|
+
status: f["status"] ?? "any",
|
|
1561
|
+
search: f["search"],
|
|
1562
|
+
categories: f["categories"]?.join(","),
|
|
1563
|
+
tags: f["tags"]?.join(","),
|
|
1564
|
+
author: f["author"],
|
|
1565
|
+
after: f["after"],
|
|
1566
|
+
before: f["before"],
|
|
1567
|
+
orderby: f["orderby"] ?? "date",
|
|
1568
|
+
order: f["order"] ?? "desc",
|
|
1569
|
+
per_page: f["per_page"] ?? 20,
|
|
1570
|
+
page: position.page
|
|
1571
|
+
}
|
|
1572
|
+
});
|
|
1573
|
+
const posts = Array.isArray(response.data) ? response.data : [];
|
|
1574
|
+
const perPage = Number(f["per_page"] ?? 20);
|
|
1575
|
+
return h.page({
|
|
1576
|
+
key: type === "page" ? "pages" : "posts",
|
|
1577
|
+
items: posts.map((post) => trimPost(h, post)).slice(position.skip),
|
|
1578
|
+
extra: compact({ total: totalItems(response), page: position.page }),
|
|
1579
|
+
...pageCursors(h, position, hasMore(response, position.page, posts.length, perPage))
|
|
1580
|
+
});
|
|
1581
|
+
}
|
|
1582
|
+
},
|
|
1583
|
+
{
|
|
1584
|
+
name: "get_post",
|
|
1585
|
+
kind: "read",
|
|
1586
|
+
title: "Get a WordPress post or page",
|
|
1587
|
+
description: "One post (or page) by id, with its raw title, HTML content, excerpt, status, slug, dates, categories, tags, featured image, link and editor link: what update_post needs to edit it. Long content comes in parts of about 20 KB: pass next_content_offset as content_offset for the next part.",
|
|
1588
|
+
inputSchema: {
|
|
1589
|
+
type: "object",
|
|
1590
|
+
properties: {
|
|
1591
|
+
id: { type: "integer", minimum: 1, description: "The post or page id." },
|
|
1592
|
+
type: TYPE_SCHEMA,
|
|
1593
|
+
content_offset: { type: "integer", minimum: 0, default: 0, description: "Where the content part starts (default 0)." }
|
|
1594
|
+
},
|
|
1595
|
+
required: ["id"],
|
|
1596
|
+
additionalProperties: false
|
|
1597
|
+
},
|
|
1598
|
+
async run(args, h) {
|
|
1599
|
+
const route = `${TYPE_ROUTES[args.type]}/${args.id}`;
|
|
1600
|
+
let post;
|
|
1601
|
+
try {
|
|
1602
|
+
({ data: post } = await rest(h, route, { query: { context: "edit" } }));
|
|
1603
|
+
} catch (error) {
|
|
1604
|
+
if (!(error instanceof ToolFailure) || error.details.status !== 403) throw error;
|
|
1605
|
+
({ data: post } = await rest(h, route, { query: { context: "view" } }));
|
|
1606
|
+
}
|
|
1607
|
+
const content = typeof post?.content?.raw === "string" ? post.content.raw : String(post?.content?.rendered ?? "");
|
|
1608
|
+
const points = Array.from(content);
|
|
1609
|
+
const start = Math.min(args.content_offset, points.length);
|
|
1610
|
+
const end = chunkEnd(points, start, CONTENT_BYTES);
|
|
1611
|
+
return compact({
|
|
1612
|
+
...trimPost(h, post),
|
|
1613
|
+
title: fieldText(post?.title),
|
|
1614
|
+
excerpt: fieldText(post?.excerpt),
|
|
1615
|
+
date_gmt: post?.date_gmt,
|
|
1616
|
+
comment_status: post?.comment_status,
|
|
1617
|
+
format: post?.format && post.format !== "standard" ? post.format : void 0,
|
|
1618
|
+
template: post?.template || void 0,
|
|
1619
|
+
password_protected: post?.password ? true : void 0,
|
|
1620
|
+
content: points.slice(start, end).join(""),
|
|
1621
|
+
content_length: points.length,
|
|
1622
|
+
content_offset: start > 0 ? start : void 0,
|
|
1623
|
+
next_content_offset: end < points.length ? end : void 0
|
|
1624
|
+
});
|
|
1625
|
+
}
|
|
1626
|
+
},
|
|
1627
|
+
{
|
|
1628
|
+
name: "create_post",
|
|
1629
|
+
kind: "create",
|
|
1630
|
+
check: "list_posts",
|
|
1631
|
+
title: "Create a WordPress post or page",
|
|
1632
|
+
description: "Creates a post (or page). It is a draft unless status says otherwise: publish puts it live at once, future at date. Body as HTML; categories and tags by id (list_terms, create_term); featured_media is a media id from upload_media. Returns the id, link and editor link. Not retried: after an unclear outcome, look for it with list_posts before trying again.",
|
|
1633
|
+
inputSchema: {
|
|
1634
|
+
type: "object",
|
|
1635
|
+
properties: { type: TYPE_SCHEMA, ...POST_FIELDS, status: { ...POST_FIELDS["status"], default: "draft" } },
|
|
1636
|
+
required: ["title"],
|
|
1637
|
+
additionalProperties: false
|
|
1638
|
+
},
|
|
1639
|
+
async run(args, h) {
|
|
1640
|
+
const body = postBody(args);
|
|
1641
|
+
const { data } = await rest(h, TYPE_ROUTES[args.type], { method: "POST", json: body, write: true });
|
|
1642
|
+
return savedPost(h, data);
|
|
1643
|
+
}
|
|
1644
|
+
},
|
|
1645
|
+
{
|
|
1646
|
+
name: "update_post",
|
|
1647
|
+
kind: "update",
|
|
1648
|
+
check: "get_post",
|
|
1649
|
+
title: "Update or publish a WordPress post or page",
|
|
1650
|
+
description: "Changes a post (or page): only the fields given change. status publish puts a draft live; draft takes a post back offline; featured_media sets or replaces the cover (0 removes it). Editing a published post changes it live. Returns the saved post.",
|
|
1651
|
+
inputSchema: {
|
|
1652
|
+
type: "object",
|
|
1653
|
+
properties: { id: { type: "integer", minimum: 1, description: "The post or page id." }, type: TYPE_SCHEMA, ...POST_FIELDS },
|
|
1654
|
+
required: ["id"],
|
|
1655
|
+
additionalProperties: false
|
|
1656
|
+
},
|
|
1657
|
+
async run(args, h) {
|
|
1658
|
+
const body = postBody(args);
|
|
1659
|
+
if (!Object.keys(body).length) throw new ToolFailure("Nothing to change: give at least one field besides id and type. Nothing was sent.");
|
|
1660
|
+
const { data } = await rest(h, `${TYPE_ROUTES[args.type]}/${args.id}`, { method: "POST", json: body, write: true });
|
|
1661
|
+
return savedPost(h, data);
|
|
1662
|
+
}
|
|
1663
|
+
},
|
|
1664
|
+
{
|
|
1665
|
+
name: "upload_media",
|
|
1666
|
+
kind: "create",
|
|
1667
|
+
check: "list_media",
|
|
1668
|
+
title: "Upload a file to the WordPress media library",
|
|
1669
|
+
description: `Downloads a file from a public https URL and uploads it to the media library, with alt text, title and caption. Takes ${MEDIA_TYPES_TEXT}, told by the file's bytes; the site's own upload limit applies. Returns the media id (for featured_media) and its source_url (for <img> tags in content).`,
|
|
1670
|
+
inputSchema: {
|
|
1671
|
+
type: "object",
|
|
1672
|
+
properties: {
|
|
1673
|
+
url: { type: "string", format: "uri", maxLength: 2e3, description: "A public https URL of the file." },
|
|
1674
|
+
filename: { type: "string", maxLength: 120, description: "The file name to give it (the extension follows the file type). Default: from the URL." },
|
|
1675
|
+
alt_text: { type: "string", maxLength: 300, description: "Alt text for an image: what it shows." },
|
|
1676
|
+
title: { type: "string", maxLength: 200, description: "The title in the media library." },
|
|
1677
|
+
caption: { type: "string", maxLength: 500, description: "A caption." },
|
|
1678
|
+
description: { type: "string", maxLength: 1e3, description: "A description." },
|
|
1679
|
+
post_id: { type: "integer", minimum: 1, description: "Attach the file to this post or page id." }
|
|
1680
|
+
},
|
|
1681
|
+
required: ["url"],
|
|
1682
|
+
additionalProperties: false
|
|
1683
|
+
},
|
|
1684
|
+
async run(args, h) {
|
|
1685
|
+
const file = await h.media(args.url, { what: "file", maxBytes: MAX_MEDIA_BYTES });
|
|
1686
|
+
const type = sniffFile(file.bytes);
|
|
1687
|
+
if (!type) {
|
|
1688
|
+
throw new ToolFailure(`The file is not a type the media library takes by default (${MEDIA_TYPES_TEXT}), judging by its content. Nothing was sent to WordPress.`);
|
|
1689
|
+
}
|
|
1690
|
+
const name2 = uploadName(args.filename, args.url, type.ext);
|
|
1691
|
+
const { data } = await rest(h, "/wp/v2/media", {
|
|
1692
|
+
method: "POST",
|
|
1693
|
+
// WordPress reads these from the query string when the body is the file itself.
|
|
1694
|
+
query: { alt_text: args.alt_text, title: args.title, caption: args.caption, description: args.description, post: args.post_id },
|
|
1695
|
+
headers: { "content-disposition": `attachment; filename="${name2}"` },
|
|
1696
|
+
body: file.bytes,
|
|
1697
|
+
contentType: type.mime,
|
|
1698
|
+
write: true,
|
|
1699
|
+
errors: { 413: "The site refused the file as larger than its upload limit" }
|
|
1700
|
+
});
|
|
1701
|
+
return trimMedia(data);
|
|
1702
|
+
}
|
|
1703
|
+
},
|
|
1704
|
+
{
|
|
1705
|
+
name: "update_media",
|
|
1706
|
+
kind: "update",
|
|
1707
|
+
check: "list_media",
|
|
1708
|
+
title: "Update a WordPress media item",
|
|
1709
|
+
description: "Changes a media item's alt text, title, caption or description, or the post it is attached to. Only the fields given change.",
|
|
1710
|
+
inputSchema: {
|
|
1711
|
+
type: "object",
|
|
1712
|
+
properties: {
|
|
1713
|
+
id: { type: "integer", minimum: 1, description: "The media id." },
|
|
1714
|
+
alt_text: { type: "string", maxLength: 1e3, description: "Alt text: what the image shows." },
|
|
1715
|
+
title: { type: "string", maxLength: 500, description: "The title." },
|
|
1716
|
+
caption: { type: "string", maxLength: 5e3, description: "The caption." },
|
|
1717
|
+
description: { type: "string", maxLength: 2e4, description: "The description." },
|
|
1718
|
+
post_id: { type: "integer", minimum: 0, description: "Attach it to this post or page id (0 detaches it)." }
|
|
1719
|
+
},
|
|
1720
|
+
required: ["id"],
|
|
1721
|
+
additionalProperties: false
|
|
1722
|
+
},
|
|
1723
|
+
async run(args, h) {
|
|
1724
|
+
const body = compact({ alt_text: args.alt_text, title: args.title, caption: args.caption, description: args.description, post: args.post_id });
|
|
1725
|
+
if (args.alt_text === "") body["alt_text"] = "";
|
|
1726
|
+
if (args.post_id === 0) body["post"] = 0;
|
|
1727
|
+
if (!Object.keys(body).length) throw new ToolFailure("Nothing to change: give at least one field besides id. Nothing was sent.");
|
|
1728
|
+
const { data } = await rest(h, `/wp/v2/media/${args.id}`, { method: "POST", json: body, write: true });
|
|
1729
|
+
return trimMedia(data);
|
|
1730
|
+
}
|
|
1731
|
+
},
|
|
1732
|
+
{
|
|
1733
|
+
name: "list_media",
|
|
1734
|
+
kind: "read",
|
|
1735
|
+
title: "List the WordPress media library",
|
|
1736
|
+
description: "Lists files in the media library, newest first: id, title, source URL, type, alt text, size in pixels and bytes, and the post each is attached to. Search words or a type narrow it. Pass nextCursor back as cursor for more.",
|
|
1737
|
+
inputSchema: LIST_MEDIA_SCHEMA,
|
|
1738
|
+
async run(args, h) {
|
|
1739
|
+
const position = listPosition(h, LIST_MEDIA_SCHEMA, args);
|
|
1740
|
+
const f = position.filters;
|
|
1741
|
+
const perPage = Number(f["per_page"] ?? 20);
|
|
1742
|
+
const response = await rest(h, "/wp/v2/media", {
|
|
1743
|
+
query: {
|
|
1744
|
+
_fields: MEDIA_FIELDS,
|
|
1745
|
+
search: f["search"],
|
|
1746
|
+
media_type: f["media_type"],
|
|
1747
|
+
mime_type: f["mime_type"],
|
|
1748
|
+
parent: f["attached_to"],
|
|
1749
|
+
orderby: f["orderby"] ?? "date",
|
|
1750
|
+
order: f["order"] ?? "desc",
|
|
1751
|
+
per_page: perPage,
|
|
1752
|
+
page: position.page
|
|
1753
|
+
}
|
|
1754
|
+
});
|
|
1755
|
+
const media = Array.isArray(response.data) ? response.data : [];
|
|
1756
|
+
return h.page({
|
|
1757
|
+
key: "media",
|
|
1758
|
+
items: media.map(trimMedia).slice(position.skip),
|
|
1759
|
+
extra: compact({ total: totalItems(response), page: position.page }),
|
|
1760
|
+
...pageCursors(h, position, hasMore(response, position.page, media.length, perPage))
|
|
1761
|
+
});
|
|
1762
|
+
}
|
|
1763
|
+
},
|
|
1764
|
+
{
|
|
1765
|
+
name: "list_terms",
|
|
1766
|
+
kind: "read",
|
|
1767
|
+
title: "List WordPress categories or tags",
|
|
1768
|
+
description: "Lists the site's categories or tags with their ids, names, slugs, post counts and parents. Search for a name before creating a term, so none is made twice. Pass nextCursor back as cursor for more.",
|
|
1769
|
+
inputSchema: LIST_TERMS_SCHEMA,
|
|
1770
|
+
async run(args, h) {
|
|
1771
|
+
const position = listPosition(h, LIST_TERMS_SCHEMA, args);
|
|
1772
|
+
const f = position.filters;
|
|
1773
|
+
const taxonomy = String(f["taxonomy"] ?? "categories");
|
|
1774
|
+
if (taxonomy === "tags" && f["parent"] !== void 0) throw new ToolFailure("parent is for categories only. Nothing was sent.");
|
|
1775
|
+
const perPage = Number(f["per_page"] ?? 100);
|
|
1776
|
+
const response = await rest(h, `/wp/v2/${taxonomy}`, {
|
|
1777
|
+
query: {
|
|
1778
|
+
_fields: "id,name,slug,count,parent,description,link",
|
|
1779
|
+
search: f["search"],
|
|
1780
|
+
slug: f["slug"],
|
|
1781
|
+
parent: f["parent"],
|
|
1782
|
+
hide_empty: f["hide_empty"] ? true : void 0,
|
|
1783
|
+
orderby: f["orderby"] ?? "name",
|
|
1784
|
+
per_page: perPage,
|
|
1785
|
+
page: position.page
|
|
1786
|
+
}
|
|
1787
|
+
});
|
|
1788
|
+
const terms = Array.isArray(response.data) ? response.data : [];
|
|
1789
|
+
return h.page({
|
|
1790
|
+
key: taxonomy,
|
|
1791
|
+
items: terms.map(trimTerm).slice(position.skip),
|
|
1792
|
+
extra: compact({ total: totalItems(response), page: position.page }),
|
|
1793
|
+
...pageCursors(h, position, hasMore(response, position.page, terms.length, perPage))
|
|
1794
|
+
});
|
|
1795
|
+
}
|
|
1796
|
+
},
|
|
1797
|
+
{
|
|
1798
|
+
name: "create_term",
|
|
1799
|
+
kind: "create",
|
|
1800
|
+
check: "list_terms",
|
|
1801
|
+
title: "Create a WordPress category or tag",
|
|
1802
|
+
description: "Creates a category or tag and returns its id for create_post. When one with that name (or slug) already exists, WordPress keeps it and this returns the existing one with existing: true, so it is never made twice.",
|
|
1803
|
+
inputSchema: {
|
|
1804
|
+
type: "object",
|
|
1805
|
+
properties: {
|
|
1806
|
+
taxonomy: TAXONOMY_SCHEMA,
|
|
1807
|
+
name: { type: "string", minLength: 1, maxLength: 200, description: "The name." },
|
|
1808
|
+
slug: { type: "string", pattern: "^[A-Za-z0-9%_-]{1,200}$", description: "The slug (default: made from the name)." },
|
|
1809
|
+
parent: { type: "integer", minimum: 0, description: "Categories only: the parent category id." },
|
|
1810
|
+
description: { type: "string", maxLength: 2e3, description: "A description." }
|
|
1811
|
+
},
|
|
1812
|
+
required: ["taxonomy", "name"],
|
|
1813
|
+
additionalProperties: false
|
|
1814
|
+
},
|
|
1815
|
+
async run(args, h) {
|
|
1816
|
+
if (args.taxonomy === "tags" && args.parent !== void 0) throw new ToolFailure("parent is for categories only. Nothing was sent.");
|
|
1817
|
+
try {
|
|
1818
|
+
const { data } = await rest(h, `/wp/v2/${args.taxonomy}`, {
|
|
1819
|
+
method: "POST",
|
|
1820
|
+
json: compact({ name: args.name, slug: args.slug, parent: args.parent, description: args.description }),
|
|
1821
|
+
write: true
|
|
1822
|
+
});
|
|
1823
|
+
return { ...trimTerm(data), existing: false };
|
|
1824
|
+
} catch (error) {
|
|
1825
|
+
if (!(error instanceof ToolFailure) || error.details.vendorCode !== "term_exists") throw error;
|
|
1826
|
+
}
|
|
1827
|
+
const existing = await findTerm(h, args.taxonomy, args.name, args.slug, args.taxonomy === "categories" ? args.parent ?? 0 : void 0);
|
|
1828
|
+
if (!existing) {
|
|
1829
|
+
throw new ToolFailure(`WordPress says this ${args.taxonomy === "tags" ? "tag" : "category"} already exists, but it was not found by name: look for it with list_terms. Nothing was changed.`);
|
|
1830
|
+
}
|
|
1831
|
+
return { ...trimTerm(existing), existing: true };
|
|
1832
|
+
}
|
|
1833
|
+
},
|
|
1834
|
+
{
|
|
1835
|
+
name: "set_seo_meta",
|
|
1836
|
+
kind: "update",
|
|
1837
|
+
check: "get_post",
|
|
1838
|
+
title: "Set a WordPress post's SEO title, description and focus keyword",
|
|
1839
|
+
description: "Writes the SEO title, meta description and focus keyword of a post or page through the Rank Math SEO plugin's own API, the way its editor saves them. When the site does not run Rank Math (or its API), nothing is written and the result says so with applied: false; that is not an error. Only the fields given change.",
|
|
1840
|
+
inputSchema: {
|
|
1841
|
+
type: "object",
|
|
1842
|
+
properties: {
|
|
1843
|
+
post_id: { type: "integer", minimum: 1, description: "The post or page id." },
|
|
1844
|
+
focus_keyword: {
|
|
1845
|
+
type: "string",
|
|
1846
|
+
minLength: 1,
|
|
1847
|
+
maxLength: 300,
|
|
1848
|
+
description: 'The focus keyword; several as one comma-separated text, the main one first ("main keyword,second term").'
|
|
1849
|
+
},
|
|
1850
|
+
seo_title: { type: "string", minLength: 1, maxLength: 300, description: "The title for search results." },
|
|
1851
|
+
meta_description: { type: "string", minLength: 1, maxLength: 1e3, description: "The meta description for search results (about 120 to 160 characters)." }
|
|
1852
|
+
},
|
|
1853
|
+
required: ["post_id"],
|
|
1854
|
+
additionalProperties: false
|
|
1855
|
+
},
|
|
1856
|
+
async run(args, h) {
|
|
1857
|
+
const meta = compact({
|
|
1858
|
+
rank_math_focus_keyword: args.focus_keyword,
|
|
1859
|
+
rank_math_title: args.seo_title,
|
|
1860
|
+
rank_math_description: args.meta_description
|
|
1861
|
+
});
|
|
1862
|
+
if (!Object.keys(meta).length) throw new ToolFailure("Nothing to set: give focus_keyword, seo_title or meta_description. Nothing was sent.");
|
|
1863
|
+
const skipped = (reason) => ({ applied: false, post_id: args.post_id, reason });
|
|
1864
|
+
try {
|
|
1865
|
+
await rest(h, "/rankmath/v1", { query: { _fields: "namespace" } });
|
|
1866
|
+
} catch (error) {
|
|
1867
|
+
if (error instanceof ToolFailure && error.details.status === 404) return skipped("The site does not run the Rank Math SEO plugin (its API is not there), so nothing was written.");
|
|
1868
|
+
throw error;
|
|
1869
|
+
}
|
|
1870
|
+
try {
|
|
1871
|
+
await rest(h, "/rankmath/v1/updateMeta", {
|
|
1872
|
+
method: "POST",
|
|
1873
|
+
json: { objectType: "post", objectID: args.post_id, meta },
|
|
1874
|
+
write: true
|
|
1875
|
+
});
|
|
1876
|
+
} catch (error) {
|
|
1877
|
+
if (error instanceof ToolFailure && error.details.status === 404 && error.details.vendorCode === "rest_no_route") {
|
|
1878
|
+
return skipped("The site's Rank Math version has no API for saving SEO fields, so nothing was written.");
|
|
1879
|
+
}
|
|
1880
|
+
throw error;
|
|
1881
|
+
}
|
|
1882
|
+
return { applied: true, post_id: args.post_id, fields: Object.keys(meta) };
|
|
1883
|
+
}
|
|
1884
|
+
},
|
|
1885
|
+
// The rest of the REST API: comments, revisions, pages' templates, plugin routes, and more.
|
|
1886
|
+
...apiTools({
|
|
1887
|
+
label: "WordPress",
|
|
1888
|
+
description: "The REST API of the connected WordPress site, as the connected user: a path is a REST route after /wp-json, such as /wp/v2/comments, /wp/v2/posts/12/revisions, /wp/v2/media/34 or a plugin's own namespace; _fields and context=edit go in query; bodies are JSON (json, or body with a JSON content_type). DELETE moves posts to the trash unless force is true. Application passwords, plugins, themes, users, site settings and batch requests are out of reach. Reference: https://developer.wordpress.org/rest-api/reference/.",
|
|
1889
|
+
guard: restGuard,
|
|
1890
|
+
send: async (request, h) => {
|
|
1891
|
+
if (!isJsonBody(request)) {
|
|
1892
|
+
refuseRequest("The body must be JSON: give it as json, or as body with a JSON content_type. A form body is refused, since WordPress could read a route from it.");
|
|
1893
|
+
}
|
|
1894
|
+
try {
|
|
1895
|
+
return await h.api({ ...request, origin: h.originOf("url"), path: `${installPath(h.credentials["url"])}/wp-json${request.path}` });
|
|
1896
|
+
} catch (error) {
|
|
1897
|
+
throw withHint(error);
|
|
1898
|
+
}
|
|
1899
|
+
},
|
|
1900
|
+
responseHeaders: ["x-wp-total", "x-wp-totalpages"]
|
|
1901
|
+
})
|
|
1902
|
+
]
|
|
1903
|
+
});
|
|
1904
|
+
module.exports = connector;
|