@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +1185 -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 +12 -1
|
@@ -0,0 +1,2375 @@
|
|
|
1
|
+
/* meta-ads connector module (MIT License). Built from src/vendors/meta-ads; 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/meta-ads/graph.ts
|
|
1091
|
+
var VERSION = "v26.0";
|
|
1092
|
+
function compact(value) {
|
|
1093
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
|
|
1094
|
+
}
|
|
1095
|
+
function tokenOf(credentials) {
|
|
1096
|
+
return credentials["systemusertoken"] || credentials["access_token"] || "";
|
|
1097
|
+
}
|
|
1098
|
+
var PROOF = /^[0-9a-f]{64}$/i;
|
|
1099
|
+
function proofQuery(credentials) {
|
|
1100
|
+
const proof = credentials["appsecret_proof"];
|
|
1101
|
+
return credentials["access_token"] && !credentials["systemusertoken"] && proof && PROOF.test(proof) ? { appsecret_proof: proof } : {};
|
|
1102
|
+
}
|
|
1103
|
+
function pickAccount(h, key, given, words) {
|
|
1104
|
+
if (given) {
|
|
1105
|
+
requireAccounts(h.ctx.accounts, key, given, words.label);
|
|
1106
|
+
return given;
|
|
1107
|
+
}
|
|
1108
|
+
const allowed = allowedAccounts(h.ctx.accounts, key);
|
|
1109
|
+
if (allowed && allowed.length === 1) return allowed[0];
|
|
1110
|
+
if (allowed && allowed.length > 1) throw new ToolFailure(`${words.argument} is required: one of ${allowed.join(", ")}. Nothing was sent.`);
|
|
1111
|
+
if (allowed) throw new ToolFailure(`No ${words.label} is chosen for this connection yet. Nothing was sent.`);
|
|
1112
|
+
throw new ToolFailure(`${words.argument} is required. Nothing was sent.`);
|
|
1113
|
+
}
|
|
1114
|
+
function listState(h, cursor, limit) {
|
|
1115
|
+
const state = h.cursor(cursor);
|
|
1116
|
+
return {
|
|
1117
|
+
...typeof state?.["a"] === "string" ? { after: state["a"] } : {},
|
|
1118
|
+
skip: typeof state?.["o"] === "number" ? state["o"] : 0,
|
|
1119
|
+
limit: typeof state?.["n"] === "number" ? state["n"] : limit
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
function rowsOf(data) {
|
|
1123
|
+
return Array.isArray(data?.data) ? data.data : [];
|
|
1124
|
+
}
|
|
1125
|
+
function listResult(h, key, items, state, data, extra) {
|
|
1126
|
+
const after = data?.paging?.cursors?.after;
|
|
1127
|
+
const next = data?.paging?.next && typeof after === "string" && after ? after : void 0;
|
|
1128
|
+
return h.page({
|
|
1129
|
+
key,
|
|
1130
|
+
items: items.slice(state.skip),
|
|
1131
|
+
...extra ? { extra } : {},
|
|
1132
|
+
resumeAt: (index) => h.makeCursor({ ...state.after ? { a: state.after } : {}, o: state.skip + index, n: state.limit }),
|
|
1133
|
+
...next ? { nextPage: h.makeCursor({ a: next, o: 0, n: state.limit }) } : {}
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
function sleep(ms, signal) {
|
|
1137
|
+
return new Promise((resolve, reject) => {
|
|
1138
|
+
if (signal?.aborted) {
|
|
1139
|
+
reject(new ToolFailure("The call was cancelled while waiting."));
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
const stop = () => {
|
|
1143
|
+
clearTimeout(timer);
|
|
1144
|
+
reject(new ToolFailure("The call was cancelled while waiting."));
|
|
1145
|
+
};
|
|
1146
|
+
const timer = setTimeout(() => {
|
|
1147
|
+
signal?.removeEventListener("abort", stop);
|
|
1148
|
+
resolve();
|
|
1149
|
+
}, ms);
|
|
1150
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1153
|
+
function refuseSecrets(request) {
|
|
1154
|
+
const texts = [...request.segments, ...Object.keys(request.query), ...Object.values(request.query).flat()];
|
|
1155
|
+
if (request.segments.includes("oauth") || texts.some((text) => /access_token|appsecret|app_secret|client_secret|debug_token/i.test(text))) {
|
|
1156
|
+
throw new ToolFailure("Tokens and app secrets are not available through the generic Meta Ads tools, and the connection's own token is added for you. Nothing was sent.");
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
function base64(bytes) {
|
|
1160
|
+
let binary = "";
|
|
1161
|
+
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
|
|
1162
|
+
return btoa(binary);
|
|
1163
|
+
}
|
|
1164
|
+
function imageType(bytes) {
|
|
1165
|
+
if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
|
|
1166
|
+
if (bytes.length >= 8 && [137, 80, 78, 71, 13, 10, 26, 10].every((value, index) => bytes[index] === value)) return "image/png";
|
|
1167
|
+
if (bytes.length >= 6 && String.fromCharCode(...bytes.subarray(0, 6)).startsWith("GIF8")) return "image/gif";
|
|
1168
|
+
return void 0;
|
|
1169
|
+
}
|
|
1170
|
+
var HTTPS_URL = { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3 };
|
|
1171
|
+
var ISO_TIME_PATTERN = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})$";
|
|
1172
|
+
var DATE_PATTERN = "^\\d{4}-\\d{2}-\\d{2}$";
|
|
1173
|
+
|
|
1174
|
+
// src/vendors/meta-ads/graph-rules.ts
|
|
1175
|
+
var RateLimited = class extends ToolFailure {
|
|
1176
|
+
};
|
|
1177
|
+
var THROTTLE_CODE = /\(#(?:4|17|32|613|800(?:0\d|1[0-4]))\)/;
|
|
1178
|
+
var THROTTLE_TEXT = /request limit reached|too many calls|exceeded the rate limit/i;
|
|
1179
|
+
var NOTHING_CHANGED = " Nothing was changed.";
|
|
1180
|
+
function rateLimited(error, label) {
|
|
1181
|
+
if (!(error instanceof ToolFailure) || error instanceof RateLimited) return error;
|
|
1182
|
+
const { status } = error.details;
|
|
1183
|
+
if (status !== 400 && status !== 403) return error;
|
|
1184
|
+
const { message } = error;
|
|
1185
|
+
if (!THROTTLE_CODE.test(message) && !THROTTLE_TEXT.test(message)) return error;
|
|
1186
|
+
const unchanged = message.endsWith(NOTHING_CHANGED);
|
|
1187
|
+
const body = unchanged ? message.slice(0, -NOTHING_CHANGED.length) : message;
|
|
1188
|
+
const words = (/\(HTTP \d{3}\): (.+)\.$/s.exec(body)?.[1] ?? / said: "(.+)"\.$/s.exec(body)?.[1])?.replace(/[.!?。]+$/u, "");
|
|
1189
|
+
return new RateLimited(
|
|
1190
|
+
`${label} rate limit reached (HTTP ${status})${words ? `: ${words}` : ""}.${unchanged ? NOTHING_CHANGED : ""} Wait a while before trying again: the limit counts calls over a rolling hour.`,
|
|
1191
|
+
error.details
|
|
1192
|
+
);
|
|
1193
|
+
}
|
|
1194
|
+
function withRateLimits(tools, label) {
|
|
1195
|
+
return tools.map((tool) => ({
|
|
1196
|
+
...tool,
|
|
1197
|
+
run: (args, h) => tool.run(args, {
|
|
1198
|
+
...h,
|
|
1199
|
+
api: (request) => h.api(request).catch((error) => {
|
|
1200
|
+
throw rateLimited(error, label);
|
|
1201
|
+
})
|
|
1202
|
+
})
|
|
1203
|
+
}));
|
|
1204
|
+
}
|
|
1205
|
+
var MAX_DEPTH = 32;
|
|
1206
|
+
var SECRET = /access_token|appsecret|app_secret|client_secret|debug_token/i;
|
|
1207
|
+
var OVERRIDES = ["batch", "method"];
|
|
1208
|
+
function nothingSent2(sentence) {
|
|
1209
|
+
return new ToolFailure(`${sentence} Nothing was sent.`);
|
|
1210
|
+
}
|
|
1211
|
+
function isRecord(value) {
|
|
1212
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1213
|
+
}
|
|
1214
|
+
function decodings(text) {
|
|
1215
|
+
const forms = [text];
|
|
1216
|
+
let current = text;
|
|
1217
|
+
for (let round = 0; round < 3; round += 1) {
|
|
1218
|
+
let next;
|
|
1219
|
+
try {
|
|
1220
|
+
next = decodeURIComponent(current.replace(/\+/g, " "));
|
|
1221
|
+
} catch {
|
|
1222
|
+
break;
|
|
1223
|
+
}
|
|
1224
|
+
if (next === current) break;
|
|
1225
|
+
forms.push(next);
|
|
1226
|
+
current = next;
|
|
1227
|
+
}
|
|
1228
|
+
return forms;
|
|
1229
|
+
}
|
|
1230
|
+
function parsedValue(value) {
|
|
1231
|
+
if (typeof value !== "string" || !/^\s*[[{]/.test(value)) return value;
|
|
1232
|
+
try {
|
|
1233
|
+
return JSON.parse(value);
|
|
1234
|
+
} catch {
|
|
1235
|
+
return value;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
function collect(value, into, depth) {
|
|
1239
|
+
if (depth > MAX_DEPTH) throw nothingSent2("The request is nested too deeply.");
|
|
1240
|
+
if (typeof value === "string") {
|
|
1241
|
+
into.push(...decodings(value));
|
|
1242
|
+
const inner = parsedValue(value);
|
|
1243
|
+
if (inner !== value) collect(inner, into, depth + 1);
|
|
1244
|
+
} else if (typeof value === "number" || typeof value === "boolean") {
|
|
1245
|
+
into.push(String(value));
|
|
1246
|
+
} else if (Array.isArray(value)) {
|
|
1247
|
+
for (const item of value) collect(item, into, depth + 1);
|
|
1248
|
+
} else if (isRecord(value)) {
|
|
1249
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1250
|
+
into.push(...decodings(key));
|
|
1251
|
+
collect(item, into, depth + 1);
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
function queryParams(query) {
|
|
1256
|
+
if (!isRecord(query)) return [];
|
|
1257
|
+
const params = [];
|
|
1258
|
+
for (const [name2, value] of Object.entries(query)) {
|
|
1259
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
1260
|
+
if (item !== void 0 && item !== null) params.push({ name: name2, value: parsedValue(item) });
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
return params;
|
|
1264
|
+
}
|
|
1265
|
+
function bodyParams(args, label) {
|
|
1266
|
+
const entries = (record) => Object.entries(record).map(([name2, value]) => ({ name: name2, value: parsedValue(value) }));
|
|
1267
|
+
if (args.json !== void 0 && args.body !== void 0) throw nothingSent2("Give json or body, not both.");
|
|
1268
|
+
if (args.json !== void 0) return isRecord(args.json) ? entries(args.json) : [];
|
|
1269
|
+
if (typeof args.body !== "string") return [];
|
|
1270
|
+
const type = typeof args.content_type === "string" ? args.content_type.trim().toLowerCase() : "";
|
|
1271
|
+
if (!type) throw nothingSent2('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
|
|
1272
|
+
if (/^application\/x-www-form-urlencoded\b/.test(type)) {
|
|
1273
|
+
return [...new URLSearchParams(args.body)].map(([name2, value]) => ({ name: name2, value: parsedValue(value) }));
|
|
1274
|
+
}
|
|
1275
|
+
if (/^application\/(?:[a-z0-9.+-]+\+)?json\b/.test(type)) {
|
|
1276
|
+
let data;
|
|
1277
|
+
try {
|
|
1278
|
+
data = JSON.parse(args.body);
|
|
1279
|
+
} catch {
|
|
1280
|
+
throw nothingSent2("body is not valid JSON.");
|
|
1281
|
+
}
|
|
1282
|
+
if (!isRecord(data)) throw nothingSent2("A JSON body must be an object of parameters.");
|
|
1283
|
+
return entries(data);
|
|
1284
|
+
}
|
|
1285
|
+
throw nothingSent2(`The generic ${label} tools send parameters as a JSON object (json) or as a form (body, with content_type application/x-www-form-urlencoded).`);
|
|
1286
|
+
}
|
|
1287
|
+
function readGraphRequest(args, label) {
|
|
1288
|
+
const path = typeof args.path === "string" ? args.path : "";
|
|
1289
|
+
const segments = path.split("/").filter((segment) => segment !== "").flatMap(decodings);
|
|
1290
|
+
const params = [...queryParams(args.query), ...bodyParams(args, label)];
|
|
1291
|
+
const texts = [...segments];
|
|
1292
|
+
const fields = [];
|
|
1293
|
+
for (const { name: name2, value } of params) {
|
|
1294
|
+
texts.push(...decodings(name2));
|
|
1295
|
+
collect(value, texts, 0);
|
|
1296
|
+
if (name2.trim().toLowerCase() === "fields") collect(value, fields, 0);
|
|
1297
|
+
}
|
|
1298
|
+
return { segments, params, fields, texts };
|
|
1299
|
+
}
|
|
1300
|
+
function refuseUnsafe(parts, label) {
|
|
1301
|
+
const override = OVERRIDES.find((name2) => parts.params.some((param) => param.name.trim().toLowerCase() === name2));
|
|
1302
|
+
if (override) {
|
|
1303
|
+
throw nothingSent2(`The ${override} parameter is not available through the generic ${label} tools: send one request at a time, with api_get to read and api_request to change.`);
|
|
1304
|
+
}
|
|
1305
|
+
if (parts.segments.some((segment) => segment.toLowerCase() === "oauth") || parts.texts.some((text) => SECRET.test(text))) {
|
|
1306
|
+
throw nothingSent2(`Tokens and app secrets are not available through the generic ${label} tools, and the connection's own token is added for you.`);
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
var SECRET_KEY = /^(?:access_token|appsecret_proof)$/i;
|
|
1310
|
+
var SECRET_URL_PARAM = /([?&](?:access_token|appsecret_proof)=)[^&#\s"'\\]*/gi;
|
|
1311
|
+
var SECRET_JSON_VALUE = /(\\*")(access_token|appsecret_proof)\1\s*:\s*\1[^"\\]*\1/gi;
|
|
1312
|
+
function withoutSecrets(value, depth = 0) {
|
|
1313
|
+
if (depth > 64) return null;
|
|
1314
|
+
if (typeof value === "string") return value.replace(SECRET_URL_PARAM, "$1hidden").replace(SECRET_JSON_VALUE, "$1$2$1:$1hidden$1");
|
|
1315
|
+
if (Array.isArray(value)) return value.map((item) => withoutSecrets(item, depth + 1));
|
|
1316
|
+
if (isRecord(value)) {
|
|
1317
|
+
const clean = {};
|
|
1318
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1319
|
+
if (!SECRET_KEY.test(key)) clean[key] = withoutSecrets(item, depth + 1);
|
|
1320
|
+
}
|
|
1321
|
+
return clean;
|
|
1322
|
+
}
|
|
1323
|
+
return value;
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
// src/vendors/meta-ads/index.ts
|
|
1327
|
+
var AD_ACCOUNT = { argument: "ad_account_id", label: "ad account" };
|
|
1328
|
+
var AD_ACCOUNT_ID = {
|
|
1329
|
+
type: "string",
|
|
1330
|
+
pattern: "^(act_)?[0-9]{1,30}$",
|
|
1331
|
+
description: "The ad account id, with or without act_, from list_ad_accounts. Leave it out when only one ad account is chosen for this connection."
|
|
1332
|
+
};
|
|
1333
|
+
var OBJECT_ID = { type: "string", pattern: "^[0-9]{1,30}$", description: "A campaign, ad set or ad id." };
|
|
1334
|
+
var MONEY = { type: "integer", minimum: 1, maximum: 1e12, description: "In the minor unit of the account's currency: 5000 is 50.00 USD." };
|
|
1335
|
+
var TIME = { type: "string", pattern: ISO_TIME_PATTERN, description: "A date and time with its offset, such as 2026-12-01T09:00:00+0000." };
|
|
1336
|
+
var TARGETING = {
|
|
1337
|
+
type: "object",
|
|
1338
|
+
description: 'A Meta targeting spec, such as {"geo_locations": {"countries": ["US"]}, "age_min": 25, "age_max": 54, "flexible_spec": [{"interests": [{"id": "6003139266461"}]}], "publisher_platforms": ["facebook", "instagram"]}. Omit the placement fields for automatic placements; never use explore in instagram_positions.'
|
|
1339
|
+
};
|
|
1340
|
+
var STATUS_FILTER = {
|
|
1341
|
+
type: "array",
|
|
1342
|
+
items: {
|
|
1343
|
+
type: "string",
|
|
1344
|
+
enum: ["ACTIVE", "PAUSED", "DELETED", "PENDING_REVIEW", "DISAPPROVED", "PREAPPROVED", "PENDING_BILLING_INFO", "CAMPAIGN_PAUSED", "ARCHIVED", "ADSET_PAUSED", "IN_PROCESS", "WITH_ISSUES"]
|
|
1345
|
+
},
|
|
1346
|
+
minItems: 1,
|
|
1347
|
+
uniqueItems: true,
|
|
1348
|
+
description: 'Only items with these effective statuses, e.g. ["ACTIVE", "PAUSED"].'
|
|
1349
|
+
};
|
|
1350
|
+
var ACCOUNT_STATUS = {
|
|
1351
|
+
1: "ACTIVE",
|
|
1352
|
+
2: "DISABLED",
|
|
1353
|
+
3: "UNSETTLED",
|
|
1354
|
+
7: "PENDING_RISK_REVIEW",
|
|
1355
|
+
8: "PENDING_SETTLEMENT",
|
|
1356
|
+
9: "IN_GRACE_PERIOD",
|
|
1357
|
+
100: "PENDING_CLOSURE",
|
|
1358
|
+
101: "CLOSED",
|
|
1359
|
+
201: "ANY_ACTIVE",
|
|
1360
|
+
202: "ANY_CLOSED"
|
|
1361
|
+
};
|
|
1362
|
+
var OBJECT_TYPES = ["campaign", "ad_set", "ad", "creative"];
|
|
1363
|
+
var OBJECTS = {
|
|
1364
|
+
campaign: {
|
|
1365
|
+
edge: "campaigns",
|
|
1366
|
+
fields: "id,name,status,effective_status,objective,daily_budget,lifetime_budget,budget_remaining,bid_strategy,special_ad_categories,start_time,stop_time,created_time"
|
|
1367
|
+
},
|
|
1368
|
+
ad_set: {
|
|
1369
|
+
edge: "adsets",
|
|
1370
|
+
fields: "id,name,status,effective_status,campaign_id,daily_budget,lifetime_budget,budget_remaining,bid_amount,bid_strategy,optimization_goal,billing_event,start_time,end_time,targeting,promoted_object,destination_type"
|
|
1371
|
+
},
|
|
1372
|
+
ad: { edge: "ads", fields: "id,name,status,effective_status,campaign_id,adset_id,creative{id,name},created_time,updated_time" },
|
|
1373
|
+
creative: { edge: "adcreatives", fields: "id,name,status,object_story_spec,thumbnail_url,image_hash,video_id,call_to_action_type" }
|
|
1374
|
+
};
|
|
1375
|
+
var DEFAULT_INSIGHT_FIELDS = {
|
|
1376
|
+
account: ["spend", "impressions", "reach", "clicks", "ctr", "cpc", "cpm", "frequency", "actions", "cost_per_action_type", "purchase_roas"],
|
|
1377
|
+
campaign: ["campaign_id", "campaign_name", "spend", "impressions", "reach", "clicks", "ctr", "cpc", "cpm", "frequency", "actions", "cost_per_action_type", "purchase_roas"],
|
|
1378
|
+
adset: ["adset_id", "adset_name", "campaign_name", "spend", "impressions", "clicks", "ctr", "cpc", "actions", "cost_per_action_type"],
|
|
1379
|
+
ad: ["ad_id", "ad_name", "adset_name", "campaign_name", "spend", "impressions", "clicks", "ctr", "cpc", "actions", "cost_per_action_type", "quality_ranking", "engagement_rate_ranking", "conversion_rate_ranking"]
|
|
1380
|
+
};
|
|
1381
|
+
var DATE_PRESETS = [
|
|
1382
|
+
"today",
|
|
1383
|
+
"yesterday",
|
|
1384
|
+
"this_month",
|
|
1385
|
+
"last_month",
|
|
1386
|
+
"this_quarter",
|
|
1387
|
+
"last_quarter",
|
|
1388
|
+
"this_year",
|
|
1389
|
+
"last_year",
|
|
1390
|
+
"last_3d",
|
|
1391
|
+
"last_7d",
|
|
1392
|
+
"last_14d",
|
|
1393
|
+
"last_28d",
|
|
1394
|
+
"last_30d",
|
|
1395
|
+
"last_90d",
|
|
1396
|
+
"last_week_mon_sun",
|
|
1397
|
+
"last_week_sun_sat",
|
|
1398
|
+
"this_week_mon_today",
|
|
1399
|
+
"this_week_sun_today",
|
|
1400
|
+
"maximum"
|
|
1401
|
+
];
|
|
1402
|
+
var BREAKDOWNS = [
|
|
1403
|
+
"age",
|
|
1404
|
+
"gender",
|
|
1405
|
+
"country",
|
|
1406
|
+
"region",
|
|
1407
|
+
"dma",
|
|
1408
|
+
"device_platform",
|
|
1409
|
+
"publisher_platform",
|
|
1410
|
+
"platform_position",
|
|
1411
|
+
"impression_device",
|
|
1412
|
+
"hourly_stats_aggregated_by_advertiser_time_zone",
|
|
1413
|
+
"hourly_stats_aggregated_by_audience_time_zone",
|
|
1414
|
+
"frequency_value"
|
|
1415
|
+
];
|
|
1416
|
+
var POLL_MS = 3e3;
|
|
1417
|
+
function graph(h, request) {
|
|
1418
|
+
return h.api({ ...request, query: { ...request.query, ...proofQuery(h.credentials) } });
|
|
1419
|
+
}
|
|
1420
|
+
function adAccountOf(h, given) {
|
|
1421
|
+
return pickAccount(h, "ad_accounts", given?.replace(/^act_/, ""), AD_ACCOUNT);
|
|
1422
|
+
}
|
|
1423
|
+
function mappedPages(credentials, adAccountId) {
|
|
1424
|
+
let mappings;
|
|
1425
|
+
try {
|
|
1426
|
+
mappings = JSON.parse(credentials["pagemappings"] ?? "[]");
|
|
1427
|
+
} catch {
|
|
1428
|
+
return [];
|
|
1429
|
+
}
|
|
1430
|
+
if (!Array.isArray(mappings)) return [];
|
|
1431
|
+
return [...new Set(mappings.filter((item) => item && typeof item === "object" && (!adAccountId || String(item.adaccountid ?? "").replace(/^act_/, "") === adAccountId)).map((item) => String(item.pageid ?? "")).filter((id) => /^[0-9]{1,30}$/.test(id)))];
|
|
1432
|
+
}
|
|
1433
|
+
function allowedPages(h, adAccountId) {
|
|
1434
|
+
const accounts = h.ctx.accounts;
|
|
1435
|
+
if (accounts === null) return null;
|
|
1436
|
+
if (accounts && Array.isArray(accounts["pages"])) return accounts["pages"].map(String);
|
|
1437
|
+
return mappedPages(h.credentials, adAccountId);
|
|
1438
|
+
}
|
|
1439
|
+
var PAGE_KEYS = /* @__PURE__ */ new Set(["page_id", "actor_id"]);
|
|
1440
|
+
var STORY_KEYS = /* @__PURE__ */ new Set(["object_story_id", "effective_object_story_id"]);
|
|
1441
|
+
function pageIdsIn(value, into, depth = 0) {
|
|
1442
|
+
if (depth > 32) return;
|
|
1443
|
+
if (typeof value === "string") {
|
|
1444
|
+
if (!/^\s*[[{]/.test(value)) return;
|
|
1445
|
+
try {
|
|
1446
|
+
pageIdsIn(JSON.parse(value), into, depth + 1);
|
|
1447
|
+
} catch {
|
|
1448
|
+
}
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
if (Array.isArray(value)) {
|
|
1452
|
+
for (const item of value) pageIdsIn(item, into, depth + 1);
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
if (typeof value !== "object" || value === null) return;
|
|
1456
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1457
|
+
const name2 = key.trim().toLowerCase();
|
|
1458
|
+
if (PAGE_KEYS.has(name2) && (typeof item === "string" || typeof item === "number")) into.add(String(item).trim());
|
|
1459
|
+
else if (STORY_KEYS.has(name2) && typeof item === "string") into.add(item.trim().split("_")[0] ?? "");
|
|
1460
|
+
else pageIdsIn(item, into, depth + 1);
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
function requirePages(h, values, adAccountId) {
|
|
1464
|
+
const allowed = allowedPages(h, adAccountId);
|
|
1465
|
+
if (allowed === null) return;
|
|
1466
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1467
|
+
for (const value of values) pageIdsIn(value, ids);
|
|
1468
|
+
const refused = [...ids].filter((id) => !allowed.includes(id)).map((id) => truncate(id, 40));
|
|
1469
|
+
if (!refused.length) return;
|
|
1470
|
+
throw new ToolFailure(
|
|
1471
|
+
`The Page ${refused.join(", ")} ${refused.length > 1 ? "are" : "is"} not among the Pages chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : "No Page is chosen for it yet.") + " Nothing was sent."
|
|
1472
|
+
);
|
|
1473
|
+
}
|
|
1474
|
+
function choosePage(h, given, adAccountId) {
|
|
1475
|
+
const allowed = allowedPages(h, adAccountId);
|
|
1476
|
+
if (given) {
|
|
1477
|
+
if (allowed && !allowed.includes(given)) {
|
|
1478
|
+
throw new ToolFailure(
|
|
1479
|
+
`The Page ${given} is not among the Pages chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : "No Page is chosen for it yet.") + " Nothing was sent."
|
|
1480
|
+
);
|
|
1481
|
+
}
|
|
1482
|
+
return given;
|
|
1483
|
+
}
|
|
1484
|
+
if (allowed && allowed.length === 1) return allowed[0];
|
|
1485
|
+
if (allowed && allowed.length > 1) throw new ToolFailure(`page_id is required: one of ${allowed.join(", ")}. Nothing was sent.`);
|
|
1486
|
+
if (allowed) throw new ToolFailure("No Page is chosen for this connection yet, and a creative needs one. Nothing was sent.");
|
|
1487
|
+
throw new ToolFailure("page_id is required. Nothing was sent.");
|
|
1488
|
+
}
|
|
1489
|
+
async function objectInAccount(h, id, fields) {
|
|
1490
|
+
const { data } = await graph(h, { path: `/${VERSION}/${id}`, query: { fields: `${fields},account_id` } });
|
|
1491
|
+
const account = String(data?.account_id ?? "").replace(/^act_/, "");
|
|
1492
|
+
if (!account) throw new ToolFailure(`Meta Ads did not say which ad account ${id} belongs to. Nothing was changed.`);
|
|
1493
|
+
requireAccounts(h.ctx.accounts, "ad_accounts", account, "ad account");
|
|
1494
|
+
return data;
|
|
1495
|
+
}
|
|
1496
|
+
function trimAccount(account) {
|
|
1497
|
+
const tasks = Array.isArray(account?.user_tasks) ? account.user_tasks : [];
|
|
1498
|
+
return compact({
|
|
1499
|
+
id: account?.account_id ?? String(account?.id ?? "").replace(/^act_/, ""),
|
|
1500
|
+
name: account?.name,
|
|
1501
|
+
status: ACCOUNT_STATUS[account?.account_status] ?? account?.account_status,
|
|
1502
|
+
currency: account?.currency,
|
|
1503
|
+
timezone: account?.timezone_name,
|
|
1504
|
+
tasks: tasks.length ? tasks : void 0,
|
|
1505
|
+
can_manage: tasks.length ? tasks.includes("ADVERTISE") && tasks.includes("ANALYZE") : void 0
|
|
1506
|
+
});
|
|
1507
|
+
}
|
|
1508
|
+
function checkPlacements(targeting) {
|
|
1509
|
+
if (Array.isArray(targeting?.instagram_positions) && targeting.instagram_positions.includes("explore")) {
|
|
1510
|
+
throw new ToolFailure("Meta removed the Instagram explore placement: take explore out of instagram_positions. Nothing was sent.");
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
var LEAD_WORDS = /(?<![a-z0-9_])(?:leads|leadgen_forms|field_data)(?![a-z0-9_])/i;
|
|
1514
|
+
var USER_PAGE_WORDS = /(?<![a-z0-9_])accounts(?![a-z0-9_])/i;
|
|
1515
|
+
var OTHER_ACCOUNT_WORDS = new RegExp(
|
|
1516
|
+
"(?<![a-z0-9_])(?:business|businesses|owned_businesses|client_businesses|agencies|adaccounts|ad_accounts|owned_ad_accounts|client_ad_accounts|pending_owned_ad_accounts|pending_client_ad_accounts|assigned_ad_accounts|shared_accounts)(?![a-z0-9_])",
|
|
1517
|
+
"i"
|
|
1518
|
+
);
|
|
1519
|
+
function refuseOutOfReach(parts, h) {
|
|
1520
|
+
const selection = [...parts.segments, ...parts.fields];
|
|
1521
|
+
if (selection.some((text) => LEAD_WORDS.test(text))) {
|
|
1522
|
+
throw new ToolFailure("Lead forms and lead data are not available on this connection. Nothing was sent.");
|
|
1523
|
+
}
|
|
1524
|
+
if (selection.some((text) => USER_PAGE_WORDS.test(text))) {
|
|
1525
|
+
throw new ToolFailure("The accounts edge (Pages with their tokens) is not available through the generic Meta Ads tools: list_pages lists the Pages. Nothing was sent.");
|
|
1526
|
+
}
|
|
1527
|
+
if (allowedAccounts(h.ctx.accounts, "ad_accounts") === null) return;
|
|
1528
|
+
if (selection.some((text) => OTHER_ACCOUNT_WORDS.test(text)) || parts.params.some(({ name: name2 }) => name2.trim().toLowerCase() === "ids")) {
|
|
1529
|
+
throw new ToolFailure(
|
|
1530
|
+
"With ad accounts chosen for this connection, the generic Meta Ads tools stay inside them: businesses, agencies, other ad accounts and lookups by ids are not available. Nothing was sent."
|
|
1531
|
+
);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
async function adAccountLock(request, h) {
|
|
1535
|
+
if (allowedAccounts(h.ctx.accounts, "ad_accounts") === null) return;
|
|
1536
|
+
const named = request.segments.filter((segment) => /^act_[0-9]{1,30}$/.test(segment)).map((segment) => segment.slice(4));
|
|
1537
|
+
if (named.length) {
|
|
1538
|
+
requireAccounts(h.ctx.accounts, "ad_accounts", named, "ad account");
|
|
1539
|
+
return;
|
|
1540
|
+
}
|
|
1541
|
+
const first = request.segments[1];
|
|
1542
|
+
if (request.method === "GET" && first === "search") return;
|
|
1543
|
+
if (first && /^[0-9]{1,30}$/.test(first)) {
|
|
1544
|
+
try {
|
|
1545
|
+
await objectInAccount(h, first, "id");
|
|
1546
|
+
} catch (error) {
|
|
1547
|
+
if (error instanceof ToolFailure && error.details.status) {
|
|
1548
|
+
throw new ToolFailure(`${first} could not be matched to an ad account chosen for this connection: ${error.message}`, error.details);
|
|
1549
|
+
}
|
|
1550
|
+
throw error;
|
|
1551
|
+
}
|
|
1552
|
+
return;
|
|
1553
|
+
}
|
|
1554
|
+
throw new ToolFailure(
|
|
1555
|
+
"With ad accounts chosen for this connection, a path must name one of them (act_<id>) or one of their campaigns, ad sets, ads, creatives or audiences. Nothing was sent."
|
|
1556
|
+
);
|
|
1557
|
+
}
|
|
1558
|
+
function objectStory(args) {
|
|
1559
|
+
const cta = (type, link) => type ? compact({ type, value: link ? { link } : void 0 }) : void 0;
|
|
1560
|
+
if (args.format === "video") {
|
|
1561
|
+
if (!args.video_id) throw new ToolFailure("A video creative needs video_id (from upload_video). Nothing was sent.");
|
|
1562
|
+
return {
|
|
1563
|
+
video_data: compact({
|
|
1564
|
+
video_id: args.video_id,
|
|
1565
|
+
message: args.message,
|
|
1566
|
+
title: args.headline,
|
|
1567
|
+
link_description: args.description,
|
|
1568
|
+
image_url: args.thumbnail_url,
|
|
1569
|
+
image_hash: args.image_hash,
|
|
1570
|
+
call_to_action: cta(args.call_to_action_type ?? (args.link || args.call_to_action_link ? "LEARN_MORE" : void 0), args.call_to_action_link ?? args.link)
|
|
1571
|
+
})
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
if (!args.link) throw new ToolFailure(`An ${args.format} creative needs link, the page people go to. Nothing was sent.`);
|
|
1575
|
+
if (args.format === "carousel") {
|
|
1576
|
+
if (!args.cards || args.cards.length < 2) throw new ToolFailure("A carousel creative needs 2 to 10 cards. Nothing was sent.");
|
|
1577
|
+
return {
|
|
1578
|
+
link_data: compact({
|
|
1579
|
+
link: args.link,
|
|
1580
|
+
message: args.message,
|
|
1581
|
+
call_to_action: cta(args.call_to_action_type, args.call_to_action_link),
|
|
1582
|
+
child_attachments: args.cards.map((card) => compact({
|
|
1583
|
+
link: card.link,
|
|
1584
|
+
name: card.headline,
|
|
1585
|
+
description: card.description,
|
|
1586
|
+
image_hash: card.image_hash,
|
|
1587
|
+
video_id: card.video_id,
|
|
1588
|
+
call_to_action: cta(card.call_to_action_type, card.link)
|
|
1589
|
+
}))
|
|
1590
|
+
})
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
if (!args.image_hash) throw new ToolFailure("An image creative needs image_hash (from upload_image). Nothing was sent.");
|
|
1594
|
+
return {
|
|
1595
|
+
link_data: compact({
|
|
1596
|
+
link: args.link,
|
|
1597
|
+
message: args.message,
|
|
1598
|
+
name: args.headline,
|
|
1599
|
+
description: args.description,
|
|
1600
|
+
image_hash: args.image_hash,
|
|
1601
|
+
call_to_action: cta(args.call_to_action_type, args.call_to_action_link)
|
|
1602
|
+
})
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
function genericTools() {
|
|
1606
|
+
const tools = apiTools({
|
|
1607
|
+
label: "Meta Ads",
|
|
1608
|
+
description: "The Marketing API v26.0 on https://graph.facebook.com, with the connection's token: paths start with /v26.0/, such as /v26.0/act_<id>/insights, /v26.0/act_<id>/customaudiences, /v26.0/<campaign_id> or /v26.0/<ad_id>/previews, with parameters in query (lists and objects as JSON text). With ad accounts chosen, a path must name one of them or one of their objects, and Pages in a body must be chosen ones. One request per call: batch and method are refused; lead data and tokens stay out of reach. Reference: https://developers.facebook.com/docs/marketing-api.",
|
|
1609
|
+
basePath: `/${VERSION}/`,
|
|
1610
|
+
methods: ["POST", "DELETE"],
|
|
1611
|
+
guard: async (request, h) => {
|
|
1612
|
+
refuseSecrets(request);
|
|
1613
|
+
await adAccountLock(request, h);
|
|
1614
|
+
},
|
|
1615
|
+
send: async (request, h) => {
|
|
1616
|
+
const response = await graph(h, request);
|
|
1617
|
+
return { ...response, data: withoutSecrets(response.data) };
|
|
1618
|
+
}
|
|
1619
|
+
});
|
|
1620
|
+
return tools.map((tool) => ({
|
|
1621
|
+
...tool,
|
|
1622
|
+
async run(args, h) {
|
|
1623
|
+
const parts = readGraphRequest(args, "Meta Ads");
|
|
1624
|
+
refuseUnsafe(parts, "Meta Ads");
|
|
1625
|
+
refuseOutOfReach(parts, h);
|
|
1626
|
+
requirePages(h, parts.params.map(({ name: name2, value }) => ({ [name2]: value })));
|
|
1627
|
+
return tool.run(args, h);
|
|
1628
|
+
}
|
|
1629
|
+
}));
|
|
1630
|
+
}
|
|
1631
|
+
var connector = defineConnector({
|
|
1632
|
+
vendor: "meta-ads",
|
|
1633
|
+
label: "Meta Ads",
|
|
1634
|
+
origins: ["https://graph.facebook.com"],
|
|
1635
|
+
credentials: ["access_token", "systemusertoken", "appsecret_proof", "pagemappings"],
|
|
1636
|
+
requiredCredentials: [["access_token"], ["systemusertoken"]],
|
|
1637
|
+
credentialLabels: {
|
|
1638
|
+
access_token: "Meta Ads access token",
|
|
1639
|
+
systemusertoken: "Meta Ads system user token",
|
|
1640
|
+
appsecret_proof: "Meta Ads app secret proof",
|
|
1641
|
+
pagemappings: "Meta Ads Page mappings"
|
|
1642
|
+
},
|
|
1643
|
+
authHeaders: (credentials) => ({ authorization: `Bearer ${tokenOf(credentials)}` }),
|
|
1644
|
+
accountPickers: [
|
|
1645
|
+
{
|
|
1646
|
+
key: "ad_accounts",
|
|
1647
|
+
label: "Meta ad accounts",
|
|
1648
|
+
description: "The ad accounts the agent may report on and manage.",
|
|
1649
|
+
multiple: true,
|
|
1650
|
+
tool: "list_ad_accounts",
|
|
1651
|
+
idField: "id",
|
|
1652
|
+
nameField: "name",
|
|
1653
|
+
legacyField: "adaccountid"
|
|
1654
|
+
},
|
|
1655
|
+
{
|
|
1656
|
+
key: "pages",
|
|
1657
|
+
label: "Facebook Pages for ads",
|
|
1658
|
+
description: "The Pages the agent may use in ad creatives.",
|
|
1659
|
+
multiple: true,
|
|
1660
|
+
tool: "list_pages",
|
|
1661
|
+
idField: "id",
|
|
1662
|
+
nameField: "name",
|
|
1663
|
+
legacyField: "pagemappings"
|
|
1664
|
+
}
|
|
1665
|
+
],
|
|
1666
|
+
tools: withRateLimits([
|
|
1667
|
+
{
|
|
1668
|
+
name: "list_ad_accounts",
|
|
1669
|
+
kind: "read",
|
|
1670
|
+
title: "List Meta ad accounts",
|
|
1671
|
+
description: "Lists the ad accounts this connection can use, with id (without act_), name, status, currency, time zone and the connected account's tasks. By default only active accounts it can both manage and report on (ADVERTISE and ANALYZE); all: true lists every one. When ad accounts are chosen for the connection, only those are listed. Pass nextCursor back as cursor for more.",
|
|
1672
|
+
inputSchema: {
|
|
1673
|
+
type: "object",
|
|
1674
|
+
properties: {
|
|
1675
|
+
all: { type: "boolean", default: false, description: "true to list every ad account, not only the active ones with ADVERTISE and ANALYZE." },
|
|
1676
|
+
limit: { type: "integer", minimum: 1, maximum: 100, default: 50, description: "Ad accounts per call, 1 to 100 (default 50)." },
|
|
1677
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1678
|
+
},
|
|
1679
|
+
additionalProperties: false
|
|
1680
|
+
},
|
|
1681
|
+
async run(args, h) {
|
|
1682
|
+
const state = listState(h, args.cursor, args.limit);
|
|
1683
|
+
const { data } = await graph(h, {
|
|
1684
|
+
path: `/${VERSION}/me/adaccounts`,
|
|
1685
|
+
query: { fields: "account_id,name,account_status,currency,timezone_name,user_tasks", limit: state.limit, after: state.after }
|
|
1686
|
+
});
|
|
1687
|
+
const allowed = allowedAccounts(h.ctx.accounts, "ad_accounts");
|
|
1688
|
+
const accounts = rowsOf(data).filter((row) => args.all || row?.account_status === 1 && Array.isArray(row?.user_tasks) && row.user_tasks.includes("ADVERTISE") && row.user_tasks.includes("ANALYZE")).map(trimAccount).filter((item) => typeof item["id"] === "string" && (!allowed || allowed.includes(item["id"])));
|
|
1689
|
+
return listResult(h, "ad_accounts", accounts, state, data);
|
|
1690
|
+
}
|
|
1691
|
+
},
|
|
1692
|
+
{
|
|
1693
|
+
name: "get_ad_account",
|
|
1694
|
+
kind: "read",
|
|
1695
|
+
title: "Get a Meta ad account",
|
|
1696
|
+
description: "Returns an ad account's status (and why it is disabled), the connected account's tasks on it, currency, time zone, amount spent, balance, spend cap and minimum daily budget (money in the currency's minor unit). Check can_manage before any change: ANALYZE alone is read-only.",
|
|
1697
|
+
inputSchema: { type: "object", properties: { ad_account_id: AD_ACCOUNT_ID }, additionalProperties: false },
|
|
1698
|
+
async run(args, h) {
|
|
1699
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
1700
|
+
const { data } = await graph(h, {
|
|
1701
|
+
path: `/${VERSION}/act_${accountId}`,
|
|
1702
|
+
query: { fields: "account_id,name,account_status,disable_reason,user_tasks,currency,timezone_name,amount_spent,balance,spend_cap,min_daily_budget" }
|
|
1703
|
+
});
|
|
1704
|
+
return compact({
|
|
1705
|
+
...trimAccount(data),
|
|
1706
|
+
disable_reason: data?.disable_reason || void 0,
|
|
1707
|
+
amount_spent: data?.amount_spent,
|
|
1708
|
+
balance: data?.balance,
|
|
1709
|
+
spend_cap: data?.spend_cap,
|
|
1710
|
+
min_daily_budget: data?.min_daily_budget
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
},
|
|
1714
|
+
{
|
|
1715
|
+
name: "list_pages",
|
|
1716
|
+
kind: "read",
|
|
1717
|
+
title: "List Facebook Pages for ads",
|
|
1718
|
+
description: "Lists the Facebook Pages this connection can use in ad creatives: the Pages assigned to the connected account with its tasks on each (ADVERTISE to run ads), or, with ad_account_id, the Pages that ad account can promote. When Pages are chosen for the connection, only those are listed.",
|
|
1719
|
+
inputSchema: {
|
|
1720
|
+
type: "object",
|
|
1721
|
+
properties: {
|
|
1722
|
+
ad_account_id: { ...AD_ACCOUNT_ID, description: "List the Pages this ad account can promote instead." },
|
|
1723
|
+
limit: { type: "integer", minimum: 1, maximum: 100, default: 50, description: "Pages per call, 1 to 100 (default 50)." },
|
|
1724
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1725
|
+
},
|
|
1726
|
+
additionalProperties: false
|
|
1727
|
+
},
|
|
1728
|
+
async run(args, h) {
|
|
1729
|
+
const accountId = args.ad_account_id ? adAccountOf(h, args.ad_account_id) : void 0;
|
|
1730
|
+
const state = listState(h, args.cursor, args.limit);
|
|
1731
|
+
const { data } = await graph(h, {
|
|
1732
|
+
path: accountId ? `/${VERSION}/act_${accountId}/promote_pages` : `/${VERSION}/me/accounts`,
|
|
1733
|
+
query: { fields: accountId ? "id,name,category" : "id,name,category,tasks", limit: state.limit, after: state.after }
|
|
1734
|
+
});
|
|
1735
|
+
const allowed = allowedPages(h, accountId);
|
|
1736
|
+
const pages = rowsOf(data).filter((row) => typeof row?.id === "string" && (!allowed || allowed.includes(row.id))).map((row) => compact({ id: row.id, name: row.name, category: row.category, tasks: Array.isArray(row.tasks) ? row.tasks : void 0 }));
|
|
1737
|
+
return listResult(h, "pages", pages, state, data, accountId ? { ad_account_id: accountId } : void 0);
|
|
1738
|
+
}
|
|
1739
|
+
},
|
|
1740
|
+
{
|
|
1741
|
+
name: "get_insights",
|
|
1742
|
+
kind: "read",
|
|
1743
|
+
title: "Get Meta Ads insights",
|
|
1744
|
+
description: "Reads ad performance for an ad account at account, campaign, ad set or ad level: spend, impressions, reach, clicks, CTR, CPC, CPM, frequency, actions, cost per action and ROAS by default (ads also get their quality, engagement and conversion rankings), for a date preset (default last_7d) or since/until, optionally per day, broken down by age, gender, country, placement or device, and filtered to campaigns, ad sets or ads. Spend and costs are strings in the account currency, not minor units. Pass nextCursor back as cursor for more.",
|
|
1745
|
+
inputSchema: {
|
|
1746
|
+
type: "object",
|
|
1747
|
+
properties: {
|
|
1748
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
1749
|
+
level: { type: "string", enum: ["account", "campaign", "adset", "ad"], default: "campaign", description: "account, campaign (default), adset or ad." },
|
|
1750
|
+
fields: { type: "array", items: { type: "string", pattern: "^[a-z0-9_]{2,60}$" }, minItems: 1, maxItems: 40, uniqueItems: true, description: 'Insight fields instead of the defaults, e.g. ["spend", "actions"].' },
|
|
1751
|
+
date_preset: { type: "string", enum: DATE_PRESETS, description: "A date preset (default last_7d when no since/until)." },
|
|
1752
|
+
since: { type: "string", pattern: DATE_PATTERN, description: "The first day, in the account's time zone." },
|
|
1753
|
+
until: { type: "string", pattern: DATE_PATTERN, description: "The last day, included." },
|
|
1754
|
+
time_increment: { type: "string", pattern: "^([1-9]|[1-8][0-9]|90|monthly|all_days)$", description: "1 for one row per day, 7 per week, monthly, or all_days (default)." },
|
|
1755
|
+
breakdowns: { type: "array", items: { type: "string", enum: BREAKDOWNS }, minItems: 1, maxItems: 3, uniqueItems: true, description: 'Break the rows down, e.g. ["age", "gender"] or ["publisher_platform"].' },
|
|
1756
|
+
action_breakdowns: { type: "array", items: { type: "string", enum: ["action_type", "action_device", "action_destination", "action_video_type", "action_carousel_card_id"] }, minItems: 1, maxItems: 3, uniqueItems: true, description: "How actions are split (default action_type)." },
|
|
1757
|
+
campaign_ids: { type: "array", items: OBJECT_ID, minItems: 1, maxItems: 50, uniqueItems: true, description: "Only these campaigns." },
|
|
1758
|
+
adset_ids: { type: "array", items: OBJECT_ID, minItems: 1, maxItems: 50, uniqueItems: true, description: "Only these ad sets." },
|
|
1759
|
+
ad_ids: { type: "array", items: OBJECT_ID, minItems: 1, maxItems: 50, uniqueItems: true, description: "Only these ads." },
|
|
1760
|
+
sort: { type: "string", pattern: "^[a-z0-9_]{2,60}_(ascending|descending)$", description: "Sort rows, e.g. spend_descending." },
|
|
1761
|
+
limit: { type: "integer", minimum: 1, maximum: 500, default: 50, description: "Rows per call, 1 to 500 (default 50)." },
|
|
1762
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1763
|
+
},
|
|
1764
|
+
additionalProperties: false
|
|
1765
|
+
},
|
|
1766
|
+
async run(args, h) {
|
|
1767
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
1768
|
+
if ((args.since || args.until) && args.date_preset) throw new ToolFailure("Give date_preset or since and until, not both. Nothing was sent.");
|
|
1769
|
+
if (Boolean(args.since) !== Boolean(args.until)) throw new ToolFailure("since and until go together. Nothing was sent.");
|
|
1770
|
+
const state = listState(h, args.cursor, args.limit);
|
|
1771
|
+
const filtering = [
|
|
1772
|
+
...args.campaign_ids ? [{ field: "campaign.id", operator: "IN", value: args.campaign_ids }] : [],
|
|
1773
|
+
...args.adset_ids ? [{ field: "adset.id", operator: "IN", value: args.adset_ids }] : [],
|
|
1774
|
+
...args.ad_ids ? [{ field: "ad.id", operator: "IN", value: args.ad_ids }] : []
|
|
1775
|
+
];
|
|
1776
|
+
const range = args.since && args.until ? { since: args.since, until: args.until } : void 0;
|
|
1777
|
+
const { data } = await graph(h, {
|
|
1778
|
+
path: `/${VERSION}/act_${accountId}/insights`,
|
|
1779
|
+
query: {
|
|
1780
|
+
level: args.level,
|
|
1781
|
+
fields: (args.fields ?? DEFAULT_INSIGHT_FIELDS[args.level] ?? []).join(","),
|
|
1782
|
+
date_preset: range ? void 0 : args.date_preset ?? "last_7d",
|
|
1783
|
+
time_range: range ? JSON.stringify(range) : void 0,
|
|
1784
|
+
time_increment: args.time_increment,
|
|
1785
|
+
breakdowns: args.breakdowns?.join(","),
|
|
1786
|
+
action_breakdowns: args.action_breakdowns?.join(","),
|
|
1787
|
+
filtering: filtering.length ? JSON.stringify(filtering) : void 0,
|
|
1788
|
+
sort: args.sort,
|
|
1789
|
+
limit: state.limit,
|
|
1790
|
+
after: state.after
|
|
1791
|
+
}
|
|
1792
|
+
});
|
|
1793
|
+
return listResult(h, "rows", rowsOf(data), state, data, {
|
|
1794
|
+
ad_account_id: accountId,
|
|
1795
|
+
level: args.level,
|
|
1796
|
+
...range ? { since: range.since, until: range.until } : { date_preset: args.date_preset ?? "last_7d" },
|
|
1797
|
+
note: "Money in insights is in the account currency (not minor units). A row Meta has no data for is left out."
|
|
1798
|
+
});
|
|
1799
|
+
}
|
|
1800
|
+
},
|
|
1801
|
+
{
|
|
1802
|
+
name: "list_objects",
|
|
1803
|
+
kind: "read",
|
|
1804
|
+
title: "List Meta campaigns, ad sets, ads or creatives",
|
|
1805
|
+
description: "Lists an ad account's campaigns, ad sets, ads or creatives, newest first, with status, effective status and, for campaigns and ad sets, budgets (minor units), bid strategy and schedule; ad sets also show their targeting and optimization goal. Filter by campaign, ad set or effective status. Pass nextCursor back as cursor for more.",
|
|
1806
|
+
inputSchema: {
|
|
1807
|
+
type: "object",
|
|
1808
|
+
properties: {
|
|
1809
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
1810
|
+
type: { type: "string", enum: [...OBJECT_TYPES], description: "campaign, ad_set, ad or creative." },
|
|
1811
|
+
campaign_id: { ...OBJECT_ID, description: "Only the ad sets or ads of this campaign." },
|
|
1812
|
+
adset_id: { ...OBJECT_ID, description: "Only the ads of this ad set." },
|
|
1813
|
+
effective_status: STATUS_FILTER,
|
|
1814
|
+
limit: { type: "integer", minimum: 1, maximum: 100, default: 25, description: "Items per call, 1 to 100 (default 25)." },
|
|
1815
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1816
|
+
},
|
|
1817
|
+
required: ["type"],
|
|
1818
|
+
additionalProperties: false
|
|
1819
|
+
},
|
|
1820
|
+
async run(args, h) {
|
|
1821
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
1822
|
+
const state = listState(h, args.cursor, args.limit);
|
|
1823
|
+
const { edge, fields } = OBJECTS[args.type];
|
|
1824
|
+
const filtering = [
|
|
1825
|
+
...args.campaign_id && args.type !== "campaign" ? [{ field: "campaign.id", operator: "EQUAL", value: args.campaign_id }] : [],
|
|
1826
|
+
...args.adset_id && args.type === "ad" ? [{ field: "adset.id", operator: "EQUAL", value: args.adset_id }] : []
|
|
1827
|
+
];
|
|
1828
|
+
const { data } = await graph(h, {
|
|
1829
|
+
path: `/${VERSION}/act_${accountId}/${edge}`,
|
|
1830
|
+
query: {
|
|
1831
|
+
fields,
|
|
1832
|
+
effective_status: args.effective_status && args.type !== "creative" ? JSON.stringify(args.effective_status) : void 0,
|
|
1833
|
+
filtering: filtering.length ? JSON.stringify(filtering) : void 0,
|
|
1834
|
+
limit: state.limit,
|
|
1835
|
+
after: state.after
|
|
1836
|
+
}
|
|
1837
|
+
});
|
|
1838
|
+
return listResult(h, "items", rowsOf(data), state, data, { ad_account_id: accountId, type: args.type });
|
|
1839
|
+
}
|
|
1840
|
+
},
|
|
1841
|
+
{
|
|
1842
|
+
name: "get_object",
|
|
1843
|
+
kind: "read",
|
|
1844
|
+
title: "Get a Meta campaign, ad set, ad or creative",
|
|
1845
|
+
description: "Returns one campaign, ad set, ad or creative with its ad account, status, effective status and settings (budgets in minor units, targeting, creative). Use it to check a change, or one whose outcome was unclear.",
|
|
1846
|
+
inputSchema: {
|
|
1847
|
+
type: "object",
|
|
1848
|
+
properties: {
|
|
1849
|
+
type: { type: "string", enum: [...OBJECT_TYPES], description: "campaign, ad_set, ad or creative." },
|
|
1850
|
+
id: { ...OBJECT_ID, description: "Its id." }
|
|
1851
|
+
},
|
|
1852
|
+
required: ["type", "id"],
|
|
1853
|
+
additionalProperties: false
|
|
1854
|
+
},
|
|
1855
|
+
async run(args, h) {
|
|
1856
|
+
const extra = args.type === "ad" ? ",ad_review_feedback,issues_info" : args.type === "campaign" || args.type === "ad_set" ? ",updated_time" : "";
|
|
1857
|
+
const data = await objectInAccount(h, args.id, `${OBJECTS[args.type].fields}${extra}`);
|
|
1858
|
+
return compact({ ...data, account_id: String(data.account_id).replace(/^act_/, "") });
|
|
1859
|
+
}
|
|
1860
|
+
},
|
|
1861
|
+
{
|
|
1862
|
+
name: "list_audiences",
|
|
1863
|
+
kind: "read",
|
|
1864
|
+
title: "List Meta custom audiences",
|
|
1865
|
+
description: "Lists an ad account's custom and lookalike audiences with their size range, source, delivery status and last update. Pass nextCursor back as cursor for more.",
|
|
1866
|
+
inputSchema: {
|
|
1867
|
+
type: "object",
|
|
1868
|
+
properties: {
|
|
1869
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
1870
|
+
limit: { type: "integer", minimum: 1, maximum: 100, default: 25, description: "Audiences per call, 1 to 100 (default 25)." },
|
|
1871
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1872
|
+
},
|
|
1873
|
+
additionalProperties: false
|
|
1874
|
+
},
|
|
1875
|
+
async run(args, h) {
|
|
1876
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
1877
|
+
const state = listState(h, args.cursor, args.limit);
|
|
1878
|
+
const { data } = await graph(h, {
|
|
1879
|
+
path: `/${VERSION}/act_${accountId}/customaudiences`,
|
|
1880
|
+
query: {
|
|
1881
|
+
fields: "id,name,subtype,description,approximate_count_lower_bound,approximate_count_upper_bound,data_source,delivery_status,operation_status,time_updated",
|
|
1882
|
+
limit: state.limit,
|
|
1883
|
+
after: state.after
|
|
1884
|
+
}
|
|
1885
|
+
});
|
|
1886
|
+
const audiences = rowsOf(data).map((row) => compact({
|
|
1887
|
+
...row,
|
|
1888
|
+
description: typeof row?.description === "string" ? truncate(row.description, 300) : void 0,
|
|
1889
|
+
data_source: row?.data_source?.type ?? row?.data_source,
|
|
1890
|
+
delivery_status: row?.delivery_status?.description ?? row?.delivery_status,
|
|
1891
|
+
operation_status: row?.operation_status?.description ?? row?.operation_status
|
|
1892
|
+
}));
|
|
1893
|
+
return listResult(h, "audiences", audiences, state, data, { ad_account_id: accountId });
|
|
1894
|
+
}
|
|
1895
|
+
},
|
|
1896
|
+
{
|
|
1897
|
+
name: "list_ad_media",
|
|
1898
|
+
kind: "read",
|
|
1899
|
+
title: "List Meta ad images or videos",
|
|
1900
|
+
description: "Lists an ad account's uploaded ad images (hash, name, URL, size) or ad videos (id, title, processing status, length). Use it to find an image_hash or video_id, or to check an upload.",
|
|
1901
|
+
inputSchema: {
|
|
1902
|
+
type: "object",
|
|
1903
|
+
properties: {
|
|
1904
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
1905
|
+
type: { type: "string", enum: ["image", "video"], default: "image", description: "image (default) or video." },
|
|
1906
|
+
limit: { type: "integer", minimum: 1, maximum: 100, default: 25, description: "Items per call, 1 to 100 (default 25)." },
|
|
1907
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1908
|
+
},
|
|
1909
|
+
additionalProperties: false
|
|
1910
|
+
},
|
|
1911
|
+
async run(args, h) {
|
|
1912
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
1913
|
+
const state = listState(h, args.cursor, args.limit);
|
|
1914
|
+
const images = args.type === "image";
|
|
1915
|
+
const { data } = await graph(h, {
|
|
1916
|
+
path: `/${VERSION}/act_${accountId}/${images ? "adimages" : "advideos"}`,
|
|
1917
|
+
query: { fields: images ? "hash,name,url,width,height,status,created_time" : "id,title,status,length,created_time", limit: state.limit, after: state.after }
|
|
1918
|
+
});
|
|
1919
|
+
const items = rowsOf(data).map((row) => images ? compact(row) : compact({ ...row, status: row?.status?.video_status ?? row?.status }));
|
|
1920
|
+
return listResult(h, images ? "images" : "videos", items, state, data, { ad_account_id: accountId });
|
|
1921
|
+
}
|
|
1922
|
+
},
|
|
1923
|
+
{
|
|
1924
|
+
name: "search_targeting",
|
|
1925
|
+
kind: "read",
|
|
1926
|
+
title: "Search Meta targeting options",
|
|
1927
|
+
description: "Finds targeting ids for an ad set: interests (adinterest, or adinterestsuggestion from interest_list), places (adgeolocation, with location_types), languages (adlocale), employers, job titles, schools and fields of study, with the audience size range Meta gives.",
|
|
1928
|
+
inputSchema: {
|
|
1929
|
+
type: "object",
|
|
1930
|
+
properties: {
|
|
1931
|
+
type: {
|
|
1932
|
+
type: "string",
|
|
1933
|
+
enum: ["adinterest", "adinterestsuggestion", "adgeolocation", "adlocale", "adworkemployer", "adworkposition", "adeducationschool", "adeducationmajor"],
|
|
1934
|
+
description: "What to search."
|
|
1935
|
+
},
|
|
1936
|
+
q: { type: "string", minLength: 1, maxLength: 200, description: "The search text." },
|
|
1937
|
+
interest_list: { type: "array", items: { type: "string", minLength: 1, maxLength: 200 }, minItems: 1, maxItems: 10, description: "adinterestsuggestion: interest names to find related ones for." },
|
|
1938
|
+
location_types: {
|
|
1939
|
+
type: "array",
|
|
1940
|
+
items: { type: "string", enum: ["country", "region", "city", "zip", "geo_market", "electoral_district", "country_group", "neighborhood"] },
|
|
1941
|
+
minItems: 1,
|
|
1942
|
+
uniqueItems: true,
|
|
1943
|
+
description: "adgeolocation: the kinds of place to find."
|
|
1944
|
+
},
|
|
1945
|
+
limit: { type: "integer", minimum: 1, maximum: 50, default: 10, description: "Results, 1 to 50 (default 10)." }
|
|
1946
|
+
},
|
|
1947
|
+
required: ["type"],
|
|
1948
|
+
additionalProperties: false
|
|
1949
|
+
},
|
|
1950
|
+
async run(args, h) {
|
|
1951
|
+
if (args.type === "adinterestsuggestion" ? !args.interest_list : !args.q) {
|
|
1952
|
+
throw new ToolFailure(args.type === "adinterestsuggestion" ? "adinterestsuggestion needs interest_list. Nothing was sent." : "q is required. Nothing was sent.");
|
|
1953
|
+
}
|
|
1954
|
+
const { data } = await graph(h, {
|
|
1955
|
+
path: `/${VERSION}/search`,
|
|
1956
|
+
query: {
|
|
1957
|
+
type: args.type,
|
|
1958
|
+
q: args.q,
|
|
1959
|
+
interest_list: args.interest_list ? JSON.stringify(args.interest_list) : void 0,
|
|
1960
|
+
location_types: args.location_types ? JSON.stringify(args.location_types) : void 0,
|
|
1961
|
+
limit: args.limit
|
|
1962
|
+
}
|
|
1963
|
+
});
|
|
1964
|
+
return { type: args.type, results: rowsOf(data).slice(0, args.limit).map((row) => compact(row)) };
|
|
1965
|
+
}
|
|
1966
|
+
},
|
|
1967
|
+
{
|
|
1968
|
+
name: "estimate_audience",
|
|
1969
|
+
kind: "read",
|
|
1970
|
+
title: "Estimate a Meta Ads audience",
|
|
1971
|
+
description: "Estimates how many people a targeting spec reaches in an ad account (the monthly active range Meta gives), for an optimization goal (default REACH). Use it to size or compare audiences before creating an ad set.",
|
|
1972
|
+
inputSchema: {
|
|
1973
|
+
type: "object",
|
|
1974
|
+
properties: {
|
|
1975
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
1976
|
+
targeting: TARGETING,
|
|
1977
|
+
optimization_goal: { type: "string", pattern: "^[A-Z_]{2,60}$", default: "REACH", description: "The ad set optimization goal, e.g. REACH (default), LINK_CLICKS, OFFSITE_CONVERSIONS." },
|
|
1978
|
+
promoted_object: { type: "object", description: 'What the ad set promotes, when the goal needs it, e.g. {"pixel_id": "...", "custom_event_type": "PURCHASE"}.' }
|
|
1979
|
+
},
|
|
1980
|
+
required: ["targeting"],
|
|
1981
|
+
additionalProperties: false
|
|
1982
|
+
},
|
|
1983
|
+
async run(args, h) {
|
|
1984
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
1985
|
+
checkPlacements(args.targeting);
|
|
1986
|
+
const { data } = await graph(h, {
|
|
1987
|
+
path: `/${VERSION}/act_${accountId}/delivery_estimate`,
|
|
1988
|
+
query: {
|
|
1989
|
+
targeting_spec: JSON.stringify(args.targeting),
|
|
1990
|
+
optimization_goal: args.optimization_goal,
|
|
1991
|
+
promoted_object: args.promoted_object ? JSON.stringify(args.promoted_object) : void 0
|
|
1992
|
+
}
|
|
1993
|
+
});
|
|
1994
|
+
const [row] = rowsOf(data);
|
|
1995
|
+
return compact({
|
|
1996
|
+
ad_account_id: accountId,
|
|
1997
|
+
optimization_goal: args.optimization_goal,
|
|
1998
|
+
monthly_active_lower_bound: row?.estimate_mau_lower_bound,
|
|
1999
|
+
monthly_active_upper_bound: row?.estimate_mau_upper_bound,
|
|
2000
|
+
estimate_ready: row?.estimate_ready
|
|
2001
|
+
});
|
|
2002
|
+
}
|
|
2003
|
+
},
|
|
2004
|
+
{
|
|
2005
|
+
name: "create_campaign",
|
|
2006
|
+
kind: "create",
|
|
2007
|
+
check: "list_objects",
|
|
2008
|
+
title: "Create a Meta Ads campaign (paused)",
|
|
2009
|
+
description: "Creates a campaign in an ad account, always paused, with an objective (OUTCOME_*), special ad categories (FINANCIAL_PRODUCTS_SERVICES, EMPLOYMENT, HOUSING or ISSUES_ELECTIONS_POLITICS; [] for none), and optionally a campaign budget (daily or lifetime, in minor units), bid strategy, spend cap and schedule. Without a campaign budget, set budgets on its ad sets. Nothing runs until update_status turns it on.",
|
|
2010
|
+
inputSchema: {
|
|
2011
|
+
type: "object",
|
|
2012
|
+
properties: {
|
|
2013
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
2014
|
+
name: { type: "string", minLength: 1, maxLength: 400, description: "The campaign name." },
|
|
2015
|
+
objective: {
|
|
2016
|
+
type: "string",
|
|
2017
|
+
enum: ["OUTCOME_AWARENESS", "OUTCOME_ENGAGEMENT", "OUTCOME_TRAFFIC", "OUTCOME_LEADS", "OUTCOME_APP_PROMOTION", "OUTCOME_SALES"],
|
|
2018
|
+
description: "The campaign objective."
|
|
2019
|
+
},
|
|
2020
|
+
special_ad_categories: {
|
|
2021
|
+
type: "array",
|
|
2022
|
+
items: { type: "string", enum: ["FINANCIAL_PRODUCTS_SERVICES", "EMPLOYMENT", "HOUSING", "ISSUES_ELECTIONS_POLITICS"] },
|
|
2023
|
+
uniqueItems: true,
|
|
2024
|
+
default: [],
|
|
2025
|
+
description: "Declared categories for financial products, employment, housing or social issues; [] (default) for none."
|
|
2026
|
+
},
|
|
2027
|
+
special_ad_category_country: { type: "array", items: { type: "string", pattern: "^[A-Z]{2}$" }, minItems: 1, uniqueItems: true, description: 'Countries for the special ad categories, e.g. ["US"].' },
|
|
2028
|
+
bid_strategy: { type: "string", enum: ["LOWEST_COST_WITHOUT_CAP", "COST_CAP", "LOWEST_COST_WITH_BID_CAP", "LOWEST_COST_WITH_MIN_ROAS"], description: "With a campaign budget." },
|
|
2029
|
+
daily_budget: { ...MONEY, description: "A campaign daily budget in minor units (5000 is 50.00 in USD)." },
|
|
2030
|
+
lifetime_budget: { ...MONEY, description: "A campaign lifetime budget in minor units; needs stop_time." },
|
|
2031
|
+
spend_cap: { ...MONEY, description: "The most the campaign may spend in all, in minor units." },
|
|
2032
|
+
start_time: TIME,
|
|
2033
|
+
stop_time: TIME,
|
|
2034
|
+
adset_budget_sharing: { type: "boolean", description: "Without a campaign budget: let ad sets share up to 20% of their budgets (default false)." }
|
|
2035
|
+
},
|
|
2036
|
+
required: ["name", "objective"],
|
|
2037
|
+
additionalProperties: false
|
|
2038
|
+
},
|
|
2039
|
+
async run(args, h) {
|
|
2040
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
2041
|
+
if (args.daily_budget && args.lifetime_budget) throw new ToolFailure("Give daily_budget or lifetime_budget, not both. Nothing was sent.");
|
|
2042
|
+
const campaignBudget = Boolean(args.daily_budget || args.lifetime_budget);
|
|
2043
|
+
const { data } = await graph(h, {
|
|
2044
|
+
method: "POST",
|
|
2045
|
+
path: `/${VERSION}/act_${accountId}/campaigns`,
|
|
2046
|
+
json: compact({
|
|
2047
|
+
name: args.name,
|
|
2048
|
+
objective: args.objective,
|
|
2049
|
+
status: "PAUSED",
|
|
2050
|
+
special_ad_categories: args.special_ad_categories,
|
|
2051
|
+
special_ad_category_country: args.special_ad_category_country,
|
|
2052
|
+
bid_strategy: args.bid_strategy,
|
|
2053
|
+
daily_budget: args.daily_budget,
|
|
2054
|
+
lifetime_budget: args.lifetime_budget,
|
|
2055
|
+
spend_cap: args.spend_cap,
|
|
2056
|
+
start_time: args.start_time,
|
|
2057
|
+
stop_time: args.stop_time,
|
|
2058
|
+
is_adset_budget_sharing_enabled: campaignBudget ? void 0 : args.adset_budget_sharing ?? false
|
|
2059
|
+
}),
|
|
2060
|
+
write: true
|
|
2061
|
+
});
|
|
2062
|
+
return compact({
|
|
2063
|
+
campaign_id: data?.id ? String(data.id) : void 0,
|
|
2064
|
+
ad_account_id: accountId,
|
|
2065
|
+
name: args.name,
|
|
2066
|
+
objective: args.objective,
|
|
2067
|
+
status: "PAUSED",
|
|
2068
|
+
next: "The campaign is paused. Add ad sets and ads, then turn it on with update_status."
|
|
2069
|
+
});
|
|
2070
|
+
}
|
|
2071
|
+
},
|
|
2072
|
+
{
|
|
2073
|
+
name: "create_ad_set",
|
|
2074
|
+
kind: "create",
|
|
2075
|
+
check: "list_objects",
|
|
2076
|
+
title: "Create a Meta ad set (paused)",
|
|
2077
|
+
description: "Creates an ad set in a campaign, always paused: targeting, optimization goal, billing event (default IMPRESSIONS), and, unless the campaign has its own budget, a daily or lifetime budget in minor units; optionally a bid, schedule, promoted object (an app: its Meta app ID as application_id, from api_get /v26.0/act_<id>/advertisable_applications, and its store link as object_store_url; a pixel and event; or one of the chosen Pages), destination and attribution.",
|
|
2078
|
+
inputSchema: {
|
|
2079
|
+
type: "object",
|
|
2080
|
+
properties: {
|
|
2081
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
2082
|
+
campaign_id: { ...OBJECT_ID, description: "The campaign, from create_campaign or list_objects." },
|
|
2083
|
+
name: { type: "string", minLength: 1, maxLength: 400, description: "The ad set name." },
|
|
2084
|
+
optimization_goal: { type: "string", pattern: "^[A-Z_]{2,60}$", description: "e.g. LINK_CLICKS, LANDING_PAGE_VIEWS, IMPRESSIONS, REACH, OFFSITE_CONVERSIONS, LEAD_GENERATION, THRUPLAY, VALUE, APP_INSTALLS." },
|
|
2085
|
+
billing_event: { type: "string", pattern: "^[A-Z_]{2,60}$", default: "IMPRESSIONS", description: "What is paid for: IMPRESSIONS (default), LINK_CLICKS, THRUPLAY, ..." },
|
|
2086
|
+
targeting: TARGETING,
|
|
2087
|
+
daily_budget: { ...MONEY, description: "A daily budget in minor units (2000 is 20.00 in USD)." },
|
|
2088
|
+
lifetime_budget: { ...MONEY, description: "A lifetime budget in minor units; needs end_time." },
|
|
2089
|
+
bid_amount: { ...MONEY, description: "A bid or cost cap in minor units, for the bid strategies that take one." },
|
|
2090
|
+
bid_strategy: { type: "string", enum: ["LOWEST_COST_WITHOUT_CAP", "COST_CAP", "LOWEST_COST_WITH_BID_CAP", "LOWEST_COST_WITH_MIN_ROAS"], description: "The bid strategy." },
|
|
2091
|
+
start_time: TIME,
|
|
2092
|
+
end_time: TIME,
|
|
2093
|
+
promoted_object: {
|
|
2094
|
+
type: "object",
|
|
2095
|
+
description: `What the ad set promotes, e.g. {"application_id": "<the app's Meta app ID>", "object_store_url": "https://apps.apple.com/app/id<App Store id>"} (application_id is the Meta app registered for the app, listed by /v26.0/act_<id>/advertisable_applications; a store connector gives only the App Store id or the package name the store link is built from), {"pixel_id": "...", "custom_event_type": "PURCHASE"}, or {"page_id": "<a chosen Page>"}.`
|
|
2096
|
+
},
|
|
2097
|
+
destination_type: { type: "string", pattern: "^[A-Z_]{2,40}$", description: "Where people go, e.g. WEBSITE, APP, MESSENGER, WHATSAPP, ON_AD." },
|
|
2098
|
+
attribution_spec: { type: "array", maxItems: 4, items: { type: "object" }, description: 'e.g. [{"event_type": "CLICK_THROUGH", "window_days": 7}].' },
|
|
2099
|
+
dsa_beneficiary: { type: "string", maxLength: 200, description: "For ads shown in the EU: who benefits from the ad." },
|
|
2100
|
+
dsa_payor: { type: "string", maxLength: 200, description: "For ads shown in the EU: who pays for the ad." }
|
|
2101
|
+
},
|
|
2102
|
+
required: ["campaign_id", "name", "optimization_goal", "targeting"],
|
|
2103
|
+
additionalProperties: false
|
|
2104
|
+
},
|
|
2105
|
+
async run(args, h) {
|
|
2106
|
+
const accountId = adAccountOf(h, args["ad_account_id"]);
|
|
2107
|
+
checkPlacements(args["targeting"]);
|
|
2108
|
+
if (args["daily_budget"] && args["lifetime_budget"]) throw new ToolFailure("Give daily_budget or lifetime_budget, not both. Nothing was sent.");
|
|
2109
|
+
requirePages(h, [args["promoted_object"]], accountId);
|
|
2110
|
+
const { ad_account_id: _account, ...fields } = args;
|
|
2111
|
+
const { data } = await graph(h, {
|
|
2112
|
+
method: "POST",
|
|
2113
|
+
path: `/${VERSION}/act_${accountId}/adsets`,
|
|
2114
|
+
json: compact({ ...fields, status: "PAUSED" }),
|
|
2115
|
+
write: true
|
|
2116
|
+
});
|
|
2117
|
+
return compact({
|
|
2118
|
+
adset_id: data?.id ? String(data.id) : void 0,
|
|
2119
|
+
ad_account_id: accountId,
|
|
2120
|
+
campaign_id: args["campaign_id"],
|
|
2121
|
+
name: args["name"],
|
|
2122
|
+
status: "PAUSED"
|
|
2123
|
+
});
|
|
2124
|
+
}
|
|
2125
|
+
},
|
|
2126
|
+
{
|
|
2127
|
+
name: "upload_image",
|
|
2128
|
+
kind: "create",
|
|
2129
|
+
check: "list_ad_media",
|
|
2130
|
+
title: "Upload a Meta ad image",
|
|
2131
|
+
description: "Downloads an image from a public https URL (JPEG, PNG or GIF, up to 30 MB) and uploads it to an ad account's image library. Returns the image_hash a creative uses. Sizes: feed 1200x628 or 1080x1080, stories and Reels 1080x1920, at least 600 px wide.",
|
|
2132
|
+
inputSchema: {
|
|
2133
|
+
type: "object",
|
|
2134
|
+
properties: {
|
|
2135
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
2136
|
+
image_url: { ...HTTPS_URL, description: "A public https URL of the image." },
|
|
2137
|
+
name: { type: "string", minLength: 1, maxLength: 200, description: "A name for it in the library." }
|
|
2138
|
+
},
|
|
2139
|
+
required: ["image_url"],
|
|
2140
|
+
additionalProperties: false
|
|
2141
|
+
},
|
|
2142
|
+
async run(args, h) {
|
|
2143
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
2144
|
+
const { bytes } = await h.media(args.image_url, { what: "image", maxBytes: 3e7, accept: "image/jpeg,image/png,image/gif" });
|
|
2145
|
+
if (!imageType(bytes)) throw new ToolFailure("The URL did not return a JPEG, PNG or GIF image. Nothing was uploaded.");
|
|
2146
|
+
const { data } = await graph(h, {
|
|
2147
|
+
method: "POST",
|
|
2148
|
+
path: `/${VERSION}/act_${accountId}/adimages`,
|
|
2149
|
+
json: compact({ bytes: base64(bytes), name: args.name }),
|
|
2150
|
+
write: true
|
|
2151
|
+
});
|
|
2152
|
+
const images = data?.images && typeof data.images === "object" ? Object.values(data.images) : [];
|
|
2153
|
+
const [image] = images;
|
|
2154
|
+
return compact({ ad_account_id: accountId, image_hash: image?.hash, url: image?.url, width: image?.width, height: image?.height, bytes: bytes.length });
|
|
2155
|
+
}
|
|
2156
|
+
},
|
|
2157
|
+
{
|
|
2158
|
+
name: "upload_video",
|
|
2159
|
+
kind: "create",
|
|
2160
|
+
check: "list_ad_media",
|
|
2161
|
+
title: "Upload a Meta ad video",
|
|
2162
|
+
description: "Adds a video to an ad account from a public https URL (Meta downloads it; MP4 or MOV) and waits up to wait_seconds while Meta processes it. Returns the video_id a creative uses and its status; use it in a creative once the status is ready (list_ad_media shows it).",
|
|
2163
|
+
inputSchema: {
|
|
2164
|
+
type: "object",
|
|
2165
|
+
properties: {
|
|
2166
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
2167
|
+
video_url: { ...HTTPS_URL, description: "A public https URL of the video." },
|
|
2168
|
+
title: { type: "string", maxLength: 255, description: "The video title." },
|
|
2169
|
+
wait_seconds: { type: "integer", minimum: 0, maximum: 45, default: 30, description: "How long to wait for processing, 0 to 45 seconds (default 30)." }
|
|
2170
|
+
},
|
|
2171
|
+
required: ["video_url"],
|
|
2172
|
+
additionalProperties: false
|
|
2173
|
+
},
|
|
2174
|
+
async run(args, h) {
|
|
2175
|
+
const deadline = Date.now() + args.wait_seconds * 1e3;
|
|
2176
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
2177
|
+
const { data } = await graph(h, {
|
|
2178
|
+
method: "POST",
|
|
2179
|
+
path: `/${VERSION}/act_${accountId}/advideos`,
|
|
2180
|
+
json: compact({ file_url: args.video_url, title: args.title, name: args.title }),
|
|
2181
|
+
write: true
|
|
2182
|
+
});
|
|
2183
|
+
const videoId = data?.id ? String(data.id) : void 0;
|
|
2184
|
+
if (!videoId) throw new ToolFailure("Meta Ads sent back no video id. Check list_ad_media with type video before trying again.");
|
|
2185
|
+
let status;
|
|
2186
|
+
let reason;
|
|
2187
|
+
try {
|
|
2188
|
+
for (; ; ) {
|
|
2189
|
+
const read = await graph(h, { path: `/${VERSION}/${videoId}`, query: { fields: "status" } });
|
|
2190
|
+
status = read.data?.status?.video_status;
|
|
2191
|
+
reason = read.data?.status?.processing_phase?.error?.message ?? read.data?.status?.error?.message;
|
|
2192
|
+
if (status !== "processing" || Date.now() + POLL_MS > deadline) break;
|
|
2193
|
+
await sleep(POLL_MS, h.ctx.signal);
|
|
2194
|
+
}
|
|
2195
|
+
} catch (error) {
|
|
2196
|
+
if (!(error instanceof ToolFailure)) throw error;
|
|
2197
|
+
return { ad_account_id: accountId, video_id: videoId, status: "unknown", note: `The video was added; its status could not be read (${error.message}). Check list_ad_media with type video.` };
|
|
2198
|
+
}
|
|
2199
|
+
if (status === "error") {
|
|
2200
|
+
throw new ToolFailure(`The video was added as ${videoId}, but Meta Ads could not process it${reason ? `: ${truncate(String(reason), 300)}` : ""}. Upload a fixed file instead.`);
|
|
2201
|
+
}
|
|
2202
|
+
return compact({
|
|
2203
|
+
ad_account_id: accountId,
|
|
2204
|
+
video_id: videoId,
|
|
2205
|
+
status: status ?? "processing",
|
|
2206
|
+
next: status === "ready" ? void 0 : "Meta Ads is still processing the video: check list_ad_media with type video before using it in a creative."
|
|
2207
|
+
});
|
|
2208
|
+
}
|
|
2209
|
+
},
|
|
2210
|
+
{
|
|
2211
|
+
name: "create_creative",
|
|
2212
|
+
kind: "create",
|
|
2213
|
+
check: "list_objects",
|
|
2214
|
+
title: "Create a Meta ad creative",
|
|
2215
|
+
description: "Creates an ad creative for one of the chosen Facebook Pages (and optionally an Instagram account): an image ad (image_hash), a video ad (video_id, with a thumbnail) or a carousel of 2 to 10 cards, with primary text (message, 125 characters recommended), headline (40), description (30), link and call to action (LEARN_MORE, SHOP_NOW, SIGN_UP, DOWNLOAD, INSTALL_MOBILE_APP, ...). Returns the creative id for create_ad.",
|
|
2216
|
+
inputSchema: {
|
|
2217
|
+
type: "object",
|
|
2218
|
+
properties: {
|
|
2219
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
2220
|
+
page_id: { type: "string", pattern: "^[0-9]{1,30}$", description: "The Facebook Page the ad runs as, from list_pages. Leave it out when only one Page is chosen." },
|
|
2221
|
+
instagram_user_id: { type: "string", pattern: "^[0-9]{1,30}$", description: "An Instagram account id the ad runs as on Instagram." },
|
|
2222
|
+
name: { type: "string", minLength: 1, maxLength: 400, description: "The creative name." },
|
|
2223
|
+
format: { type: "string", enum: ["image", "video", "carousel"], description: "image, video or carousel." },
|
|
2224
|
+
message: { type: "string", maxLength: 2200, description: "The primary text." },
|
|
2225
|
+
link: { ...HTTPS_URL, description: "Where people go; required for image and carousel ads." },
|
|
2226
|
+
headline: { type: "string", maxLength: 255, description: "The headline." },
|
|
2227
|
+
description: { type: "string", maxLength: 255, description: "The description under the headline." },
|
|
2228
|
+
image_hash: { type: "string", pattern: "^[0-9a-f]{32}$", description: "From upload_image: the image of an image ad, or a video thumbnail." },
|
|
2229
|
+
video_id: { type: "string", pattern: "^[0-9]{1,30}$", description: "From upload_video, for a video ad." },
|
|
2230
|
+
thumbnail_url: { ...HTTPS_URL, description: "A public https URL of a video thumbnail." },
|
|
2231
|
+
call_to_action_type: { type: "string", pattern: "^[A-Z_]{2,40}$", description: "e.g. LEARN_MORE, SHOP_NOW, SIGN_UP, DOWNLOAD, GET_OFFER, CONTACT_US, SUBSCRIBE, APPLY_NOW, INSTALL_MOBILE_APP, USE_MOBILE_APP, BOOK_TRAVEL, GET_QUOTE, WATCH_MORE, SEND_MESSAGE." },
|
|
2232
|
+
call_to_action_link: { ...HTTPS_URL, description: "The call to action's link, when it differs from link (a video ad uses link by default)." },
|
|
2233
|
+
cards: {
|
|
2234
|
+
type: "array",
|
|
2235
|
+
minItems: 2,
|
|
2236
|
+
maxItems: 10,
|
|
2237
|
+
items: {
|
|
2238
|
+
type: "object",
|
|
2239
|
+
properties: {
|
|
2240
|
+
link: HTTPS_URL,
|
|
2241
|
+
headline: { type: "string", maxLength: 255 },
|
|
2242
|
+
description: { type: "string", maxLength: 255 },
|
|
2243
|
+
image_hash: { type: "string", pattern: "^[0-9a-f]{32}$" },
|
|
2244
|
+
video_id: { type: "string", pattern: "^[0-9]{1,30}$" },
|
|
2245
|
+
call_to_action_type: { type: "string", pattern: "^[A-Z_]{2,40}$" }
|
|
2246
|
+
},
|
|
2247
|
+
required: ["link"],
|
|
2248
|
+
additionalProperties: false
|
|
2249
|
+
},
|
|
2250
|
+
description: "Carousel cards: link, headline, description and an image_hash or video_id each."
|
|
2251
|
+
}
|
|
2252
|
+
},
|
|
2253
|
+
required: ["name", "format"],
|
|
2254
|
+
additionalProperties: false
|
|
2255
|
+
},
|
|
2256
|
+
async run(args, h) {
|
|
2257
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
2258
|
+
const pageId = choosePage(h, args.page_id, accountId);
|
|
2259
|
+
const story = objectStory(args);
|
|
2260
|
+
const { data } = await graph(h, {
|
|
2261
|
+
method: "POST",
|
|
2262
|
+
path: `/${VERSION}/act_${accountId}/adcreatives`,
|
|
2263
|
+
json: { name: args.name, object_story_spec: compact({ page_id: pageId, instagram_user_id: args.instagram_user_id, ...story }) },
|
|
2264
|
+
write: true
|
|
2265
|
+
});
|
|
2266
|
+
return compact({ creative_id: data?.id ? String(data.id) : void 0, ad_account_id: accountId, page_id: pageId, name: args.name, format: args.format });
|
|
2267
|
+
}
|
|
2268
|
+
},
|
|
2269
|
+
{
|
|
2270
|
+
name: "create_ad",
|
|
2271
|
+
kind: "create",
|
|
2272
|
+
check: "list_objects",
|
|
2273
|
+
title: "Create a Meta ad (paused)",
|
|
2274
|
+
description: "Creates an ad in an ad set from a creative, always paused; turn it on with update_status once its campaign and ad set are ready. Meta reviews every ad before it runs.",
|
|
2275
|
+
inputSchema: {
|
|
2276
|
+
type: "object",
|
|
2277
|
+
properties: {
|
|
2278
|
+
ad_account_id: AD_ACCOUNT_ID,
|
|
2279
|
+
adset_id: { ...OBJECT_ID, description: "The ad set, from create_ad_set or list_objects." },
|
|
2280
|
+
creative_id: { ...OBJECT_ID, description: "The creative, from create_creative or list_objects." },
|
|
2281
|
+
name: { type: "string", minLength: 1, maxLength: 400, description: "The ad name." },
|
|
2282
|
+
tracking_specs: { type: "array", maxItems: 10, items: { type: "object" }, description: 'Conversion tracking, e.g. [{"action.type": ["offsite_conversion"], "fb_pixel": ["<pixel id>"]}].' }
|
|
2283
|
+
},
|
|
2284
|
+
required: ["adset_id", "creative_id", "name"],
|
|
2285
|
+
additionalProperties: false
|
|
2286
|
+
},
|
|
2287
|
+
async run(args, h) {
|
|
2288
|
+
const accountId = adAccountOf(h, args.ad_account_id);
|
|
2289
|
+
const { data } = await graph(h, {
|
|
2290
|
+
method: "POST",
|
|
2291
|
+
path: `/${VERSION}/act_${accountId}/ads`,
|
|
2292
|
+
json: compact({ name: args.name, adset_id: args.adset_id, creative: { creative_id: args.creative_id }, status: "PAUSED", tracking_specs: args.tracking_specs }),
|
|
2293
|
+
write: true
|
|
2294
|
+
});
|
|
2295
|
+
return compact({ ad_id: data?.id ? String(data.id) : void 0, ad_account_id: accountId, adset_id: args.adset_id, creative_id: args.creative_id, status: "PAUSED" });
|
|
2296
|
+
}
|
|
2297
|
+
},
|
|
2298
|
+
{
|
|
2299
|
+
name: "update_status",
|
|
2300
|
+
kind: "update",
|
|
2301
|
+
check: "get_object",
|
|
2302
|
+
title: "Turn a Meta campaign, ad set or ad on or off",
|
|
2303
|
+
description: "Sets a campaign, ad set or ad to ACTIVE (it can start spending), PAUSED or ARCHIVED, after checking it belongs to a chosen ad account. Returns its status before and after. A campaign only spends when its ad sets and ads are active too.",
|
|
2304
|
+
inputSchema: {
|
|
2305
|
+
type: "object",
|
|
2306
|
+
properties: {
|
|
2307
|
+
object_id: OBJECT_ID,
|
|
2308
|
+
status: { type: "string", enum: ["ACTIVE", "PAUSED", "ARCHIVED"], description: "ACTIVE, PAUSED or ARCHIVED." }
|
|
2309
|
+
},
|
|
2310
|
+
required: ["object_id", "status"],
|
|
2311
|
+
additionalProperties: false
|
|
2312
|
+
},
|
|
2313
|
+
async run(args, h) {
|
|
2314
|
+
const before = await objectInAccount(h, args.object_id, "id,name,status");
|
|
2315
|
+
const { data } = await graph(h, { method: "POST", path: `/${VERSION}/${args.object_id}`, json: { status: args.status }, write: true });
|
|
2316
|
+
if (data?.success === false) throw new ToolFailure("Meta Ads did not change the status (it answered success: false). Check get_object before trying again.");
|
|
2317
|
+
return compact({ id: args.object_id, name: before?.name, previous_status: before?.status, status: args.status });
|
|
2318
|
+
}
|
|
2319
|
+
},
|
|
2320
|
+
{
|
|
2321
|
+
name: "update_budget",
|
|
2322
|
+
kind: "update",
|
|
2323
|
+
check: "get_object",
|
|
2324
|
+
title: "Change a Meta campaign or ad set budget",
|
|
2325
|
+
description: "Changes the budget of a campaign or ad set after checking it belongs to a chosen ad account: daily or lifetime budget, bid amount, spend cap (campaigns) or end time (ad sets). Money is in minor units (3000 is 30.00 in USD). Returns the values before and after.",
|
|
2326
|
+
inputSchema: {
|
|
2327
|
+
type: "object",
|
|
2328
|
+
properties: {
|
|
2329
|
+
object_id: { ...OBJECT_ID, description: "A campaign or ad set id." },
|
|
2330
|
+
daily_budget: MONEY,
|
|
2331
|
+
lifetime_budget: MONEY,
|
|
2332
|
+
bid_amount: MONEY,
|
|
2333
|
+
spend_cap: MONEY,
|
|
2334
|
+
end_time: TIME
|
|
2335
|
+
},
|
|
2336
|
+
required: ["object_id"],
|
|
2337
|
+
additionalProperties: false
|
|
2338
|
+
},
|
|
2339
|
+
async run(args, h) {
|
|
2340
|
+
const { object_id: id, ...changes } = args;
|
|
2341
|
+
if (!Object.keys(changes).length) throw new ToolFailure("Nothing to change: give a budget, bid_amount, spend_cap or end_time. Nothing was sent.");
|
|
2342
|
+
if (changes.daily_budget && changes.lifetime_budget) throw new ToolFailure("Give daily_budget or lifetime_budget, not both. Nothing was sent.");
|
|
2343
|
+
const before = await objectInAccount(h, id, "id,name,daily_budget,lifetime_budget");
|
|
2344
|
+
const { data } = await graph(h, { method: "POST", path: `/${VERSION}/${id}`, json: changes, write: true });
|
|
2345
|
+
if (data?.success === false) throw new ToolFailure("Meta Ads did not change the budget (it answered success: false). Check get_object before trying again.");
|
|
2346
|
+
return compact({
|
|
2347
|
+
id,
|
|
2348
|
+
name: before?.name,
|
|
2349
|
+
previous: compact({ daily_budget: before?.daily_budget, lifetime_budget: before?.lifetime_budget }),
|
|
2350
|
+
changed: changes
|
|
2351
|
+
});
|
|
2352
|
+
}
|
|
2353
|
+
},
|
|
2354
|
+
{
|
|
2355
|
+
name: "delete_object",
|
|
2356
|
+
kind: "delete",
|
|
2357
|
+
check: "get_object",
|
|
2358
|
+
title: "Delete a Meta campaign, ad set or ad",
|
|
2359
|
+
description: "Deletes a campaign, ad set or ad after checking it belongs to a chosen ad account. Meta keeps it with status DELETED; it cannot run again. Pausing is the reversible choice.",
|
|
2360
|
+
inputSchema: {
|
|
2361
|
+
type: "object",
|
|
2362
|
+
properties: { object_id: OBJECT_ID },
|
|
2363
|
+
required: ["object_id"],
|
|
2364
|
+
additionalProperties: false
|
|
2365
|
+
},
|
|
2366
|
+
async run(args, h) {
|
|
2367
|
+
const before = await objectInAccount(h, args.object_id, "id,name,status");
|
|
2368
|
+
const { data } = await graph(h, { method: "DELETE", path: `/${VERSION}/${args.object_id}`, write: true });
|
|
2369
|
+
return { id: args.object_id, name: before?.name, deleted: data?.success !== false };
|
|
2370
|
+
}
|
|
2371
|
+
},
|
|
2372
|
+
...genericTools()
|
|
2373
|
+
], "Meta Ads")
|
|
2374
|
+
});
|
|
2375
|
+
module.exports = connector;
|