@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +1131 -34
- package/dist/cli.js +15 -12
- package/dist/core/credentials.d.ts +21 -0
- package/dist/core/credentials.js +45 -0
- package/dist/core/origins.d.ts +18 -0
- package/dist/core/origins.js +40 -0
- package/dist/core/upload-hosts.d.ts +15 -0
- package/dist/core/upload-hosts.js +43 -0
- package/dist/host/describe.d.ts +10 -0
- package/dist/host/describe.js +38 -0
- package/dist/host/env.d.ts +25 -2
- package/dist/host/env.js +24 -7
- package/dist/host/guarded-fetch.d.ts +36 -9
- package/dist/host/guarded-fetch.js +175 -52
- package/dist/host/index.d.ts +8 -5
- package/dist/host/index.js +12 -1
- package/dist/host/load.js +31 -1
- package/dist/host/server.d.ts +13 -2
- package/dist/host/server.js +15 -2
- package/dist/types.d.ts +96 -5
- package/dist/vendors/adapty.js +1303 -0
- package/dist/vendors/adjust.js +1372 -0
- package/dist/vendors/apollo.js +2499 -0
- package/dist/vendors/apple-appstore.js +2798 -0
- package/dist/vendors/beehiiv.js +1965 -0
- package/dist/vendors/blogger.js +1687 -0
- package/dist/vendors/bluesky.js +850 -127
- package/dist/vendors/brevo.js +2195 -0
- package/dist/vendors/calendarific.js +1116 -0
- package/dist/vendors/devto.js +685 -92
- package/dist/vendors/facebook-pages.js +2185 -0
- package/dist/vendors/firebase.js +1333 -0
- package/dist/vendors/ga4.js +1585 -0
- package/dist/vendors/gmail.js +1962 -0
- package/dist/vendors/google-ads.js +2201 -0
- package/dist/vendors/google-business.js +1621 -0
- package/dist/vendors/google-calendar.js +1936 -0
- package/dist/vendors/google-drive.js +2654 -0
- package/dist/vendors/google-merchant-center.js +1742 -0
- package/dist/vendors/google-play.js +1856 -0
- package/dist/vendors/google-search-console.js +1572 -0
- package/dist/vendors/hashnode.js +1722 -0
- package/dist/vendors/instagram.js +2249 -0
- package/dist/vendors/kaggle.js +2043 -0
- package/dist/vendors/keepa.js +2087 -0
- package/dist/vendors/linkedin.js +1588 -0
- package/dist/vendors/mailchimp.js +2402 -0
- package/dist/vendors/mastodon.js +1836 -0
- package/dist/vendors/meta-ads.js +2375 -0
- package/dist/vendors/notion.js +1950 -0
- package/dist/vendors/pinterest.js +1744 -0
- package/dist/vendors/qiita.js +1552 -0
- package/dist/vendors/reddit.js +1791 -0
- package/dist/vendors/revenuecat.js +1593 -0
- package/dist/vendors/roasit.js +1460 -0
- package/dist/vendors/sendgrid.js +2188 -0
- package/dist/vendors/serper.js +901 -179
- package/dist/vendors/shopify.js +2511 -0
- package/dist/vendors/threads.js +1869 -0
- package/dist/vendors/tiktok.js +2199 -0
- package/dist/vendors/tumblr.js +1793 -0
- package/dist/vendors/twitter.js +1650 -0
- package/dist/vendors/woocommerce.js +2258 -0
- package/dist/vendors/wordpress.js +1904 -0
- package/dist/vendors/youtube.js +2542 -0
- package/package.json +1 -1
|
@@ -0,0 +1,2201 @@
|
|
|
1
|
+
/* google-ads connector module (MIT License). Built from src/vendors/google-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(text2) {
|
|
41
|
+
return encoder.encode(text2);
|
|
42
|
+
}
|
|
43
|
+
function utf8Length(text2) {
|
|
44
|
+
return encoder.encode(text2).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(text2) {
|
|
60
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text2)) throw new Error("not base64url");
|
|
61
|
+
const padded = text2.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text2.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
|
+
async function sha256Hex(text2) {
|
|
68
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(text2)));
|
|
69
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
70
|
+
}
|
|
71
|
+
function truncate(text2, max) {
|
|
72
|
+
if (text2.length <= max) return text2;
|
|
73
|
+
const points = Array.from(text2);
|
|
74
|
+
if (points.length <= max) return text2;
|
|
75
|
+
return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
|
|
76
|
+
}
|
|
77
|
+
function cleanVendorText(text2, max = 300) {
|
|
78
|
+
if (typeof text2 !== "string") return void 0;
|
|
79
|
+
if (/^\s*</.test(text2)) return void 0;
|
|
80
|
+
const line = text2.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
81
|
+
return line ? truncate(line, max) : void 0;
|
|
82
|
+
}
|
|
83
|
+
function formatNumber(value) {
|
|
84
|
+
return value.toLocaleString("en-US");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/core/output.ts
|
|
88
|
+
var OUTPUT_LIMIT_BYTES = 32 * 1024;
|
|
89
|
+
function jsonSize(value) {
|
|
90
|
+
return utf8Length(JSON.stringify(value) ?? "");
|
|
91
|
+
}
|
|
92
|
+
function cutStrings(value, max) {
|
|
93
|
+
if (typeof value === "string") return truncate(value, max);
|
|
94
|
+
if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
|
|
95
|
+
if (typeof value === "object" && value !== null) {
|
|
96
|
+
const out = {};
|
|
97
|
+
for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
|
|
103
|
+
if (jsonSize(value) <= limit) return { value, truncated: false };
|
|
104
|
+
for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
|
|
105
|
+
const cut = cutStrings(value, max);
|
|
106
|
+
if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
|
|
107
|
+
}
|
|
108
|
+
return void 0;
|
|
109
|
+
}
|
|
110
|
+
function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
|
|
111
|
+
const build = (count) => {
|
|
112
|
+
const cut = count < input.items.length;
|
|
113
|
+
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
|
|
114
|
+
const next = cut ? input.resumeAt(count) : input.nextPage;
|
|
115
|
+
if (next) result2["nextCursor"] = next;
|
|
116
|
+
if (cut) result2["truncated"] = true;
|
|
117
|
+
return result2;
|
|
118
|
+
};
|
|
119
|
+
const all = build(input.items.length);
|
|
120
|
+
if (jsonSize(all) <= limit) return all;
|
|
121
|
+
let low = 1;
|
|
122
|
+
let high = input.items.length - 1;
|
|
123
|
+
while (low < high) {
|
|
124
|
+
const middle = Math.ceil((low + high) / 2);
|
|
125
|
+
if (jsonSize(build(middle)) <= limit) low = middle;
|
|
126
|
+
else high = middle - 1;
|
|
127
|
+
}
|
|
128
|
+
const best = build(low);
|
|
129
|
+
if (jsonSize(best) <= limit) return best;
|
|
130
|
+
const shrunk = shrinkToFit(best, limit);
|
|
131
|
+
if (shrunk) return { ...shrunk.value, truncated: true };
|
|
132
|
+
throw new ToolFailure("The result is too large to return, even one item at a time.");
|
|
133
|
+
}
|
|
134
|
+
function encodeCursor(tool, state) {
|
|
135
|
+
return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
|
|
136
|
+
}
|
|
137
|
+
function decodeCursor(tool, cursor) {
|
|
138
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
139
|
+
try {
|
|
140
|
+
const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
|
|
141
|
+
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
142
|
+
return state;
|
|
143
|
+
}
|
|
144
|
+
} catch {
|
|
145
|
+
}
|
|
146
|
+
throw new ToolFailure(
|
|
147
|
+
"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."
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// src/core/api-tools.ts
|
|
152
|
+
var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
|
|
153
|
+
var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
|
|
154
|
+
var NOTE_ROOM = 400;
|
|
155
|
+
var MAX_CUT_POINTS = 4e4;
|
|
156
|
+
function isQueryValue(value) {
|
|
157
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
158
|
+
}
|
|
159
|
+
function nothingSent(sentence) {
|
|
160
|
+
return new ToolFailure(`${sentence} Nothing was sent.`);
|
|
161
|
+
}
|
|
162
|
+
function fitReply(reply) {
|
|
163
|
+
if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
|
|
164
|
+
const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
|
|
165
|
+
if (shrunk) {
|
|
166
|
+
return {
|
|
167
|
+
...shrunk.value,
|
|
168
|
+
truncated: true,
|
|
169
|
+
note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
const text2 = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
|
|
173
|
+
const points = Array.from(text2.length > MAX_CUT_POINTS ? text2.slice(0, MAX_CUT_POINTS) : text2);
|
|
174
|
+
if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
|
|
175
|
+
const cut = (count) => ({
|
|
176
|
+
status: reply["status"],
|
|
177
|
+
...reply["headers"] ? { headers: reply["headers"] } : {},
|
|
178
|
+
truncated: true,
|
|
179
|
+
note: `The reply has ${formatNumber(utf8Length(text2))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
|
|
180
|
+
text: points.slice(0, count).join("")
|
|
181
|
+
});
|
|
182
|
+
let low = 0;
|
|
183
|
+
let high = points.length;
|
|
184
|
+
while (low < high) {
|
|
185
|
+
const middle = Math.ceil((low + high) / 2);
|
|
186
|
+
if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
|
|
187
|
+
else high = middle - 1;
|
|
188
|
+
}
|
|
189
|
+
return cut(low);
|
|
190
|
+
}
|
|
191
|
+
function shapeReply(response, headerNames) {
|
|
192
|
+
const reply = { status: response.status };
|
|
193
|
+
const headers = {};
|
|
194
|
+
for (const name2 of headerNames) {
|
|
195
|
+
const value = response.headers.get(name2);
|
|
196
|
+
if (value) headers[name2] = truncate(value, 2e3);
|
|
197
|
+
}
|
|
198
|
+
if (Object.keys(headers).length) reply["headers"] = headers;
|
|
199
|
+
const type = response.headers.get("content-type") ?? "";
|
|
200
|
+
if (type && !TEXT_TYPES.test(type)) {
|
|
201
|
+
reply["contentType"] = truncate(type, 200);
|
|
202
|
+
reply["note"] = "The reply is a binary file and is not shown.";
|
|
203
|
+
return reply;
|
|
204
|
+
}
|
|
205
|
+
if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
|
|
206
|
+
return fitReply(reply);
|
|
207
|
+
}
|
|
208
|
+
function checkAccounts(rule, request, h) {
|
|
209
|
+
const label = rule.label ?? "account";
|
|
210
|
+
const allowed = allowedAccounts(h.ctx.accounts, rule.key);
|
|
211
|
+
if (allowed === null) return;
|
|
212
|
+
const namesNone = nothingSent(
|
|
213
|
+
`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.`)
|
|
214
|
+
);
|
|
215
|
+
if (rule.ids) {
|
|
216
|
+
const ids = rule.ids(request).map(String);
|
|
217
|
+
if (!ids.length) throw namesNone;
|
|
218
|
+
requireAccounts(h.ctx.accounts, rule.key, ids, label);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
|
|
222
|
+
}
|
|
223
|
+
function apiTools(options) {
|
|
224
|
+
const { label, basePath } = options;
|
|
225
|
+
const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
|
|
226
|
+
const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
|
|
227
|
+
const base = basePath?.replace(/\/+$/, "");
|
|
228
|
+
const pathSchema = {
|
|
229
|
+
type: "string",
|
|
230
|
+
minLength: 1,
|
|
231
|
+
maxLength: 2e3,
|
|
232
|
+
pattern: "^(?!.*//)/[^?#]*$",
|
|
233
|
+
description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
|
|
234
|
+
};
|
|
235
|
+
const querySchema = {
|
|
236
|
+
type: "object",
|
|
237
|
+
description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
|
|
238
|
+
};
|
|
239
|
+
const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
|
|
240
|
+
async function run(method, args, h) {
|
|
241
|
+
let origin = h.origins[0];
|
|
242
|
+
if (args.origin !== void 0) {
|
|
243
|
+
let wanted;
|
|
244
|
+
try {
|
|
245
|
+
wanted = new URL(args.origin).origin;
|
|
246
|
+
} catch {
|
|
247
|
+
}
|
|
248
|
+
if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
|
|
249
|
+
origin = wanted;
|
|
250
|
+
}
|
|
251
|
+
const url = new URL(args.path, origin);
|
|
252
|
+
if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
|
|
253
|
+
const path = url.pathname;
|
|
254
|
+
if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
|
|
255
|
+
let segments;
|
|
256
|
+
try {
|
|
257
|
+
segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
|
|
258
|
+
} catch {
|
|
259
|
+
throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
|
|
260
|
+
}
|
|
261
|
+
if (segments[segments.length - 1] === "") segments.pop();
|
|
262
|
+
const query = {};
|
|
263
|
+
const queryLists = {};
|
|
264
|
+
for (const [key, value] of Object.entries(args.query ?? {})) {
|
|
265
|
+
if (value === void 0 || value === null) continue;
|
|
266
|
+
const list = Array.isArray(value) ? value : [value];
|
|
267
|
+
if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
|
|
268
|
+
query[key] = Array.isArray(value) ? list : value;
|
|
269
|
+
queryLists[key] = list.map(String);
|
|
270
|
+
}
|
|
271
|
+
const request = { method, origin, path, query };
|
|
272
|
+
if (method !== "GET") {
|
|
273
|
+
if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
|
|
274
|
+
if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
|
|
275
|
+
if (args.json !== void 0 && !args.content_type) {
|
|
276
|
+
request.json = args.json;
|
|
277
|
+
} else if (args.json !== void 0 || args.body !== void 0) {
|
|
278
|
+
request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
|
|
279
|
+
request.contentType = args.content_type;
|
|
280
|
+
}
|
|
281
|
+
request.write = true;
|
|
282
|
+
}
|
|
283
|
+
const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
|
|
284
|
+
if (options.accounts) checkAccounts(options.accounts, info, h);
|
|
285
|
+
await options.guard?.(info, h);
|
|
286
|
+
const response = options.send ? await options.send(request, h) : await h.api(request);
|
|
287
|
+
return shapeReply(response, headerNames);
|
|
288
|
+
}
|
|
289
|
+
return [
|
|
290
|
+
{
|
|
291
|
+
name: "api_get",
|
|
292
|
+
kind: "read",
|
|
293
|
+
title: `Call the ${label} API (GET)`,
|
|
294
|
+
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.`,
|
|
295
|
+
inputSchema: {
|
|
296
|
+
type: "object",
|
|
297
|
+
properties: { path: pathSchema, query: querySchema, ...originSchema },
|
|
298
|
+
required: ["path"],
|
|
299
|
+
additionalProperties: false
|
|
300
|
+
},
|
|
301
|
+
run: (args, h) => run("GET", args, h)
|
|
302
|
+
},
|
|
303
|
+
{
|
|
304
|
+
name: "api_request",
|
|
305
|
+
kind: "write",
|
|
306
|
+
check: "api_get",
|
|
307
|
+
title: `Send a request to the ${label} API`,
|
|
308
|
+
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.`,
|
|
309
|
+
inputSchema: {
|
|
310
|
+
type: "object",
|
|
311
|
+
properties: {
|
|
312
|
+
method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
|
|
313
|
+
path: pathSchema,
|
|
314
|
+
query: querySchema,
|
|
315
|
+
json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
|
|
316
|
+
body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
|
|
317
|
+
content_type: {
|
|
318
|
+
type: "string",
|
|
319
|
+
pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
|
|
320
|
+
maxLength: 200,
|
|
321
|
+
description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
|
|
322
|
+
},
|
|
323
|
+
...originSchema
|
|
324
|
+
},
|
|
325
|
+
required: ["method", "path"],
|
|
326
|
+
additionalProperties: false
|
|
327
|
+
},
|
|
328
|
+
run: (args, h) => run(args.method, args, h)
|
|
329
|
+
}
|
|
330
|
+
];
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// src/core/credentials.ts
|
|
334
|
+
function requiredAlternatives(module2) {
|
|
335
|
+
return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
|
|
336
|
+
}
|
|
337
|
+
function unmetAlternatives(alternatives, has) {
|
|
338
|
+
const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
|
|
339
|
+
if (lacking.some((list) => list.length === 0)) return [];
|
|
340
|
+
return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
|
|
341
|
+
}
|
|
342
|
+
function andList(items) {
|
|
343
|
+
if (items.length <= 2) return items.join(" and ");
|
|
344
|
+
return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
|
|
345
|
+
}
|
|
346
|
+
function orList(items) {
|
|
347
|
+
if (items.length <= 1) return items.join("");
|
|
348
|
+
return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// src/core/files.ts
|
|
352
|
+
var ATTACHMENT_URI = "attachment:///";
|
|
353
|
+
var MAX_NAME = 200;
|
|
354
|
+
function fileLimitOf(ctx) {
|
|
355
|
+
const maxBytes = ctx.files?.maxBytes;
|
|
356
|
+
return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
|
|
357
|
+
}
|
|
358
|
+
function fileName(name2) {
|
|
359
|
+
const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
|
|
360
|
+
const points = Array.from(clean);
|
|
361
|
+
if (points.length <= MAX_NAME) return clean || "file";
|
|
362
|
+
const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
|
|
363
|
+
return points.slice(0, MAX_NAME - extension.length).join("") + extension;
|
|
364
|
+
}
|
|
365
|
+
function fileType(mimeType) {
|
|
366
|
+
const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
|
|
367
|
+
return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
|
|
368
|
+
}
|
|
369
|
+
function resourceBlock(file) {
|
|
370
|
+
return {
|
|
371
|
+
type: "resource",
|
|
372
|
+
resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// src/core/http.ts
|
|
377
|
+
var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
378
|
+
var USER_AGENT = "agent-connectors";
|
|
379
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
380
|
+
function errorCode(error) {
|
|
381
|
+
const code = error?.code;
|
|
382
|
+
return typeof code === "string" ? code : void 0;
|
|
383
|
+
}
|
|
384
|
+
function describe(error) {
|
|
385
|
+
const name2 = error?.name;
|
|
386
|
+
const code = errorCode(error);
|
|
387
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
388
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
389
|
+
if (code === "TOO_LARGE") return "the reply was too large";
|
|
390
|
+
return cleanVendorText(error?.message, 200) ?? "a network error";
|
|
391
|
+
}
|
|
392
|
+
function retryAfterSeconds(headers, now = Date.now()) {
|
|
393
|
+
const retryAfter = headers.get("retry-after");
|
|
394
|
+
if (retryAfter) {
|
|
395
|
+
const seconds = Number(retryAfter);
|
|
396
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
397
|
+
const date = Date.parse(retryAfter);
|
|
398
|
+
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
|
|
399
|
+
}
|
|
400
|
+
const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
|
|
401
|
+
if (reset) {
|
|
402
|
+
const value = Number(reset);
|
|
403
|
+
if (Number.isFinite(value) && value >= 0) {
|
|
404
|
+
return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return void 0;
|
|
408
|
+
}
|
|
409
|
+
function vendorCode(data) {
|
|
410
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
411
|
+
for (const key of ["error", "code"]) {
|
|
412
|
+
const value = data[key];
|
|
413
|
+
if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
|
|
414
|
+
}
|
|
415
|
+
return void 0;
|
|
416
|
+
}
|
|
417
|
+
function vendorMessage(data) {
|
|
418
|
+
if (typeof data === "string") return cleanVendorText(data);
|
|
419
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
420
|
+
const record = data;
|
|
421
|
+
for (const key of ["message", "error_description", "error", "detail", "title"]) {
|
|
422
|
+
const value = record[key];
|
|
423
|
+
if (typeof value === "string" && value.trim()) return cleanVendorText(value);
|
|
424
|
+
const nested = value?.message;
|
|
425
|
+
if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
|
|
426
|
+
}
|
|
427
|
+
if (Array.isArray(record["errors"])) {
|
|
428
|
+
const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
|
|
429
|
+
if (messages.length) return cleanVendorText(messages.join("; "));
|
|
430
|
+
}
|
|
431
|
+
return void 0;
|
|
432
|
+
}
|
|
433
|
+
var TooLarge = class extends Error {
|
|
434
|
+
constructor(limit) {
|
|
435
|
+
super(`the reply is larger than ${formatNumber(limit)} bytes`);
|
|
436
|
+
this.limit = limit;
|
|
437
|
+
}
|
|
438
|
+
limit;
|
|
439
|
+
};
|
|
440
|
+
async function readCapped(response, maxBytes) {
|
|
441
|
+
const declared = Number(response.headers.get("content-length"));
|
|
442
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
443
|
+
await response.body?.cancel().catch(() => {
|
|
444
|
+
});
|
|
445
|
+
throw new TooLarge(maxBytes);
|
|
446
|
+
}
|
|
447
|
+
if (!response.body) return new Uint8Array(0);
|
|
448
|
+
const reader = response.body.getReader();
|
|
449
|
+
const chunks = [];
|
|
450
|
+
let total = 0;
|
|
451
|
+
for (; ; ) {
|
|
452
|
+
const { done, value } = await reader.read();
|
|
453
|
+
if (done) break;
|
|
454
|
+
total += value.byteLength;
|
|
455
|
+
if (total > maxBytes) {
|
|
456
|
+
await reader.cancel().catch(() => {
|
|
457
|
+
});
|
|
458
|
+
throw new TooLarge(maxBytes);
|
|
459
|
+
}
|
|
460
|
+
chunks.push(value);
|
|
461
|
+
}
|
|
462
|
+
const bytes = new Uint8Array(total);
|
|
463
|
+
let offset = 0;
|
|
464
|
+
for (const chunk of chunks) {
|
|
465
|
+
bytes.set(chunk, offset);
|
|
466
|
+
offset += chunk.byteLength;
|
|
467
|
+
}
|
|
468
|
+
return bytes;
|
|
469
|
+
}
|
|
470
|
+
function parseBody(bytes, contentType) {
|
|
471
|
+
if (bytes.length === 0) return null;
|
|
472
|
+
const text2 = utf8Decode(bytes);
|
|
473
|
+
if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text2)) {
|
|
474
|
+
try {
|
|
475
|
+
return JSON.parse(text2);
|
|
476
|
+
} catch {
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return text2;
|
|
480
|
+
}
|
|
481
|
+
function createHttp(env) {
|
|
482
|
+
const { label, ctx } = env;
|
|
483
|
+
const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
|
|
484
|
+
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.`;
|
|
485
|
+
function failureFor(status, headers, data, request) {
|
|
486
|
+
const message = vendorMessage(data);
|
|
487
|
+
const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
|
|
488
|
+
const retryAfter = retryAfterSeconds(headers);
|
|
489
|
+
const code = vendorCode(data);
|
|
490
|
+
const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
|
|
491
|
+
const custom = request.errors?.[status];
|
|
492
|
+
const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
|
|
493
|
+
if (status >= 500) {
|
|
494
|
+
if (request.write) {
|
|
495
|
+
return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
|
|
496
|
+
}
|
|
497
|
+
return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
|
|
498
|
+
}
|
|
499
|
+
if (status === 429) {
|
|
500
|
+
return new ToolFailure(
|
|
501
|
+
`${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
|
|
502
|
+
{ status, ...extra }
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
if (status === 401) {
|
|
506
|
+
return new ToolFailure(
|
|
507
|
+
withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
|
|
508
|
+
{ status, ...extra }
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
|
|
512
|
+
if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
|
|
513
|
+
if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
|
|
514
|
+
return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
|
|
515
|
+
}
|
|
516
|
+
async function api(request) {
|
|
517
|
+
const method = request.method ?? "GET";
|
|
518
|
+
if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
|
|
519
|
+
throw new Error(`read-only tool sent ${method}`);
|
|
520
|
+
}
|
|
521
|
+
const origin = request.origin ?? env.origins[0];
|
|
522
|
+
if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
|
|
523
|
+
const url = new URL(request.path, origin);
|
|
524
|
+
if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
|
|
525
|
+
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
526
|
+
if (value === void 0 || value === null) continue;
|
|
527
|
+
if (Array.isArray(value)) {
|
|
528
|
+
url.searchParams.delete(key);
|
|
529
|
+
for (const item of value) url.searchParams.append(key, String(item));
|
|
530
|
+
} else {
|
|
531
|
+
url.searchParams.set(key, String(value));
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
const headers = {
|
|
535
|
+
accept: "application/json",
|
|
536
|
+
"user-agent": USER_AGENT,
|
|
537
|
+
...request.auth === false ? {} : env.authHeaders(),
|
|
538
|
+
...request.headers
|
|
539
|
+
};
|
|
540
|
+
let body;
|
|
541
|
+
if (request.json !== void 0) {
|
|
542
|
+
body = JSON.stringify(request.json);
|
|
543
|
+
headers["content-type"] = "application/json";
|
|
544
|
+
} else if (request.body) {
|
|
545
|
+
body = request.body;
|
|
546
|
+
headers["content-type"] = request.contentType ?? "application/octet-stream";
|
|
547
|
+
}
|
|
548
|
+
const started = Date.now();
|
|
549
|
+
if (request.write) env.onWriteSent();
|
|
550
|
+
let response;
|
|
551
|
+
try {
|
|
552
|
+
response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
|
|
553
|
+
} catch (error) {
|
|
554
|
+
env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
|
|
555
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
556
|
+
throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
|
|
557
|
+
}
|
|
558
|
+
if (request.write) {
|
|
559
|
+
throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
|
|
560
|
+
}
|
|
561
|
+
if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
|
|
562
|
+
throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
|
|
563
|
+
}
|
|
564
|
+
env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
|
|
565
|
+
let bytes;
|
|
566
|
+
try {
|
|
567
|
+
bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
|
|
568
|
+
} catch (error) {
|
|
569
|
+
if (request.write && (response.ok || response.status >= 500)) {
|
|
570
|
+
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.`);
|
|
571
|
+
}
|
|
572
|
+
throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
|
|
573
|
+
}
|
|
574
|
+
const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
|
|
575
|
+
if (response.ok) return { status: response.status, headers: response.headers, data };
|
|
576
|
+
throw failureFor(response.status, response.headers, data, request);
|
|
577
|
+
}
|
|
578
|
+
async function media(rawUrl, options) {
|
|
579
|
+
const { what } = options;
|
|
580
|
+
let url;
|
|
581
|
+
try {
|
|
582
|
+
url = new URL(rawUrl);
|
|
583
|
+
} catch {
|
|
584
|
+
throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
|
|
585
|
+
}
|
|
586
|
+
if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
|
|
587
|
+
const started = Date.now();
|
|
588
|
+
let response;
|
|
589
|
+
try {
|
|
590
|
+
response = await ctx.fetch(url.toString(), {
|
|
591
|
+
method: "GET",
|
|
592
|
+
headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
|
|
593
|
+
...ctx.signal ? { signal: ctx.signal } : {}
|
|
594
|
+
});
|
|
595
|
+
} catch (error) {
|
|
596
|
+
env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
|
|
597
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
598
|
+
throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
|
|
599
|
+
}
|
|
600
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
601
|
+
}
|
|
602
|
+
env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
|
|
603
|
+
if (!response.ok) {
|
|
604
|
+
await response.body?.cancel().catch(() => {
|
|
605
|
+
});
|
|
606
|
+
throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
|
|
607
|
+
}
|
|
608
|
+
try {
|
|
609
|
+
const bytes = await readCapped(response, options.maxBytes);
|
|
610
|
+
return { bytes, contentType: response.headers.get("content-type") };
|
|
611
|
+
} catch (error) {
|
|
612
|
+
if (error instanceof TooLarge) {
|
|
613
|
+
throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
|
|
614
|
+
}
|
|
615
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
return { api, media };
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// src/core/origins.ts
|
|
622
|
+
function parseSiteUrl(value) {
|
|
623
|
+
const text2 = typeof value === "string" ? value.trim() : "";
|
|
624
|
+
if (!text2) return { ok: false, problem: "is empty" };
|
|
625
|
+
let url;
|
|
626
|
+
try {
|
|
627
|
+
url = new URL(text2.includes("://") ? text2 : `https://${text2}`);
|
|
628
|
+
} catch {
|
|
629
|
+
return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
|
|
630
|
+
}
|
|
631
|
+
if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
|
|
632
|
+
if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
|
|
633
|
+
if (!url.hostname) return { ok: false, problem: "has no host name" };
|
|
634
|
+
return { ok: true, url, origin: url.origin };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// src/core/schema.ts
|
|
638
|
+
var patterns = /* @__PURE__ */ new Map();
|
|
639
|
+
function patternOf(source) {
|
|
640
|
+
let compiled = patterns.get(source);
|
|
641
|
+
if (!compiled) {
|
|
642
|
+
compiled = new RegExp(source, "u");
|
|
643
|
+
patterns.set(source, compiled);
|
|
644
|
+
}
|
|
645
|
+
return compiled;
|
|
646
|
+
}
|
|
647
|
+
function isPlainObject(value) {
|
|
648
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
649
|
+
}
|
|
650
|
+
function isHttpUrl(value) {
|
|
651
|
+
try {
|
|
652
|
+
const url = new URL(value);
|
|
653
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
654
|
+
} catch {
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
function name(path) {
|
|
659
|
+
return `\`${path}\``;
|
|
660
|
+
}
|
|
661
|
+
function child(path, key) {
|
|
662
|
+
return path ? `${path}.${key}` : key;
|
|
663
|
+
}
|
|
664
|
+
function checkValue(schema, value, path, issues) {
|
|
665
|
+
switch (schema.type) {
|
|
666
|
+
case "object":
|
|
667
|
+
checkObject(schema, value, path, issues);
|
|
668
|
+
return;
|
|
669
|
+
case "array": {
|
|
670
|
+
if (!Array.isArray(value)) {
|
|
671
|
+
issues.push(`${name(path)} must be an array`);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
675
|
+
issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
|
|
676
|
+
}
|
|
677
|
+
if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
|
|
678
|
+
issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
|
|
679
|
+
}
|
|
680
|
+
if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
|
|
681
|
+
issues.push(`${name(path)} must not repeat an item`);
|
|
682
|
+
}
|
|
683
|
+
if (schema.items) {
|
|
684
|
+
value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
|
|
685
|
+
}
|
|
686
|
+
break;
|
|
687
|
+
}
|
|
688
|
+
case "string": {
|
|
689
|
+
if (typeof value !== "string") {
|
|
690
|
+
issues.push(`${name(path)} must be a string`);
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
const length = Array.from(value).length;
|
|
694
|
+
if (schema.minLength !== void 0 && length < schema.minLength) {
|
|
695
|
+
issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
|
|
696
|
+
}
|
|
697
|
+
if (schema.maxLength !== void 0 && length > schema.maxLength) {
|
|
698
|
+
issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
|
|
699
|
+
}
|
|
700
|
+
if (schema.format === "uri" && !isHttpUrl(value)) {
|
|
701
|
+
issues.push(`${name(path)} must be an absolute http(s) URL`);
|
|
702
|
+
} else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
|
|
703
|
+
issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
|
|
704
|
+
}
|
|
705
|
+
break;
|
|
706
|
+
}
|
|
707
|
+
case "integer":
|
|
708
|
+
case "number": {
|
|
709
|
+
if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
|
|
710
|
+
issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
714
|
+
issues.push(`${name(path)} must be at least ${schema.minimum}`);
|
|
715
|
+
}
|
|
716
|
+
if (schema.maximum !== void 0 && value > schema.maximum) {
|
|
717
|
+
issues.push(`${name(path)} must be at most ${schema.maximum}`);
|
|
718
|
+
}
|
|
719
|
+
break;
|
|
720
|
+
}
|
|
721
|
+
case "boolean":
|
|
722
|
+
if (typeof value !== "boolean") {
|
|
723
|
+
issues.push(`${name(path)} must be true or false`);
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
break;
|
|
727
|
+
default:
|
|
728
|
+
break;
|
|
729
|
+
}
|
|
730
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
731
|
+
issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
function checkObject(schema, value, path, issues) {
|
|
735
|
+
if (!isPlainObject(value)) {
|
|
736
|
+
issues.push(`${path ? name(path) : "the arguments"} must be an object`);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
const properties = schema.properties ?? {};
|
|
740
|
+
for (const key of schema.required ?? []) {
|
|
741
|
+
if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
|
|
742
|
+
}
|
|
743
|
+
const unknown = [];
|
|
744
|
+
for (const [key, item] of Object.entries(value)) {
|
|
745
|
+
const property = properties[key];
|
|
746
|
+
if (!property) {
|
|
747
|
+
if (schema.additionalProperties === false) unknown.push(key);
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
if (item === void 0 || item === null) continue;
|
|
751
|
+
checkValue(property, item, child(path, key), issues);
|
|
752
|
+
}
|
|
753
|
+
if (unknown.length) {
|
|
754
|
+
const known = Object.keys(properties);
|
|
755
|
+
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(", ")})` : ""));
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
function copyDefault(value) {
|
|
759
|
+
return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
|
|
760
|
+
}
|
|
761
|
+
function validateArguments(schema, args) {
|
|
762
|
+
const input = args === void 0 || args === null ? {} : args;
|
|
763
|
+
if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
|
|
764
|
+
const value = { ...input };
|
|
765
|
+
if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
|
|
766
|
+
const issues = [];
|
|
767
|
+
checkObject(schema, value, "", issues);
|
|
768
|
+
if (issues.length) return { ok: false, issues };
|
|
769
|
+
for (const [key, property] of Object.entries(schema.properties ?? {})) {
|
|
770
|
+
if (value[key] === null) delete value[key];
|
|
771
|
+
if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
|
|
772
|
+
}
|
|
773
|
+
return { ok: true, value };
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// src/core/upload-hosts.ts
|
|
777
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
778
|
+
function uploadHostProblem(entry) {
|
|
779
|
+
if (typeof entry !== "string") return "must be a host name";
|
|
780
|
+
const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
|
|
781
|
+
const labels = name2.split(".");
|
|
782
|
+
if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
|
|
783
|
+
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";
|
|
784
|
+
}
|
|
785
|
+
if (labels.length < 2) return "needs at least two labels, like example.com";
|
|
786
|
+
if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
|
|
787
|
+
return void 0;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
// src/core/connector.ts
|
|
791
|
+
var ANNOTATIONS = {
|
|
792
|
+
read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
793
|
+
create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
794
|
+
update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
795
|
+
delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
796
|
+
write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
|
|
797
|
+
};
|
|
798
|
+
var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
|
|
799
|
+
var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
800
|
+
var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
801
|
+
var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
802
|
+
var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
|
|
803
|
+
var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
804
|
+
var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
|
|
805
|
+
function deepFreeze(value) {
|
|
806
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
807
|
+
Object.freeze(value);
|
|
808
|
+
for (const item of Object.values(value)) deepFreeze(item);
|
|
809
|
+
}
|
|
810
|
+
return value;
|
|
811
|
+
}
|
|
812
|
+
function assertDefinition(def) {
|
|
813
|
+
const problem = (message) => {
|
|
814
|
+
throw new Error(`connector "${def.vendor}": ${message}`);
|
|
815
|
+
};
|
|
816
|
+
if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
|
|
817
|
+
if (!def.label?.trim()) problem("label is required");
|
|
818
|
+
const originFields = def.originFields ?? [];
|
|
819
|
+
if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
|
|
820
|
+
for (const origin of def.origins) {
|
|
821
|
+
let url;
|
|
822
|
+
try {
|
|
823
|
+
url = new URL(origin);
|
|
824
|
+
} catch {
|
|
825
|
+
}
|
|
826
|
+
if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
|
|
827
|
+
}
|
|
828
|
+
for (const name2 of def.credentials) {
|
|
829
|
+
if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
|
|
830
|
+
}
|
|
831
|
+
for (const [index, name2] of originFields.entries()) {
|
|
832
|
+
if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
|
|
833
|
+
if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
|
|
834
|
+
}
|
|
835
|
+
const names = /* @__PURE__ */ new Set();
|
|
836
|
+
for (const tool of def.tools) {
|
|
837
|
+
if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
838
|
+
if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
|
|
839
|
+
names.add(tool.name);
|
|
840
|
+
if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
|
|
841
|
+
if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
|
|
842
|
+
if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
|
|
843
|
+
if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
|
|
844
|
+
problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
for (const tool of def.tools) {
|
|
848
|
+
if (tool.kind === "read") continue;
|
|
849
|
+
const check = def.tools.find((candidate) => candidate.name === tool.check);
|
|
850
|
+
if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
|
|
851
|
+
}
|
|
852
|
+
assertUploadHosts(def, problem);
|
|
853
|
+
assertRequiredCredentials(def, problem);
|
|
854
|
+
assertAccountPickers(def, problem);
|
|
855
|
+
}
|
|
856
|
+
function assertUploadHosts(def, problem) {
|
|
857
|
+
const hosts = def.uploadHosts;
|
|
858
|
+
if (hosts === void 0) return;
|
|
859
|
+
if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
|
|
860
|
+
hosts.forEach((entry, index) => {
|
|
861
|
+
const wrong = uploadHostProblem(entry);
|
|
862
|
+
if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
|
|
863
|
+
if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
function assertRequiredCredentials(def, problem) {
|
|
867
|
+
const required = def.requiredCredentials;
|
|
868
|
+
if (required === void 0) return;
|
|
869
|
+
if (!Array.isArray(required) || !required.length) {
|
|
870
|
+
problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
|
|
871
|
+
}
|
|
872
|
+
required.forEach((list, index) => {
|
|
873
|
+
const which = `requiredCredentials[${index}]`;
|
|
874
|
+
if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
|
|
875
|
+
list.forEach((name2, position) => {
|
|
876
|
+
if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
|
|
877
|
+
if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
|
|
878
|
+
});
|
|
879
|
+
});
|
|
880
|
+
const lists = required;
|
|
881
|
+
lists.forEach((list, index) => {
|
|
882
|
+
const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
|
|
883
|
+
if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
|
|
884
|
+
if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
|
|
885
|
+
problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
|
|
886
|
+
}
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
function isDotPath(value) {
|
|
890
|
+
return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
|
|
891
|
+
}
|
|
892
|
+
function assertAccountPickers(def, problem) {
|
|
893
|
+
const pickers = def.accountPickers;
|
|
894
|
+
if (pickers === void 0) return;
|
|
895
|
+
if (!Array.isArray(pickers)) problem("accountPickers must be a list");
|
|
896
|
+
const keys = /* @__PURE__ */ new Set();
|
|
897
|
+
for (const item of pickers) {
|
|
898
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
|
|
899
|
+
const picker = item;
|
|
900
|
+
const key = picker["key"];
|
|
901
|
+
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}$`);
|
|
902
|
+
if (keys.has(key)) problem(`account picker ${key} is defined twice`);
|
|
903
|
+
keys.add(key);
|
|
904
|
+
const fail = (message) => problem(`account picker ${key}: ${message}`);
|
|
905
|
+
const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
|
|
906
|
+
if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
|
|
907
|
+
const { label, description, multiple, legacyField } = picker;
|
|
908
|
+
if (typeof label !== "string" || !label.trim()) fail("label is required");
|
|
909
|
+
if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
|
|
910
|
+
fail("description, when given, must be a text of 1 to 1024 characters");
|
|
911
|
+
}
|
|
912
|
+
if (typeof multiple !== "boolean") fail("multiple must be true or false");
|
|
913
|
+
const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
|
|
914
|
+
if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
|
|
915
|
+
if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
|
|
916
|
+
for (const field of ["idField", "nameField"]) {
|
|
917
|
+
if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
|
|
918
|
+
}
|
|
919
|
+
if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
|
|
920
|
+
fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
function copyPicker(picker) {
|
|
925
|
+
return {
|
|
926
|
+
key: picker.key,
|
|
927
|
+
label: picker.label,
|
|
928
|
+
...picker.description !== void 0 ? { description: picker.description } : {},
|
|
929
|
+
multiple: picker.multiple,
|
|
930
|
+
tool: picker.tool,
|
|
931
|
+
idField: picker.idField,
|
|
932
|
+
nameField: picker.nameField,
|
|
933
|
+
...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
function result(payload, isError, files = []) {
|
|
937
|
+
return {
|
|
938
|
+
content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
|
|
939
|
+
...isError ? { isError: true } : {}
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
function failure(message, details = {}) {
|
|
943
|
+
return result({ error: message, ...details }, true);
|
|
944
|
+
}
|
|
945
|
+
function trimmed(values) {
|
|
946
|
+
const out = {};
|
|
947
|
+
if (typeof values !== "object" || values === null) return out;
|
|
948
|
+
for (const [key, value] of Object.entries(values)) {
|
|
949
|
+
if (value === void 0 || value === null) continue;
|
|
950
|
+
const text2 = String(value).trim();
|
|
951
|
+
if (text2) out[key] = text2;
|
|
952
|
+
}
|
|
953
|
+
return out;
|
|
954
|
+
}
|
|
955
|
+
function defineConnector(def) {
|
|
956
|
+
assertDefinition(def);
|
|
957
|
+
const { label } = def;
|
|
958
|
+
const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
|
|
959
|
+
const toolList = def.tools.map((tool) => tool.name).join(", ");
|
|
960
|
+
const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
|
|
961
|
+
const required = requiredAlternatives(def);
|
|
962
|
+
const notConnected = (unmet) => {
|
|
963
|
+
const [first] = unmet;
|
|
964
|
+
if (unmet.length === 1 && first) {
|
|
965
|
+
return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
|
|
966
|
+
}
|
|
967
|
+
return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
|
|
968
|
+
};
|
|
969
|
+
const descriptors = def.tools.map((tool) => ({
|
|
970
|
+
name: tool.name,
|
|
971
|
+
title: tool.title,
|
|
972
|
+
description: tool.description,
|
|
973
|
+
inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
|
|
974
|
+
annotations: { ...ANNOTATIONS[tool.kind] }
|
|
975
|
+
}));
|
|
976
|
+
async function call(toolName, args, ctx) {
|
|
977
|
+
const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
|
|
978
|
+
if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
|
|
979
|
+
if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
|
|
980
|
+
const log = (text2) => {
|
|
981
|
+
try {
|
|
982
|
+
ctx.log?.(text2);
|
|
983
|
+
} catch {
|
|
984
|
+
}
|
|
985
|
+
};
|
|
986
|
+
const given = trimmed(ctx.credentials);
|
|
987
|
+
const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
|
|
988
|
+
const has = (name2) => Boolean(credentials[name2]);
|
|
989
|
+
const unmet = unmetAlternatives(required, has);
|
|
990
|
+
if (unmet.length) return failure(notConnected(unmet));
|
|
991
|
+
const complete = required.filter((list) => list.every(has));
|
|
992
|
+
const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
|
|
993
|
+
const fieldOrigins = /* @__PURE__ */ new Map();
|
|
994
|
+
for (const name2 of def.originFields ?? []) {
|
|
995
|
+
if (!given[name2] && !inUse.includes(name2)) continue;
|
|
996
|
+
const site = parseSiteUrl(given[name2] ?? "");
|
|
997
|
+
if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
|
|
998
|
+
fieldOrigins.set(name2, site.origin);
|
|
999
|
+
}
|
|
1000
|
+
const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
|
|
1001
|
+
const parsed = validateArguments(tool.inputSchema, args);
|
|
1002
|
+
if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
|
|
1003
|
+
const frozenCredentials = Object.freeze({ ...credentials });
|
|
1004
|
+
let writeSent = false;
|
|
1005
|
+
const fileLimit = fileLimitOf(ctx);
|
|
1006
|
+
const files = [];
|
|
1007
|
+
let fileBytes = 0;
|
|
1008
|
+
const http = createHttp({
|
|
1009
|
+
vendor: def.vendor,
|
|
1010
|
+
label,
|
|
1011
|
+
tool: tool.name,
|
|
1012
|
+
readOnly: tool.kind === "read",
|
|
1013
|
+
origins,
|
|
1014
|
+
// A 401 names the credentials in use (for a module that needs none, the ones given).
|
|
1015
|
+
credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
|
|
1016
|
+
ctx,
|
|
1017
|
+
authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
|
|
1018
|
+
log,
|
|
1019
|
+
onWriteSent: () => {
|
|
1020
|
+
writeSent = true;
|
|
1021
|
+
}
|
|
1022
|
+
});
|
|
1023
|
+
const helpers = {
|
|
1024
|
+
tool: tool.name,
|
|
1025
|
+
credentials: frozenCredentials,
|
|
1026
|
+
ctx,
|
|
1027
|
+
origins: Object.freeze([...origins]),
|
|
1028
|
+
originOf: (credential) => {
|
|
1029
|
+
const origin = fieldOrigins.get(credential);
|
|
1030
|
+
if (!origin) throw new Error(`${credential} gives no origin in this call`);
|
|
1031
|
+
return origin;
|
|
1032
|
+
},
|
|
1033
|
+
api: http.api,
|
|
1034
|
+
media: http.media,
|
|
1035
|
+
page: (input) => fitPage(input),
|
|
1036
|
+
cursor: (cursor) => decodeCursor(tool.name, cursor),
|
|
1037
|
+
makeCursor: (state) => encodeCursor(tool.name, state),
|
|
1038
|
+
fileLimit: () => fileLimit,
|
|
1039
|
+
file: ({ name: name2, mimeType, bytes }) => {
|
|
1040
|
+
if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
|
|
1041
|
+
const total = fileBytes + bytes.byteLength;
|
|
1042
|
+
if (total > fileLimit) {
|
|
1043
|
+
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.`);
|
|
1044
|
+
}
|
|
1045
|
+
fileBytes = total;
|
|
1046
|
+
const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
|
|
1047
|
+
files.push({ ...info, bytes });
|
|
1048
|
+
return { ...info };
|
|
1049
|
+
},
|
|
1050
|
+
log
|
|
1051
|
+
};
|
|
1052
|
+
try {
|
|
1053
|
+
const data = await tool.run(parsed.value, helpers);
|
|
1054
|
+
const fitted = shrinkToFit(data ?? {});
|
|
1055
|
+
if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
|
|
1056
|
+
const payload = fitted.value;
|
|
1057
|
+
return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
|
|
1058
|
+
} catch (error) {
|
|
1059
|
+
if (error instanceof OutcomeUnknown) {
|
|
1060
|
+
return result({
|
|
1061
|
+
outcome: "unknown",
|
|
1062
|
+
check: tool.check,
|
|
1063
|
+
error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
|
|
1064
|
+
}, true);
|
|
1065
|
+
}
|
|
1066
|
+
if (error instanceof ToolFailure) return failure(error.message, error.details);
|
|
1067
|
+
log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
|
|
1068
|
+
if (writeSent) {
|
|
1069
|
+
return result({
|
|
1070
|
+
outcome: "unknown",
|
|
1071
|
+
check: tool.check,
|
|
1072
|
+
error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
|
|
1073
|
+
}, true);
|
|
1074
|
+
}
|
|
1075
|
+
return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
return deepFreeze({
|
|
1079
|
+
vendor: def.vendor,
|
|
1080
|
+
origins: [...def.origins],
|
|
1081
|
+
originFields: [...def.originFields ?? []],
|
|
1082
|
+
uploadHosts: [...def.uploadHosts ?? []],
|
|
1083
|
+
credentials: [...def.credentials],
|
|
1084
|
+
requiredCredentials: required.map((list) => [...list]),
|
|
1085
|
+
accountPickers: (def.accountPickers ?? []).map(copyPicker),
|
|
1086
|
+
tools: descriptors,
|
|
1087
|
+
call
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// src/core/jwt.ts
|
|
1092
|
+
var TOKEN_EARLY_MS = 5 * 60 * 1e3;
|
|
1093
|
+
|
|
1094
|
+
// src/vendors/google-ads/identifiers.ts
|
|
1095
|
+
var MAX_MATCH_IDENTIFIERS = 1e4;
|
|
1096
|
+
function normalizeEmail(raw) {
|
|
1097
|
+
const email = raw.trim().toLowerCase();
|
|
1098
|
+
const at = email.lastIndexOf("@");
|
|
1099
|
+
if (at <= 0 || at === email.length - 1) return void 0;
|
|
1100
|
+
let name2 = email.slice(0, at);
|
|
1101
|
+
const domain = email.slice(at + 1);
|
|
1102
|
+
if (!/^[^\s@]+$/.test(name2) || !/^[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}$/.test(domain)) return void 0;
|
|
1103
|
+
if (domain === "gmail.com" || domain === "googlemail.com") {
|
|
1104
|
+
const plus = name2.indexOf("+");
|
|
1105
|
+
name2 = (plus === -1 ? name2 : name2.slice(0, plus)).replace(/\./g, "");
|
|
1106
|
+
}
|
|
1107
|
+
return name2 ? `${name2}@${domain}` : void 0;
|
|
1108
|
+
}
|
|
1109
|
+
function normalizePhone(raw) {
|
|
1110
|
+
const text2 = raw.trim();
|
|
1111
|
+
if (!text2.startsWith("+")) return void 0;
|
|
1112
|
+
const number = text2.slice(1).replace(/[\s().-]/g, "");
|
|
1113
|
+
return /^[1-9][0-9]{7,14}$/.test(number) ? `+${number}` : void 0;
|
|
1114
|
+
}
|
|
1115
|
+
async function hashIdentifiers(args) {
|
|
1116
|
+
const result2 = { emails: [], phones: [], skippedEmails: [], skippedPhones: [] };
|
|
1117
|
+
for (const [index, email] of (args.emails ?? []).entries()) {
|
|
1118
|
+
const normalized = normalizeEmail(email);
|
|
1119
|
+
if (normalized) result2.emails.push(await sha256Hex(normalized));
|
|
1120
|
+
else result2.skippedEmails.push(index);
|
|
1121
|
+
}
|
|
1122
|
+
for (const [index, phone] of (args.phones ?? []).entries()) {
|
|
1123
|
+
const normalized = normalizePhone(phone);
|
|
1124
|
+
if (normalized) result2.phones.push(await sha256Hex(normalized));
|
|
1125
|
+
else result2.skippedPhones.push(index);
|
|
1126
|
+
}
|
|
1127
|
+
result2.emails.push(...(args.hashed_emails ?? []).map((hash) => hash.toLowerCase()));
|
|
1128
|
+
result2.phones.push(...(args.hashed_phones ?? []).map((hash) => hash.toLowerCase()));
|
|
1129
|
+
return result2;
|
|
1130
|
+
}
|
|
1131
|
+
function identifierCount(args) {
|
|
1132
|
+
return (args.emails?.length ?? 0) + (args.phones?.length ?? 0) + (args.hashed_emails?.length ?? 0) + (args.hashed_phones?.length ?? 0);
|
|
1133
|
+
}
|
|
1134
|
+
function skippedSummary(indices) {
|
|
1135
|
+
return indices.length ? { count: indices.length, first_indices: indices.slice(0, 100) } : void 0;
|
|
1136
|
+
}
|
|
1137
|
+
var IDENTIFIER_LISTS = {
|
|
1138
|
+
emails: { type: "array", maxItems: MAX_MATCH_IDENTIFIERS, items: { type: "string", maxLength: 320 }, description: "Email addresses in plain text; they are normalized and hashed with SHA-256 before anything is sent." },
|
|
1139
|
+
phones: { type: "array", maxItems: MAX_MATCH_IDENTIFIERS, items: { type: "string", maxLength: 40 }, description: 'Phone numbers in E.164 form with the country code, e.g. "+15551234567"; hashed with SHA-256 before sending.' }
|
|
1140
|
+
};
|
|
1141
|
+
var SHA256_HEX = { type: "string", pattern: "^[A-Fa-f0-9]{64}$" };
|
|
1142
|
+
var HASHED_LISTS = {
|
|
1143
|
+
hashed_emails: { type: "array", maxItems: MAX_MATCH_IDENTIFIERS, items: SHA256_HEX, description: "Emails already normalized and hashed with SHA-256 (hex)." },
|
|
1144
|
+
hashed_phones: { type: "array", maxItems: MAX_MATCH_IDENTIFIERS, items: SHA256_HEX, description: "E.164 phone numbers already hashed with SHA-256 (hex)." }
|
|
1145
|
+
};
|
|
1146
|
+
var CONSENT = {
|
|
1147
|
+
ad_user_data_consent: { type: "string", enum: ["GRANTED", "DENIED"], description: "The people's consent to sending their data to Google for ads, required for people in the EEA." },
|
|
1148
|
+
ad_personalization_consent: { type: "string", enum: ["GRANTED", "DENIED"], description: "Their consent to personalized advertising, required for people in the EEA." }
|
|
1149
|
+
};
|
|
1150
|
+
|
|
1151
|
+
// src/vendors/google-ads/shared.ts
|
|
1152
|
+
var VERSION = "v26";
|
|
1153
|
+
var LABEL2 = "Google Ads";
|
|
1154
|
+
var ACCOUNT = "Google Ads account";
|
|
1155
|
+
var ADS_ORIGIN = "https://googleads.googleapis.com";
|
|
1156
|
+
var MAX_SEARCH_BYTES = 8 * 1024 * 1024;
|
|
1157
|
+
var CUSTOMER_ID = {
|
|
1158
|
+
type: "string",
|
|
1159
|
+
pattern: "^[0-9]{3}-?[0-9]{3}-?[0-9]{4}$",
|
|
1160
|
+
description: 'The 10-digit Google Ads account ID, with or without dashes, e.g. "1234567890" (list_customers lists them).'
|
|
1161
|
+
};
|
|
1162
|
+
var LOGIN_CUSTOMER_ID = {
|
|
1163
|
+
type: "string",
|
|
1164
|
+
pattern: "^[0-9]{3}-?[0-9]{3}-?[0-9]{4}$",
|
|
1165
|
+
description: "The manager account (MCC) the account is reached through, sent as login-customer-id. Default: the connection's manager account ID if set, else the manager account the connector finds above the account (list_customers gives it as login_customer_id)."
|
|
1166
|
+
};
|
|
1167
|
+
var CURSOR = { type: "string", description: "nextCursor from the previous result, with the same other arguments." };
|
|
1168
|
+
var ERRORS = {
|
|
1169
|
+
403: "Google Ads refused the request: the Google account has no access to this account, the account is reached through a manager account (give login_customer_id), or the Google Cloud project of the OAuth client has no Google Ads API access to production accounts yet"
|
|
1170
|
+
};
|
|
1171
|
+
var SEARCH_ERRORS = {
|
|
1172
|
+
...ERRORS,
|
|
1173
|
+
400: `Google Ads did not accept the query: check the GAQL syntax, the field names (snake_case, e.g. metrics.cost_micros) and that the fields can be selected together FROM that resource (api_get /${VERSION}/googleAdsFields/<field> tells whether a field exists and what it can be selected with)`
|
|
1174
|
+
};
|
|
1175
|
+
function compact(value) {
|
|
1176
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
|
|
1177
|
+
}
|
|
1178
|
+
function digits(value) {
|
|
1179
|
+
return value.replace(/[^0-9]/g, "");
|
|
1180
|
+
}
|
|
1181
|
+
function chosenCustomer(h, value) {
|
|
1182
|
+
const id = digits(value);
|
|
1183
|
+
requireAccounts(h.ctx.accounts, "customers", id, ACCOUNT);
|
|
1184
|
+
return id;
|
|
1185
|
+
}
|
|
1186
|
+
function snake(key) {
|
|
1187
|
+
return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
1188
|
+
}
|
|
1189
|
+
function snakeDeep(value) {
|
|
1190
|
+
if (Array.isArray(value)) return value.map(snakeDeep);
|
|
1191
|
+
if (value && typeof value === "object") {
|
|
1192
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [snake(key), snakeDeep(item)]));
|
|
1193
|
+
}
|
|
1194
|
+
return typeof value === "string" ? truncate(value, 2e3) : value;
|
|
1195
|
+
}
|
|
1196
|
+
function loginHeaders(login) {
|
|
1197
|
+
return login ? { "login-customer-id": digits(login) } : {};
|
|
1198
|
+
}
|
|
1199
|
+
async function searchPage(h, customer, query, login, pageToken) {
|
|
1200
|
+
const { data } = await h.api({
|
|
1201
|
+
method: "POST",
|
|
1202
|
+
path: `/${VERSION}/customers/${customer}/googleAds:search`,
|
|
1203
|
+
headers: loginHeaders(login),
|
|
1204
|
+
json: compact({ query, pageToken }),
|
|
1205
|
+
safe: true,
|
|
1206
|
+
maxBytes: MAX_SEARCH_BYTES,
|
|
1207
|
+
errors: SEARCH_ERRORS
|
|
1208
|
+
});
|
|
1209
|
+
return data;
|
|
1210
|
+
}
|
|
1211
|
+
function accessibleIds(data) {
|
|
1212
|
+
return [...new Set((Array.isArray(data?.resourceNames) ? data.resourceNames : []).map((name2) => /^customers\/([0-9]+)$/.exec(String(name2))?.[1]).filter((id) => Boolean(id)))].sort();
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
// src/vendors/google-ads/login.ts
|
|
1216
|
+
var PATHS_TTL_MS = 60 * 60 * 1e3;
|
|
1217
|
+
var MAX_SESSIONS = 64;
|
|
1218
|
+
var MAX_PATHS = 2e3;
|
|
1219
|
+
var MAX_MANAGERS_ASKED = 25;
|
|
1220
|
+
var sessions = /* @__PURE__ */ new Map();
|
|
1221
|
+
async function pathsFor(h) {
|
|
1222
|
+
const key = await sha256Hex(`login paths
|
|
1223
|
+
${h.credentials["access_token"] ?? ""}`);
|
|
1224
|
+
const now = Date.now();
|
|
1225
|
+
const cached = sessions.get(key);
|
|
1226
|
+
if (cached && cached.expiresAt > now) return cached;
|
|
1227
|
+
sessions.delete(key);
|
|
1228
|
+
for (const [other, entry] of sessions) if (entry.expiresAt <= now) sessions.delete(other);
|
|
1229
|
+
while (sessions.size >= MAX_SESSIONS) {
|
|
1230
|
+
const oldest = sessions.keys().next().value;
|
|
1231
|
+
if (oldest === void 0) break;
|
|
1232
|
+
sessions.delete(oldest);
|
|
1233
|
+
}
|
|
1234
|
+
const paths = { expiresAt: now + PATHS_TTL_MS, logins: /* @__PURE__ */ new Map(), managers: /* @__PURE__ */ new Map() };
|
|
1235
|
+
sessions.set(key, paths);
|
|
1236
|
+
return paths;
|
|
1237
|
+
}
|
|
1238
|
+
function remember(paths, customer, login) {
|
|
1239
|
+
paths.logins.delete(customer);
|
|
1240
|
+
while (paths.logins.size >= MAX_PATHS) {
|
|
1241
|
+
const oldest = paths.logins.keys().next().value;
|
|
1242
|
+
if (oldest === void 0) break;
|
|
1243
|
+
paths.logins.delete(oldest);
|
|
1244
|
+
}
|
|
1245
|
+
paths.logins.set(customer, login);
|
|
1246
|
+
}
|
|
1247
|
+
async function rememberHierarchy(h, accessible, managers, clients) {
|
|
1248
|
+
const paths = await pathsFor(h);
|
|
1249
|
+
paths.accessible = accessible;
|
|
1250
|
+
for (const id of accessible) remember(paths, id, "");
|
|
1251
|
+
for (const [id, isManager] of managers) paths.managers.set(id, isManager);
|
|
1252
|
+
for (const [client, manager] of clients) if (!paths.logins.has(client)) remember(paths, client, manager);
|
|
1253
|
+
}
|
|
1254
|
+
async function findManager(h, paths, customer) {
|
|
1255
|
+
if (!paths.accessible) {
|
|
1256
|
+
const { data } = await h.api({ path: `/${VERSION}/customers:listAccessibleCustomers`, errors: ERRORS });
|
|
1257
|
+
paths.accessible = accessibleIds(data);
|
|
1258
|
+
for (const id of paths.accessible) if (!paths.logins.has(id)) remember(paths, id, "");
|
|
1259
|
+
}
|
|
1260
|
+
if (paths.accessible.includes(customer)) return void 0;
|
|
1261
|
+
const candidates = paths.accessible.filter((id) => paths.managers.get(id) !== false).sort((a, b) => Number(paths.managers.get(b) === true) - Number(paths.managers.get(a) === true)).slice(0, MAX_MANAGERS_ASKED);
|
|
1262
|
+
const query = `SELECT customer_client.id FROM customer_client WHERE customer_client.id = ${customer}`;
|
|
1263
|
+
for (const manager of candidates) {
|
|
1264
|
+
let rows;
|
|
1265
|
+
try {
|
|
1266
|
+
const page = await searchPage(h, manager, query, manager);
|
|
1267
|
+
rows = Array.isArray(page?.results) ? page.results : [];
|
|
1268
|
+
} catch (error) {
|
|
1269
|
+
const status = error instanceof ToolFailure ? error.details.status : void 0;
|
|
1270
|
+
if (status === 400 || status === 403 || status === 404 || status !== void 0 && status >= 500) continue;
|
|
1271
|
+
throw error;
|
|
1272
|
+
}
|
|
1273
|
+
if (rows.length) return manager;
|
|
1274
|
+
}
|
|
1275
|
+
return void 0;
|
|
1276
|
+
}
|
|
1277
|
+
async function loginFor(h, customer, explicit) {
|
|
1278
|
+
if (explicit) return digits(explicit);
|
|
1279
|
+
const manager = h.credentials["managercustomerid"];
|
|
1280
|
+
if (manager) return manager;
|
|
1281
|
+
if (!customer) return void 0;
|
|
1282
|
+
const paths = await pathsFor(h);
|
|
1283
|
+
const known = paths.logins.get(customer);
|
|
1284
|
+
if (known !== void 0) return known || void 0;
|
|
1285
|
+
const found = await findManager(h, paths, customer);
|
|
1286
|
+
remember(paths, customer, found ?? "");
|
|
1287
|
+
return found;
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
// src/vendors/google-ads/data-manager.ts
|
|
1291
|
+
var DATA_MANAGER = "https://datamanager.googleapis.com";
|
|
1292
|
+
var DM_VERSION = "v1";
|
|
1293
|
+
var MAX_EVENTS = 2e3;
|
|
1294
|
+
var MAX_EVENT_IDENTIFIERS = 10;
|
|
1295
|
+
var MAX_WARNINGS = 20;
|
|
1296
|
+
var MAX_COUNTS = 20;
|
|
1297
|
+
var MAX_INDICES = 20;
|
|
1298
|
+
var EVENT_SOURCES = ["WEB", "APP", "IN_STORE", "PHONE", "MESSAGE", "OTHER"];
|
|
1299
|
+
var RFC3339 = "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,9})?(Z|[+-][0-9]{2}:[0-9]{2})$";
|
|
1300
|
+
var ACCESS = "Google refused the request: the sign-in needs the scope https://www.googleapis.com/auth/datamanager, the Data Manager API must be enabled in the Google Cloud project of the OAuth client, and the Google account needs access to this Google Ads account (for one reached through a manager account, give login_customer_id)";
|
|
1301
|
+
var AUDIENCE_ERRORS = {
|
|
1302
|
+
400: "Google did not accept the audience request: the list must be a Customer Match list of contact information in this account (search gives its ID as user_list.id); validate_only: true has a request checked without taking anyone",
|
|
1303
|
+
403: ACCESS,
|
|
1304
|
+
404: "Google found no such Customer Match list in this account"
|
|
1305
|
+
};
|
|
1306
|
+
var EVENT_ERRORS = {
|
|
1307
|
+
400: "Google did not accept the conversions: the conversion action must be one of this account whose source is Website (Import from clicks), times must be RFC 3339 with a time zone and currencies 3-letter codes; validate_only: true has them checked without taking any",
|
|
1308
|
+
403: ACCESS,
|
|
1309
|
+
404: "Google found no such conversion action in this account"
|
|
1310
|
+
};
|
|
1311
|
+
var STATUS_ERRORS = {
|
|
1312
|
+
400: "Google did not accept the request ID: pass the request_id an upload returned, unchanged",
|
|
1313
|
+
403: "Google refused the request: the sign-in needs the scope https://www.googleapis.com/auth/datamanager, and only the Google account that sent an upload can read its status",
|
|
1314
|
+
404: "Google found no upload with this request ID"
|
|
1315
|
+
};
|
|
1316
|
+
var USER_LIST = {
|
|
1317
|
+
type: "string",
|
|
1318
|
+
pattern: "^(customers/[0-9]{10}/userLists/)?[0-9]{1,20}$",
|
|
1319
|
+
description: "The Customer Match list's ID, or its resource name customers/{customer_id}/userLists/{id} (search lists them: SELECT user_list.id, user_list.name FROM user_list WHERE user_list.type = CRM_BASED)."
|
|
1320
|
+
};
|
|
1321
|
+
var VALIDATE_ONLY = { type: "boolean", description: "Have Google check the request without taking the data." };
|
|
1322
|
+
var CLICK_ID = { type: "string", minLength: 1, maxLength: 1e3 };
|
|
1323
|
+
function text(value, max) {
|
|
1324
|
+
return typeof value === "string" && value ? truncate(value, max) : void 0;
|
|
1325
|
+
}
|
|
1326
|
+
function ownId(value, customer, collection, what) {
|
|
1327
|
+
const match = new RegExp(`^customers/([0-9]{10})/${collection}/([0-9]+)$`).exec(value);
|
|
1328
|
+
if (match && match[1] !== customer) throw new ToolFailure(`The ${what} belongs to another account than ${customer}. Nothing was sent.`);
|
|
1329
|
+
return match ? match[2] : value;
|
|
1330
|
+
}
|
|
1331
|
+
async function destination(h, customer, explicitLogin, productDestinationId) {
|
|
1332
|
+
let login;
|
|
1333
|
+
try {
|
|
1334
|
+
login = await loginFor(h, customer, explicitLogin);
|
|
1335
|
+
} catch (error) {
|
|
1336
|
+
if (!(error instanceof ToolFailure) || error.details.status === void 0) throw error;
|
|
1337
|
+
}
|
|
1338
|
+
return compact({
|
|
1339
|
+
operatingAccount: { accountType: "GOOGLE_ADS", accountId: customer },
|
|
1340
|
+
loginAccount: login && login !== customer ? { accountType: "GOOGLE_ADS", accountId: login } : void 0,
|
|
1341
|
+
productDestinationId
|
|
1342
|
+
});
|
|
1343
|
+
}
|
|
1344
|
+
function consentOf(args) {
|
|
1345
|
+
const status = (value) => value ? `CONSENT_${value}` : void 0;
|
|
1346
|
+
const consent = compact({ adUserData: status(args.ad_user_data_consent), adPersonalization: status(args.ad_personalization_consent) });
|
|
1347
|
+
return Object.keys(consent).length ? consent : void 0;
|
|
1348
|
+
}
|
|
1349
|
+
async function checkedIdentifiers(args) {
|
|
1350
|
+
const total = identifierCount(args);
|
|
1351
|
+
if (!total) throw new ToolFailure("Give at least one email or phone number. Nothing was sent.");
|
|
1352
|
+
if (total > MAX_MATCH_IDENTIFIERS) throw new ToolFailure(`Give at most ${MAX_MATCH_IDENTIFIERS} emails and phone numbers per call (got ${total}). Nothing was sent.`);
|
|
1353
|
+
const hashed = await hashIdentifiers(args);
|
|
1354
|
+
if (!hashed.emails.length && !hashed.phones.length) {
|
|
1355
|
+
throw new ToolFailure('None of the emails or phone numbers is valid (phones need E.164 form, e.g. "+15551234567"). Nothing was sent.');
|
|
1356
|
+
}
|
|
1357
|
+
return hashed;
|
|
1358
|
+
}
|
|
1359
|
+
function membersOf(hashed) {
|
|
1360
|
+
const member = (identifier) => ({ compositeData: { userData: { userIdentifiers: [identifier] } } });
|
|
1361
|
+
return [...hashed.emails.map((hash) => member({ emailAddress: hash })), ...hashed.phones.map((hash) => member({ phoneNumber: hash }))];
|
|
1362
|
+
}
|
|
1363
|
+
function sentCounts(args, hashed) {
|
|
1364
|
+
const counts = {
|
|
1365
|
+
emails: (args.emails?.length ?? 0) - hashed.skippedEmails.length,
|
|
1366
|
+
hashed_emails: args.hashed_emails?.length ?? 0,
|
|
1367
|
+
phones: (args.phones?.length ?? 0) - hashed.skippedPhones.length,
|
|
1368
|
+
hashed_phones: args.hashed_phones?.length ?? 0
|
|
1369
|
+
};
|
|
1370
|
+
return Object.fromEntries(Object.entries(counts).filter(([, count]) => count > 0));
|
|
1371
|
+
}
|
|
1372
|
+
function warningsOf(data) {
|
|
1373
|
+
const list = Array.isArray(data?.fieldWarnings) ? data.fieldWarnings : [];
|
|
1374
|
+
if (!list.length) return {};
|
|
1375
|
+
return {
|
|
1376
|
+
warnings: list.slice(0, MAX_WARNINGS).map((item) => compact({ field: text(item?.field, 200), reason: text(item?.reason, 120), description: text(item?.description, 200) })),
|
|
1377
|
+
...list.length > MAX_WARNINGS ? { warnings_total: list.length } : {}
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
async function ingest(h, path, body, validateOnly, errors, again) {
|
|
1381
|
+
try {
|
|
1382
|
+
const { data } = await h.api({ method: "POST", origin: DATA_MANAGER, path: `/${DM_VERSION}/${path}`, json: body, write: !validateOnly, errors });
|
|
1383
|
+
return data;
|
|
1384
|
+
} catch (error) {
|
|
1385
|
+
if (error instanceof OutcomeUnknown) throw new OutcomeUnknown(`${error.message} ${again}`);
|
|
1386
|
+
throw error;
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
function audienceTool(mode) {
|
|
1390
|
+
const adding = mode === "add";
|
|
1391
|
+
return {
|
|
1392
|
+
name: adding ? "add_audience_members" : "remove_audience_members",
|
|
1393
|
+
kind: adding ? "create" : "delete",
|
|
1394
|
+
check: "search",
|
|
1395
|
+
title: adding ? "Add Customer Match members (Data Manager API)" : "Remove Customer Match members (Data Manager API)",
|
|
1396
|
+
description: adding ? "Adds people to a Customer Match list of one account by email or phone through Google's Data Manager API, which takes Customer Match data from every Google Cloud project (upload_customer_match only works for projects Google allowlisted): normalizes and hashes them with SHA-256 here, then sends up to 10,000 in one request. Someone already in the list is not added twice. Matching takes up to 48 hours, and a list needs at least 100 members to be used for targeting. Needs the scope https://www.googleapis.com/auth/datamanager and the Data Manager API enabled in the project. Returns a request_id for get_upload_status." : "Removes people from a Customer Match list of one account by email or phone through Google's Data Manager API, open to every Google Cloud project: normalizes and hashes them with SHA-256 here, then sends up to 10,000 in one request. Removing someone who is not in the list changes nothing. Needs the scope https://www.googleapis.com/auth/datamanager and the Data Manager API enabled in the project. Returns a request_id for get_upload_status.",
|
|
1397
|
+
inputSchema: {
|
|
1398
|
+
type: "object",
|
|
1399
|
+
properties: {
|
|
1400
|
+
customer_id: CUSTOMER_ID,
|
|
1401
|
+
login_customer_id: LOGIN_CUSTOMER_ID,
|
|
1402
|
+
user_list: USER_LIST,
|
|
1403
|
+
...IDENTIFIER_LISTS,
|
|
1404
|
+
...HASHED_LISTS,
|
|
1405
|
+
...adding ? {
|
|
1406
|
+
...CONSENT,
|
|
1407
|
+
accept_customer_match_terms: {
|
|
1408
|
+
type: "boolean",
|
|
1409
|
+
enum: [true],
|
|
1410
|
+
description: "true confirms that the account accepts Google's Customer Match terms (https://support.google.com/adspolicy/answer/6299717), which Google requires with every upload. Pass it only when the advertiser has accepted them."
|
|
1411
|
+
}
|
|
1412
|
+
} : {},
|
|
1413
|
+
validate_only: VALIDATE_ONLY
|
|
1414
|
+
},
|
|
1415
|
+
required: adding ? ["customer_id", "user_list", "accept_customer_match_terms"] : ["customer_id", "user_list"],
|
|
1416
|
+
additionalProperties: false
|
|
1417
|
+
},
|
|
1418
|
+
async run(args, h) {
|
|
1419
|
+
const id = chosenCustomer(h, args.customer_id);
|
|
1420
|
+
const list = ownId(args.user_list, id, "userLists", "user list");
|
|
1421
|
+
const hashed = await checkedIdentifiers(args);
|
|
1422
|
+
const body = compact({
|
|
1423
|
+
destinations: [await destination(h, id, args.login_customer_id, list)],
|
|
1424
|
+
audienceMembers: membersOf(hashed),
|
|
1425
|
+
consent: adding ? consentOf(args) : void 0,
|
|
1426
|
+
encoding: "HEX",
|
|
1427
|
+
termsOfService: adding ? { customerMatchTermsOfServiceStatus: "ACCEPTED" } : void 0,
|
|
1428
|
+
validateOnly: args.validate_only ? true : void 0
|
|
1429
|
+
});
|
|
1430
|
+
const data = await ingest(
|
|
1431
|
+
h,
|
|
1432
|
+
adding ? "audienceMembers:ingest" : "audienceMembers:remove",
|
|
1433
|
+
body,
|
|
1434
|
+
args.validate_only,
|
|
1435
|
+
AUDIENCE_ERRORS,
|
|
1436
|
+
adding ? "Customer Match keeps each person once, so sending the same people again adds no one twice." : "Removing the same people again changes nothing more."
|
|
1437
|
+
);
|
|
1438
|
+
return compact({
|
|
1439
|
+
customer_id: id,
|
|
1440
|
+
user_list: `customers/${id}/userLists/${list}`,
|
|
1441
|
+
request_id: text(data?.requestId, 200),
|
|
1442
|
+
validate_only: args.validate_only ? true : void 0,
|
|
1443
|
+
valid: args.validate_only ? true : void 0,
|
|
1444
|
+
members_sent: hashed.emails.length + hashed.phones.length,
|
|
1445
|
+
sent: sentCounts(args, hashed),
|
|
1446
|
+
skipped_emails: skippedSummary(hashed.skippedEmails),
|
|
1447
|
+
skipped_phones: skippedSummary(hashed.skippedPhones),
|
|
1448
|
+
...warningsOf(data),
|
|
1449
|
+
note: args.validate_only ? "Google checked the request and took no one." : `Google ${adding ? "matches the people" : "removes them"} in the background${adding ? ", within 48 hours" : ""}: get_upload_status with request_id tells how many it took and why any were not.`
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
var CONVERSION = {
|
|
1455
|
+
type: "object",
|
|
1456
|
+
properties: {
|
|
1457
|
+
conversion_time: { type: "string", pattern: RFC3339, description: 'When it happened, RFC 3339 with a time zone, e.g. "2026-11-20T14:05:00-05:00".' },
|
|
1458
|
+
gclid: { ...CLICK_ID, description: "The Google click ID of the ad click." },
|
|
1459
|
+
gbraid: { ...CLICK_ID, description: "The click ID of an app click from iOS 14 or later." },
|
|
1460
|
+
wbraid: { ...CLICK_ID, description: "The click ID of a web click from iOS 14 or later." },
|
|
1461
|
+
session_attributes: { type: "string", minLength: 1, maxLength: 8e3, description: "The encoded session attributes string captured with the form, when no click ID is known." },
|
|
1462
|
+
emails: { ...IDENTIFIER_LISTS.emails, maxItems: MAX_EVENT_IDENTIFIERS, description: "The person's emails in plain text (hashed here)." },
|
|
1463
|
+
phones: { ...IDENTIFIER_LISTS.phones, maxItems: MAX_EVENT_IDENTIFIERS, description: "The person's phone numbers in E.164 form (hashed here)." },
|
|
1464
|
+
hashed_emails: { ...HASHED_LISTS.hashed_emails, maxItems: MAX_EVENT_IDENTIFIERS },
|
|
1465
|
+
hashed_phones: { ...HASHED_LISTS.hashed_phones, maxItems: MAX_EVENT_IDENTIFIERS },
|
|
1466
|
+
value: { type: "number", minimum: 0, description: "The conversion value, in currency units (not micros)." },
|
|
1467
|
+
currency: { type: "string", pattern: "^[A-Za-z]{3}$", description: `The value's 3-letter currency code, e.g. "USD" (default: the conversion action's).` },
|
|
1468
|
+
transaction_id: { type: "string", minLength: 1, maxLength: 128, description: "The order or lead ID: Google Ads counts one conversion per ID and action, so a repeat updates it instead of adding one." },
|
|
1469
|
+
event_source: { type: "string", enum: EVENT_SOURCES, description: "Where this one happened, if not event_source." }
|
|
1470
|
+
},
|
|
1471
|
+
required: ["conversion_time"],
|
|
1472
|
+
additionalProperties: false
|
|
1473
|
+
};
|
|
1474
|
+
var uploadConversions = {
|
|
1475
|
+
name: "upload_conversions",
|
|
1476
|
+
kind: "write",
|
|
1477
|
+
check: "search",
|
|
1478
|
+
title: "Upload offline conversions (Data Manager API)",
|
|
1479
|
+
description: "Sends offline conversions to a conversion action of one account through Google's Data Manager API, which takes them from every Google Cloud project (the Google Ads API's uploadClickConversions only works for projects Google allowlisted): click conversions by gclid, gbraid or wbraid, and enhanced conversions for leads by email or phone, normalized and hashed with SHA-256 here. Up to 2,000 per call, each with its time, value, currency and transaction_id. A conversion whose transaction_id was sent before updates that one. The action's source must be Website (Import from clicks). Needs the scope https://www.googleapis.com/auth/datamanager and the Data Manager API enabled. Returns a request_id for get_upload_status.",
|
|
1480
|
+
inputSchema: {
|
|
1481
|
+
type: "object",
|
|
1482
|
+
properties: {
|
|
1483
|
+
customer_id: CUSTOMER_ID,
|
|
1484
|
+
login_customer_id: LOGIN_CUSTOMER_ID,
|
|
1485
|
+
conversion_action: {
|
|
1486
|
+
type: "string",
|
|
1487
|
+
pattern: "^(customers/[0-9]{10}/conversionActions/)?[0-9]{1,20}$",
|
|
1488
|
+
description: "The conversion action's ID or resource name customers/{customer_id}/conversionActions/{id} (search lists them: SELECT conversion_action.id, conversion_action.name FROM conversion_action WHERE conversion_action.type = UPLOAD_CLICKS)."
|
|
1489
|
+
},
|
|
1490
|
+
conversions: {
|
|
1491
|
+
type: "array",
|
|
1492
|
+
minItems: 1,
|
|
1493
|
+
maxItems: MAX_EVENTS,
|
|
1494
|
+
items: CONVERSION,
|
|
1495
|
+
description: "The conversions, each with conversion_time and at least one of gclid, gbraid, wbraid, session_attributes, an email or a phone (at most 10 emails and phones each)."
|
|
1496
|
+
},
|
|
1497
|
+
event_source: { type: "string", enum: EVENT_SOURCES, default: "WEB", description: "Where the conversions happened: WEB (default), APP, IN_STORE, PHONE, MESSAGE or OTHER." },
|
|
1498
|
+
...CONSENT,
|
|
1499
|
+
validate_only: VALIDATE_ONLY
|
|
1500
|
+
},
|
|
1501
|
+
required: ["customer_id", "conversion_action", "conversions"],
|
|
1502
|
+
additionalProperties: false
|
|
1503
|
+
},
|
|
1504
|
+
async run(args, h) {
|
|
1505
|
+
const id = chosenCustomer(h, args.customer_id);
|
|
1506
|
+
const action = ownId(args.conversion_action, id, "conversionActions", "conversion action");
|
|
1507
|
+
const events = [];
|
|
1508
|
+
const skipped = [];
|
|
1509
|
+
for (const [index, conversion] of args.conversions.entries()) {
|
|
1510
|
+
const given = identifierCount(conversion);
|
|
1511
|
+
if (given > MAX_EVENT_IDENTIFIERS) {
|
|
1512
|
+
throw new ToolFailure(`Conversion ${index} has ${given} emails and phone numbers; Google takes at most ${MAX_EVENT_IDENTIFIERS} per conversion. Nothing was sent.`);
|
|
1513
|
+
}
|
|
1514
|
+
const hashed = await hashIdentifiers(conversion);
|
|
1515
|
+
const identifiers = [...hashed.emails.map((hash) => ({ emailAddress: hash })), ...hashed.phones.map((hash) => ({ phoneNumber: hash }))];
|
|
1516
|
+
const adIdentifiers = compact({ gclid: conversion.gclid, gbraid: conversion.gbraid, wbraid: conversion.wbraid, sessionAttributes: conversion.session_attributes });
|
|
1517
|
+
if (!identifiers.length && !Object.keys(adIdentifiers).length) {
|
|
1518
|
+
throw new ToolFailure(`Conversion ${index} has no gclid, gbraid, wbraid, session_attributes, or valid email or phone number, so Google could not match it. Nothing was sent.`);
|
|
1519
|
+
}
|
|
1520
|
+
if (hashed.skippedEmails.length || hashed.skippedPhones.length) {
|
|
1521
|
+
skipped.push(compact({
|
|
1522
|
+
conversion: index,
|
|
1523
|
+
emails: hashed.skippedEmails.length ? hashed.skippedEmails : void 0,
|
|
1524
|
+
phones: hashed.skippedPhones.length ? hashed.skippedPhones : void 0
|
|
1525
|
+
}));
|
|
1526
|
+
}
|
|
1527
|
+
events.push(compact({
|
|
1528
|
+
eventTimestamp: conversion.conversion_time,
|
|
1529
|
+
transactionId: conversion.transaction_id,
|
|
1530
|
+
eventSource: conversion.event_source ?? args.event_source,
|
|
1531
|
+
adIdentifiers: Object.keys(adIdentifiers).length ? adIdentifiers : void 0,
|
|
1532
|
+
userData: identifiers.length ? { userIdentifiers: identifiers } : void 0,
|
|
1533
|
+
conversionValue: conversion.value,
|
|
1534
|
+
currency: conversion.currency?.toUpperCase()
|
|
1535
|
+
}));
|
|
1536
|
+
}
|
|
1537
|
+
const body = compact({
|
|
1538
|
+
destinations: [await destination(h, id, args.login_customer_id, action)],
|
|
1539
|
+
events,
|
|
1540
|
+
consent: consentOf(args),
|
|
1541
|
+
encoding: "HEX",
|
|
1542
|
+
validateOnly: args.validate_only ? true : void 0
|
|
1543
|
+
});
|
|
1544
|
+
const data = await ingest(
|
|
1545
|
+
h,
|
|
1546
|
+
"events:ingest",
|
|
1547
|
+
body,
|
|
1548
|
+
args.validate_only,
|
|
1549
|
+
EVENT_ERRORS,
|
|
1550
|
+
"Google Ads counts a conversion with the same transaction_id, or the same gclid and time, once, so sending these again counts twice only those with neither."
|
|
1551
|
+
);
|
|
1552
|
+
return compact({
|
|
1553
|
+
customer_id: id,
|
|
1554
|
+
conversion_action: `customers/${id}/conversionActions/${action}`,
|
|
1555
|
+
request_id: text(data?.requestId, 200),
|
|
1556
|
+
validate_only: args.validate_only ? true : void 0,
|
|
1557
|
+
valid: args.validate_only ? true : void 0,
|
|
1558
|
+
conversions_sent: events.length,
|
|
1559
|
+
skipped_identifiers: skipped.length ? skipped.slice(0, 100) : void 0,
|
|
1560
|
+
...warningsOf(data),
|
|
1561
|
+
note: args.validate_only ? "Google checked the conversions and took none." : "Google processes the conversions in the background: get_upload_status with request_id tells how many it took and why any were not."
|
|
1562
|
+
});
|
|
1563
|
+
}
|
|
1564
|
+
};
|
|
1565
|
+
var STATUS_KEYS = ["audienceMembersIngestionStatus", "audienceMembersRemovalStatus", "eventsIngestionStatus", "removeAllAudienceMembersStatus"];
|
|
1566
|
+
function countsOf(list, withIndices) {
|
|
1567
|
+
if (!Array.isArray(list) || !list.length) return void 0;
|
|
1568
|
+
return list.slice(0, MAX_COUNTS).map((item) => {
|
|
1569
|
+
const indices = Array.isArray(item?.recordIndices) ? item.recordIndices : [];
|
|
1570
|
+
return compact({
|
|
1571
|
+
reason: text(item?.reason, 120),
|
|
1572
|
+
record_count: item?.recordCount !== void 0 ? Number(item.recordCount) : void 0,
|
|
1573
|
+
record_indices: withIndices && indices.length ? indices.slice(0, MAX_INDICES) : void 0
|
|
1574
|
+
});
|
|
1575
|
+
});
|
|
1576
|
+
}
|
|
1577
|
+
function destinationStatus(item, withIndices) {
|
|
1578
|
+
const key = STATUS_KEYS.find((name2) => item?.[name2] && typeof item[name2] === "object");
|
|
1579
|
+
const status = key ? item[key] : void 0;
|
|
1580
|
+
const inner = status && Object.keys(status).length === 1 && typeof Object.values(status)[0] === "object" ? Object.values(status)[0] : status;
|
|
1581
|
+
return compact({
|
|
1582
|
+
customer_id: text(item?.destination?.operatingAccount?.accountId, 20),
|
|
1583
|
+
product_destination_id: text(item?.destination?.productDestinationId, 40),
|
|
1584
|
+
request_status: text(item?.requestStatus, 40),
|
|
1585
|
+
operation: key ? snake(key.replace(/Status$/, "")) : void 0,
|
|
1586
|
+
figures: inner && Object.keys(inner).length ? snakeDeep(inner) : void 0,
|
|
1587
|
+
errors: countsOf(item?.errorInfo?.errorCounts, withIndices),
|
|
1588
|
+
warnings: countsOf(item?.warningInfo?.warningCounts, withIndices)
|
|
1589
|
+
});
|
|
1590
|
+
}
|
|
1591
|
+
var getUploadStatus = {
|
|
1592
|
+
name: "get_upload_status",
|
|
1593
|
+
kind: "read",
|
|
1594
|
+
title: "Get the status of a Data Manager upload",
|
|
1595
|
+
description: "How Google processed a request of add_audience_members, remove_audience_members or upload_conversions, by its request_id: request_status PROCESSING, SUCCESS, PARTIAL_SUCCESS or FAILED, how many records it held, the match rate range of an audience upload, and the reasons of the records that failed or got warnings, with their record indices (0-based, in the order they were sent). It changes nothing.",
|
|
1596
|
+
inputSchema: {
|
|
1597
|
+
type: "object",
|
|
1598
|
+
properties: {
|
|
1599
|
+
request_id: { type: "string", pattern: "^[A-Za-z0-9_.:-]{1,128}$", description: "The request_id an upload returned." }
|
|
1600
|
+
},
|
|
1601
|
+
required: ["request_id"],
|
|
1602
|
+
additionalProperties: false
|
|
1603
|
+
},
|
|
1604
|
+
async run(args, h) {
|
|
1605
|
+
const { data } = await h.api({
|
|
1606
|
+
origin: DATA_MANAGER,
|
|
1607
|
+
path: `/${DM_VERSION}/requestStatus:retrieve`,
|
|
1608
|
+
query: { requestId: args.request_id },
|
|
1609
|
+
errors: STATUS_ERRORS
|
|
1610
|
+
});
|
|
1611
|
+
const all = Array.isArray(data?.requestStatusPerDestination) ? data.requestStatusPerDestination : [];
|
|
1612
|
+
const allowed = allowedAccounts(h.ctx.accounts, "customers");
|
|
1613
|
+
const shown = all.filter((item) => allowed === null || allowed.includes(digits(String(item?.destination?.operatingAccount?.accountId ?? ""))));
|
|
1614
|
+
const build = (withIndices) => compact({
|
|
1615
|
+
request_id: args.request_id,
|
|
1616
|
+
destinations: shown.map((item) => destinationStatus(item, withIndices)),
|
|
1617
|
+
hidden_destinations: all.length > shown.length ? all.length - shown.length : void 0
|
|
1618
|
+
});
|
|
1619
|
+
const result2 = build(true);
|
|
1620
|
+
if (jsonSize(result2) <= OUTPUT_LIMIT_BYTES - 500) return result2;
|
|
1621
|
+
return { ...build(false), note: "Record indices are left out to fit the result." };
|
|
1622
|
+
}
|
|
1623
|
+
};
|
|
1624
|
+
function dataManagerTools() {
|
|
1625
|
+
return [audienceTool("add"), audienceTool("remove"), uploadConversions, getUploadStatus];
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
// src/vendors/google-ads/index.ts
|
|
1629
|
+
var MAX_IMAGE_BYTES = 5120 * 1024;
|
|
1630
|
+
var PICKER_BATCH = 10;
|
|
1631
|
+
var MUTATE_ERRORS = {
|
|
1632
|
+
...ERRORS,
|
|
1633
|
+
400: "Google Ads rejected the operations: check the field names (camelCase), resource names, enum values and text limits (headlines 30 characters, descriptions 90, paths 15); validate_only: true checks operations without changing anything"
|
|
1634
|
+
};
|
|
1635
|
+
var MATCH_REFUSED = "since April 2026 Google Ads takes Customer Match data only from Google Cloud projects that sent some between October 2025 and March 2026 (others get CUSTOMER_NOT_ALLOWLISTED_FOR_THIS_FEATURE), and add_audience_members and remove_audience_members send the same people through Google's Data Manager API, open to every project";
|
|
1636
|
+
var MATCH_ERRORS = {
|
|
1637
|
+
...MUTATE_ERRORS,
|
|
1638
|
+
400: `Google Ads did not accept the Customer Match job: the user list must be a CRM-based list of this account, and ${MATCH_REFUSED}`,
|
|
1639
|
+
403: `Google Ads refused the Customer Match job: ${MATCH_REFUSED}; or the Google account has no access to this account, or reaches it through a manager account (give login_customer_id)`
|
|
1640
|
+
};
|
|
1641
|
+
var CLICKS_REFUSED = "since June 15, 2026 Google Ads takes click conversions only from Google Cloud projects that sent some between December 2025 and June 2026 (others get CUSTOMER_NOT_ALLOWLISTED_FOR_THIS_FEATURE), and upload_conversions sends them through Google's Data Manager API, open to every project";
|
|
1642
|
+
var CUSTOMER_QUERY = "SELECT customer.id, customer.descriptive_name, customer.manager, customer.status, customer.currency_code, customer.time_zone, customer.test_account FROM customer LIMIT 1";
|
|
1643
|
+
var CLIENTS_QUERY = "SELECT customer_client.id, customer_client.descriptive_name, customer_client.manager, customer_client.level, customer_client.status, customer_client.currency_code, customer_client.time_zone, customer_client.test_account FROM customer_client WHERE customer_client.level <= 2";
|
|
1644
|
+
var CUSTOMER_NAME = /(?<![A-Za-z0-9_./-])customers\/([0-9]+)/g;
|
|
1645
|
+
function customersIn(value) {
|
|
1646
|
+
if (value === void 0) return [];
|
|
1647
|
+
const text2 = typeof value === "string" ? value : JSON.stringify(value);
|
|
1648
|
+
return [...new Set([...text2.matchAll(CUSTOMER_NAME)].map((match) => match[1]))];
|
|
1649
|
+
}
|
|
1650
|
+
function customerOfPath(path) {
|
|
1651
|
+
return /^\/v[0-9]+\/customers\/([0-9]+)(?:[/:]|$)/.exec(path)?.[1];
|
|
1652
|
+
}
|
|
1653
|
+
function allowlistErrors(path) {
|
|
1654
|
+
if (/:uploadClickConversions$/.test(path)) {
|
|
1655
|
+
const sentence = `Google Ads refused the click conversions: ${CLICKS_REFUSED}`;
|
|
1656
|
+
return { 400: sentence, 403: sentence };
|
|
1657
|
+
}
|
|
1658
|
+
if (/\/offlineUserDataJobs(?:[/:]|$)|:uploadUserData$/.test(path)) {
|
|
1659
|
+
const sentence = `Google Ads refused the Customer Match upload: ${MATCH_REFUSED}`;
|
|
1660
|
+
return { 400: sentence, 403: sentence };
|
|
1661
|
+
}
|
|
1662
|
+
return void 0;
|
|
1663
|
+
}
|
|
1664
|
+
function flattenRow(value, prefix = "", out = {}) {
|
|
1665
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
1666
|
+
for (const [key, item] of Object.entries(value)) flattenRow(item, prefix ? `${prefix}.${snake(key)}` : snake(key), out);
|
|
1667
|
+
} else if (prefix) {
|
|
1668
|
+
out[prefix] = Array.isArray(value) ? snakeDeep(value) : typeof value === "string" ? truncate(value, 2e3) : value;
|
|
1669
|
+
}
|
|
1670
|
+
return out;
|
|
1671
|
+
}
|
|
1672
|
+
function defaultAssetName(url) {
|
|
1673
|
+
let file = "";
|
|
1674
|
+
try {
|
|
1675
|
+
file = decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
|
|
1676
|
+
} catch {
|
|
1677
|
+
}
|
|
1678
|
+
const base = truncate(file.replace(/[\u0000-\u001f\u007f]+/g, " ").trim() || "Image", 80);
|
|
1679
|
+
return `${base} ${(/* @__PURE__ */ new Date()).toISOString().replace(/\.[0-9]{3}Z$/, "Z")}`;
|
|
1680
|
+
}
|
|
1681
|
+
function failuresOf(error) {
|
|
1682
|
+
const details = Array.isArray(error?.details) ? error.details : [];
|
|
1683
|
+
const failures = details.flatMap((detail) => Array.isArray(detail?.errors) ? detail.errors : []).slice(0, 50).map((item) => {
|
|
1684
|
+
const path = Array.isArray(item?.location?.fieldPathElements) ? item.location.fieldPathElements : [];
|
|
1685
|
+
const indexed = path.find((element) => typeof element?.index === "number");
|
|
1686
|
+
const code = item?.errorCode && typeof item.errorCode === "object" ? Object.entries(item.errorCode)[0] : void 0;
|
|
1687
|
+
return compact({
|
|
1688
|
+
operation: indexed?.index,
|
|
1689
|
+
message: typeof item?.message === "string" ? truncate(item.message, 300) : void 0,
|
|
1690
|
+
error_code: code ? `${snake(String(code[0]))}: ${String(code[1])}` : void 0,
|
|
1691
|
+
field: path.length ? path.map((element) => `${element?.fieldName}${typeof element?.index === "number" ? `[${element.index}]` : ""}`).join(".") : void 0
|
|
1692
|
+
});
|
|
1693
|
+
});
|
|
1694
|
+
if (!failures.length && typeof error?.message === "string") return [{ message: truncate(error.message, 300) }];
|
|
1695
|
+
return failures.length ? failures : void 0;
|
|
1696
|
+
}
|
|
1697
|
+
function fitWriteResult(result2, listKey) {
|
|
1698
|
+
const list = result2[listKey];
|
|
1699
|
+
if (!Array.isArray(list) || jsonSize(result2) <= OUTPUT_LIMIT_BYTES - 500) return result2;
|
|
1700
|
+
let count = list.length;
|
|
1701
|
+
while (count > 0 && jsonSize({ ...result2, [listKey]: list.slice(0, count) }) > OUTPUT_LIMIT_BYTES - 500) count = Math.floor(count * 0.8);
|
|
1702
|
+
return { ...result2, [listKey]: list.slice(0, count), [`${listKey}_total`]: list.length, [`${listKey}_note`]: `Only the first ${count} of ${list.length} are listed here; search lists the rest.` };
|
|
1703
|
+
}
|
|
1704
|
+
function hasPartialFailure(data) {
|
|
1705
|
+
return Boolean(data?.partialFailureError && (data.partialFailureError.code || data.partialFailureError.message));
|
|
1706
|
+
}
|
|
1707
|
+
function imageType(bytes) {
|
|
1708
|
+
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
|
|
1709
|
+
if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) return "image/png";
|
|
1710
|
+
if (bytes[0] === 71 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 56) return "image/gif";
|
|
1711
|
+
return void 0;
|
|
1712
|
+
}
|
|
1713
|
+
function base64(bytes) {
|
|
1714
|
+
let binary = "";
|
|
1715
|
+
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
|
|
1716
|
+
return btoa(binary);
|
|
1717
|
+
}
|
|
1718
|
+
function guardRequest(request, h) {
|
|
1719
|
+
const allowed = allowedAccounts(h.ctx.accounts, "customers");
|
|
1720
|
+
if (allowed !== null) {
|
|
1721
|
+
const ids = /* @__PURE__ */ new Set([...customersIn(request.json), ...Object.values(request.query).flat().flatMap((value) => customersIn(value))]);
|
|
1722
|
+
request.segments.forEach((segment, index) => {
|
|
1723
|
+
const next = request.segments[index + 1];
|
|
1724
|
+
if (segment === "customers" && next) ids.add(next.split(":")[0]);
|
|
1725
|
+
});
|
|
1726
|
+
const free = request.method === "GET" && /^\/v[0-9]+\/(googleAdsFields(\/|:|$)|customers:listAccessibleCustomers$)/.test(request.path);
|
|
1727
|
+
if (!ids.size && !free) {
|
|
1728
|
+
throw new ToolFailure(
|
|
1729
|
+
`This request names none of the ${ACCOUNT}s chosen for this connection. ` + (allowed.length ? `It must name one of: ${allowed.join(", ")}. Nothing was sent.` : `No ${ACCOUNT} is chosen for it yet. Nothing was sent.`)
|
|
1730
|
+
);
|
|
1731
|
+
}
|
|
1732
|
+
if (ids.size) requireAccounts(h.ctx.accounts, "customers", [...ids], ACCOUNT);
|
|
1733
|
+
}
|
|
1734
|
+
if (request.method !== "GET" && request.segments.some((segment) => /^(customerUserAccesses|customerUserAccessInvitations|customerManagerLinks|customerClientLinks)(:|$)/.test(segment))) {
|
|
1735
|
+
throw new ToolFailure(`Changing who can access a ${ACCOUNT}, or its manager links, is not offered here: do it in Google Ads, Admin, Access and security. Nothing was sent.`);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
function genericTools() {
|
|
1739
|
+
return apiTools({
|
|
1740
|
+
label: LABEL2,
|
|
1741
|
+
description: `The Google Ads API ${VERSION} REST interface at ${ADS_ORIGIN} with the connected account: paths start with /${VERSION}/customers/{customer_id}, such as /${VERSION}/customers/{customer_id}/campaigns:mutate, recommendations:apply or recommendations:dismiss, {customer_id}:uploadConversionAdjustments or :uploadCallConversions. Click conversions and Customer Match data go through upload_conversions and add_audience_members unless Google allowlisted the project. Money is in micros (1 unit = 1000000). Reference: https://developers.google.com/google-ads/api/rest/overview.`,
|
|
1742
|
+
basePath: `/${VERSION}/`,
|
|
1743
|
+
methods: ["POST"],
|
|
1744
|
+
guard: guardRequest
|
|
1745
|
+
}).map((tool) => {
|
|
1746
|
+
const properties = { ...tool.inputSchema.properties, login_customer_id: LOGIN_CUSTOMER_ID };
|
|
1747
|
+
let description = tool.description;
|
|
1748
|
+
if (tool.name === "api_request") {
|
|
1749
|
+
delete properties["body"];
|
|
1750
|
+
delete properties["content_type"];
|
|
1751
|
+
properties["json"] = { type: "object", description: "A JSON object to send as the body." };
|
|
1752
|
+
description = description.replace(" or another body (body and content_type)", "").replace("check with api_get", "check with search (GAQL)");
|
|
1753
|
+
}
|
|
1754
|
+
return {
|
|
1755
|
+
...tool,
|
|
1756
|
+
...tool.name === "api_request" ? { check: "search" } : {},
|
|
1757
|
+
description,
|
|
1758
|
+
inputSchema: { ...tool.inputSchema, properties },
|
|
1759
|
+
run: (args, h) => {
|
|
1760
|
+
const { login_customer_id: login, ...rest } = args;
|
|
1761
|
+
const api = async (request) => {
|
|
1762
|
+
const resolved = await loginFor(h, customerOfPath(request.path), typeof login === "string" ? login : void 0);
|
|
1763
|
+
const errors = allowlistErrors(request.path);
|
|
1764
|
+
return h.api({ ...request, headers: { ...request.headers, ...loginHeaders(resolved) }, ...errors ? { errors: { ...request.errors, ...errors } } : {} });
|
|
1765
|
+
};
|
|
1766
|
+
return tool.run(rest, { ...h, api });
|
|
1767
|
+
}
|
|
1768
|
+
};
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1771
|
+
var connector = defineConnector({
|
|
1772
|
+
vendor: "google-ads",
|
|
1773
|
+
label: LABEL2,
|
|
1774
|
+
origins: [ADS_ORIGIN, DATA_MANAGER],
|
|
1775
|
+
credentials: ["access_token", "developertoken", "managercustomerid"],
|
|
1776
|
+
requiredCredentials: [["access_token"]],
|
|
1777
|
+
credentialLabels: {
|
|
1778
|
+
access_token: "Google Ads access token",
|
|
1779
|
+
developertoken: "Google Ads developer token",
|
|
1780
|
+
managercustomerid: "Google Ads manager account ID"
|
|
1781
|
+
},
|
|
1782
|
+
accountPickers: [
|
|
1783
|
+
{
|
|
1784
|
+
key: "customers",
|
|
1785
|
+
label: "Google Ads accounts",
|
|
1786
|
+
description: "The Google Ads accounts the agent may report on and change.",
|
|
1787
|
+
multiple: true,
|
|
1788
|
+
tool: "list_customers",
|
|
1789
|
+
idField: "id",
|
|
1790
|
+
nameField: "name",
|
|
1791
|
+
legacyField: "customerid"
|
|
1792
|
+
}
|
|
1793
|
+
],
|
|
1794
|
+
normalizeCredentials: (credentials) => {
|
|
1795
|
+
const manager = credentials["managercustomerid"] ? digits(credentials["managercustomerid"]) : "";
|
|
1796
|
+
if (manager) credentials["managercustomerid"] = manager;
|
|
1797
|
+
else delete credentials["managercustomerid"];
|
|
1798
|
+
return credentials;
|
|
1799
|
+
},
|
|
1800
|
+
// No developer-token header: Google ignores it since 2026-09-09 and will refuse it in a later major version.
|
|
1801
|
+
// The login-customer-id goes on each Google Ads request (loginFor), never to the Data Manager API.
|
|
1802
|
+
authHeaders: (credentials) => ({ authorization: `Bearer ${credentials["access_token"]}` }),
|
|
1803
|
+
tools: [
|
|
1804
|
+
{
|
|
1805
|
+
name: "list_customers",
|
|
1806
|
+
kind: "read",
|
|
1807
|
+
title: "List Google Ads accounts",
|
|
1808
|
+
description: "Lists the Google Ads accounts the connected Google account can open: those it has direct access to, and the client accounts (two levels deep) of each manager account among them. Each has its ID, name, status, currency, time zone, whether it is a manager, and for a client account the login_customer_id to act through. When the connection is limited to chosen accounts, those are marked selected: true, and only they can be used. Pass nextCursor back as cursor for more.",
|
|
1809
|
+
inputSchema: { type: "object", properties: { cursor: CURSOR }, additionalProperties: false },
|
|
1810
|
+
async run(args, h) {
|
|
1811
|
+
const state = h.cursor(args.cursor);
|
|
1812
|
+
const start = typeof state?.["i"] === "number" ? state["i"] : 0;
|
|
1813
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1814
|
+
const chosen = allowedAccounts(h.ctx.accounts, "customers");
|
|
1815
|
+
const selected = (id) => chosen?.includes(id) ? true : void 0;
|
|
1816
|
+
const { data } = await h.api({ path: `/${VERSION}/customers:listAccessibleCustomers`, errors: ERRORS });
|
|
1817
|
+
const accessible = accessibleIds(data);
|
|
1818
|
+
const seen = new Set(accessible);
|
|
1819
|
+
const customers = [];
|
|
1820
|
+
const managers = [];
|
|
1821
|
+
const clients = [];
|
|
1822
|
+
const tryRead = async (customer, query, login) => {
|
|
1823
|
+
try {
|
|
1824
|
+
const page = await searchPage(h, customer, query, login);
|
|
1825
|
+
return Array.isArray(page?.results) ? page.results : [];
|
|
1826
|
+
} catch (error) {
|
|
1827
|
+
const status = error instanceof ToolFailure ? error.details.status : void 0;
|
|
1828
|
+
if (status === 400 || status === 403 || status === 404) return `HTTP ${status}`;
|
|
1829
|
+
throw error;
|
|
1830
|
+
}
|
|
1831
|
+
};
|
|
1832
|
+
for (const id of accessible.slice(start, start + PICKER_BATCH)) {
|
|
1833
|
+
const rows = await tryRead(id, CUSTOMER_QUERY, id);
|
|
1834
|
+
if (typeof rows === "string") {
|
|
1835
|
+
customers.push(compact({ id, name: id, status: "NOT_ACCESSIBLE", note: `Google Ads answered ${rows} for this account.`, selected: selected(id) }));
|
|
1836
|
+
continue;
|
|
1837
|
+
}
|
|
1838
|
+
const customer = rows[0]?.customer ?? {};
|
|
1839
|
+
managers.push([id, customer.manager === true]);
|
|
1840
|
+
customers.push(compact({
|
|
1841
|
+
id,
|
|
1842
|
+
name: typeof customer.descriptiveName === "string" && customer.descriptiveName ? truncate(customer.descriptiveName, 200) : id,
|
|
1843
|
+
status: customer.status,
|
|
1844
|
+
manager: customer.manager === true,
|
|
1845
|
+
currency_code: customer.currencyCode,
|
|
1846
|
+
time_zone: customer.timeZone,
|
|
1847
|
+
test_account: customer.testAccount === true ? true : void 0,
|
|
1848
|
+
selected: selected(id)
|
|
1849
|
+
}));
|
|
1850
|
+
if (customer.manager !== true) continue;
|
|
1851
|
+
const found = await tryRead(id, CLIENTS_QUERY, id);
|
|
1852
|
+
if (typeof found === "string") continue;
|
|
1853
|
+
for (const row of found) {
|
|
1854
|
+
const client = row?.customerClient ?? {};
|
|
1855
|
+
const clientId = client.id !== void 0 ? String(client.id) : "";
|
|
1856
|
+
if (!/^[0-9]{10}$/.test(clientId) || seen.has(clientId)) continue;
|
|
1857
|
+
seen.add(clientId);
|
|
1858
|
+
clients.push([clientId, id]);
|
|
1859
|
+
customers.push(compact({
|
|
1860
|
+
id: clientId,
|
|
1861
|
+
name: typeof client.descriptiveName === "string" && client.descriptiveName ? truncate(client.descriptiveName, 200) : clientId,
|
|
1862
|
+
status: client.status,
|
|
1863
|
+
manager: client.manager === true,
|
|
1864
|
+
currency_code: client.currencyCode,
|
|
1865
|
+
time_zone: client.timeZone,
|
|
1866
|
+
test_account: client.testAccount === true ? true : void 0,
|
|
1867
|
+
level: client.level !== void 0 ? Number(client.level) : void 0,
|
|
1868
|
+
login_customer_id: id,
|
|
1869
|
+
selected: selected(clientId)
|
|
1870
|
+
}));
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
await rememberHierarchy(h, accessible, managers, clients);
|
|
1874
|
+
return h.page({
|
|
1875
|
+
key: "customers",
|
|
1876
|
+
items: customers.slice(skip),
|
|
1877
|
+
extra: compact({
|
|
1878
|
+
accessible_accounts: accessible.length,
|
|
1879
|
+
note: chosen?.length === 0 ? "No account is chosen for this connection yet, so every tool that names an account is refused until accounts from this list are chosen for it." : void 0
|
|
1880
|
+
}),
|
|
1881
|
+
resumeAt: (index) => h.makeCursor({ i: start, o: skip + index }),
|
|
1882
|
+
...start + PICKER_BATCH < accessible.length ? { nextPage: h.makeCursor({ i: start + PICKER_BATCH, o: 0 }) } : {}
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
1885
|
+
},
|
|
1886
|
+
{
|
|
1887
|
+
name: "search",
|
|
1888
|
+
kind: "read",
|
|
1889
|
+
title: "Search Google Ads with GAQL",
|
|
1890
|
+
description: `Runs a Google Ads Query Language query on one account, e.g. "SELECT campaign.id, campaign.name, metrics.clicks, metrics.cost_micros FROM campaign WHERE segments.date DURING LAST_7_DAYS AND campaign.status != REMOVED ORDER BY metrics.cost_micros DESC LIMIT 50". Rows come back flat, named like the query's fields; money is in micros (1 unit = 1000000) and counts are text. Google sends pages of 10,000 rows and a page over 8 MB cannot be read, so bound a query that can match more than a few thousand rows (keywords, search terms, daily segments) with ORDER BY and LIMIT, or split it by segments.date or campaign.id. Pass nextCursor back as cursor with the same query for more. It changes nothing.`,
|
|
1891
|
+
inputSchema: {
|
|
1892
|
+
type: "object",
|
|
1893
|
+
properties: {
|
|
1894
|
+
customer_id: CUSTOMER_ID,
|
|
1895
|
+
query: { type: "string", minLength: 10, maxLength: 2e4, description: "The GAQL query: SELECT fields FROM resource [WHERE ...] [ORDER BY ...] [LIMIT n]." },
|
|
1896
|
+
login_customer_id: LOGIN_CUSTOMER_ID,
|
|
1897
|
+
cursor: CURSOR
|
|
1898
|
+
},
|
|
1899
|
+
required: ["customer_id", "query"],
|
|
1900
|
+
additionalProperties: false
|
|
1901
|
+
},
|
|
1902
|
+
async run(args, h) {
|
|
1903
|
+
const id = chosenCustomer(h, args.customer_id);
|
|
1904
|
+
const state = h.cursor(args.cursor);
|
|
1905
|
+
const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
1906
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1907
|
+
const login = await loginFor(h, id, args.login_customer_id);
|
|
1908
|
+
const data = await searchPage(h, id, args.query, login, pageToken);
|
|
1909
|
+
const rows = (Array.isArray(data?.results) ? data.results : []).map((row) => flattenRow(row));
|
|
1910
|
+
return h.page({
|
|
1911
|
+
key: "rows",
|
|
1912
|
+
items: rows.slice(skip),
|
|
1913
|
+
extra: compact({ customer_id: id, field_mask: typeof data?.fieldMask === "string" ? truncate(data.fieldMask, 2e3) : void 0 }),
|
|
1914
|
+
resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index }),
|
|
1915
|
+
...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0 }) } : {}
|
|
1916
|
+
});
|
|
1917
|
+
}
|
|
1918
|
+
},
|
|
1919
|
+
{
|
|
1920
|
+
name: "mutate",
|
|
1921
|
+
kind: "write",
|
|
1922
|
+
check: "search",
|
|
1923
|
+
title: "Change Google Ads resources",
|
|
1924
|
+
description: 'Creates, updates or removes resources of one account in one atomic request (GoogleAdsService.Mutate): campaign budgets, campaigns, ad groups, ads, keywords and other criteria, assets and their links, user lists, conversion actions, bidding strategies, shared sets and more. Each operation is e.g. {"campaignOperation": {"update": {"resourceName": "customers/1234567890/campaigns/111", "status": "PAUSED"}, "updateMask": "status"}}; new resources can refer to each other by negative IDs. validate_only checks without changing anything. Sent once, never retried.',
|
|
1925
|
+
inputSchema: {
|
|
1926
|
+
type: "object",
|
|
1927
|
+
properties: {
|
|
1928
|
+
customer_id: CUSTOMER_ID,
|
|
1929
|
+
login_customer_id: LOGIN_CUSTOMER_ID,
|
|
1930
|
+
operations: {
|
|
1931
|
+
type: "array",
|
|
1932
|
+
minItems: 1,
|
|
1933
|
+
maxItems: 1e3,
|
|
1934
|
+
items: { type: "object" },
|
|
1935
|
+
description: "MutateOperation objects in the API's JSON (camelCase), e.g. campaignBudgetOperation, campaignOperation, adGroupOperation, adGroupAdOperation, adGroupCriterionOperation, campaignCriterionOperation, assetOperation, campaignAssetOperation, userListOperation, conversionActionOperation. Money is in micros; new campaigns are best created PAUSED."
|
|
1936
|
+
},
|
|
1937
|
+
partial_failure: { type: "boolean", description: "Apply the valid operations even if others fail (default false: all or nothing)." },
|
|
1938
|
+
validate_only: { type: "boolean", description: "Check the operations and change nothing." }
|
|
1939
|
+
},
|
|
1940
|
+
required: ["customer_id", "operations"],
|
|
1941
|
+
additionalProperties: false
|
|
1942
|
+
},
|
|
1943
|
+
async run(args, h) {
|
|
1944
|
+
const id = chosenCustomer(h, args.customer_id);
|
|
1945
|
+
const named = customersIn(args.operations).filter((other) => other !== id);
|
|
1946
|
+
if (named.length) {
|
|
1947
|
+
requireAccounts(h.ctx.accounts, "customers", named, ACCOUNT);
|
|
1948
|
+
throw new ToolFailure(`The operations name another account (${named.join(", ")}) than ${id}: every resource name must be under customers/${id}. Nothing was changed.`);
|
|
1949
|
+
}
|
|
1950
|
+
const login = await loginFor(h, id, args.login_customer_id);
|
|
1951
|
+
const { data } = await h.api({
|
|
1952
|
+
method: "POST",
|
|
1953
|
+
path: `/${VERSION}/customers/${id}/googleAds:mutate`,
|
|
1954
|
+
headers: loginHeaders(login),
|
|
1955
|
+
json: compact({ mutateOperations: args.operations, partialFailure: args.partial_failure, validateOnly: args.validate_only }),
|
|
1956
|
+
write: !args.validate_only,
|
|
1957
|
+
errors: MUTATE_ERRORS
|
|
1958
|
+
});
|
|
1959
|
+
const responses = Array.isArray(data?.mutateOperationResponses) ? data.mutateOperationResponses : [];
|
|
1960
|
+
const results = responses.map((response) => {
|
|
1961
|
+
const key = Object.keys(response ?? {})[0];
|
|
1962
|
+
const value = key ? response[key] : void 0;
|
|
1963
|
+
return key ? compact({ type: snake(key.replace(/Result$/, "")), resource_name: value?.resourceName }) : {};
|
|
1964
|
+
});
|
|
1965
|
+
return fitWriteResult(compact({
|
|
1966
|
+
customer_id: id,
|
|
1967
|
+
validate_only: args.validate_only ? true : void 0,
|
|
1968
|
+
results: args.validate_only ? void 0 : results,
|
|
1969
|
+
valid: args.validate_only && !hasPartialFailure(data) ? true : void 0,
|
|
1970
|
+
failures: hasPartialFailure(data) ? failuresOf(data.partialFailureError) : void 0
|
|
1971
|
+
}), "results");
|
|
1972
|
+
}
|
|
1973
|
+
},
|
|
1974
|
+
{
|
|
1975
|
+
name: "upload_image_asset",
|
|
1976
|
+
kind: "create",
|
|
1977
|
+
check: "search",
|
|
1978
|
+
title: "Upload a Google Ads image asset",
|
|
1979
|
+
description: "Downloads a JPEG, PNG or GIF from a public https URL (up to 5,120 KB) and creates an image asset in one account. Returns its resource name, to use in ads (e.g. responsive display ads) or link with campaignAssetOperation or assetGroupAssetOperation through mutate. Recommended sizes: 1200x628 landscape, 1200x1200 square, 900x1600 portrait; no added text or logos on marketing images.",
|
|
1980
|
+
inputSchema: {
|
|
1981
|
+
type: "object",
|
|
1982
|
+
properties: {
|
|
1983
|
+
customer_id: CUSTOMER_ID,
|
|
1984
|
+
login_customer_id: LOGIN_CUSTOMER_ID,
|
|
1985
|
+
image_url: { type: "string", format: "uri", maxLength: 2048, pattern: "^https://", description: "A public https URL of the image." },
|
|
1986
|
+
name: { type: "string", minLength: 1, maxLength: 128, description: `A name for the asset, unique in the account, e.g. "Spring sale - landscape" (default: the image's file name and the time).` }
|
|
1987
|
+
},
|
|
1988
|
+
required: ["customer_id", "image_url"],
|
|
1989
|
+
additionalProperties: false
|
|
1990
|
+
},
|
|
1991
|
+
async run(args, h) {
|
|
1992
|
+
const id = chosenCustomer(h, args.customer_id);
|
|
1993
|
+
const media = await h.media(args.image_url, { what: "image", maxBytes: MAX_IMAGE_BYTES, accept: "image/jpeg,image/png,image/gif" });
|
|
1994
|
+
const type = imageType(media.bytes);
|
|
1995
|
+
if (!type) throw new ToolFailure("The image is not a JPEG, PNG or GIF file, the formats Google Ads takes. Nothing was changed.");
|
|
1996
|
+
const login = await loginFor(h, id, args.login_customer_id);
|
|
1997
|
+
const { data } = await h.api({
|
|
1998
|
+
method: "POST",
|
|
1999
|
+
path: `/${VERSION}/customers/${id}/assets:mutate`,
|
|
2000
|
+
headers: loginHeaders(login),
|
|
2001
|
+
json: { operations: [{ create: { name: args.name ?? defaultAssetName(args.image_url), type: "IMAGE", imageAsset: { data: base64(media.bytes) } } }] },
|
|
2002
|
+
write: true,
|
|
2003
|
+
errors: MUTATE_ERRORS
|
|
2004
|
+
});
|
|
2005
|
+
const resourceName = data?.results?.[0]?.resourceName;
|
|
2006
|
+
if (typeof resourceName !== "string") throw new OutcomeUnknown(`${LABEL2} answered without the new asset's resource name, so it is not known whether the asset was created.`);
|
|
2007
|
+
return { customer_id: id, resource_name: resourceName, mime_type: type, bytes: media.bytes.length };
|
|
2008
|
+
}
|
|
2009
|
+
},
|
|
2010
|
+
{
|
|
2011
|
+
name: "generate_keyword_ideas",
|
|
2012
|
+
kind: "read",
|
|
2013
|
+
title: "Get Google Ads keyword ideas",
|
|
2014
|
+
description: "Keyword Planner ideas for one account from seed keywords, a page URL, both, or a whole site: each idea with its average monthly searches, competition (LOW, MEDIUM, HIGH) and index (0 to 100), and the low and high top-of-page bids in micros. Language and locations are IDs: English is 1000; the United States 2840, the United Kingdom 2826, Germany 2276. It changes nothing.",
|
|
2015
|
+
inputSchema: {
|
|
2016
|
+
type: "object",
|
|
2017
|
+
properties: {
|
|
2018
|
+
customer_id: CUSTOMER_ID,
|
|
2019
|
+
login_customer_id: LOGIN_CUSTOMER_ID,
|
|
2020
|
+
keywords: { type: "array", maxItems: 20, uniqueItems: true, items: { type: "string", minLength: 1, maxLength: 80 }, description: 'Seed keywords, e.g. ["trail running shoes"].' },
|
|
2021
|
+
url: { type: "string", format: "uri", maxLength: 2048, description: "A page to draw ideas from, alone or with keywords." },
|
|
2022
|
+
site: { type: "string", pattern: "^[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$", maxLength: 253, description: 'A whole site, e.g. "example.com", instead of keywords and url.' },
|
|
2023
|
+
language: { type: "string", pattern: "^(languageConstants/)?[0-9]{1,6}$", default: "1000", description: "A language ID or languageConstants/ID (default 1000, English)." },
|
|
2024
|
+
geo_target_constants: {
|
|
2025
|
+
type: "array",
|
|
2026
|
+
maxItems: 10,
|
|
2027
|
+
uniqueItems: true,
|
|
2028
|
+
items: { type: "string", pattern: "^(geoTargetConstants/)?[0-9]{1,12}$" },
|
|
2029
|
+
description: 'Location IDs or geoTargetConstants/ID, e.g. ["2840"]. None means everywhere.'
|
|
2030
|
+
},
|
|
2031
|
+
keyword_plan_network: { type: "string", enum: ["GOOGLE_SEARCH", "GOOGLE_SEARCH_AND_PARTNERS"], default: "GOOGLE_SEARCH", description: "Where the searches are counted." },
|
|
2032
|
+
include_adult_keywords: { type: "boolean", description: "Include adult keywords." },
|
|
2033
|
+
page_size: { type: "integer", minimum: 1, maximum: 1e3, default: 50, description: "Ideas per page, 1 to 1000 (default 50)." },
|
|
2034
|
+
cursor: CURSOR
|
|
2035
|
+
},
|
|
2036
|
+
required: ["customer_id"],
|
|
2037
|
+
additionalProperties: false
|
|
2038
|
+
},
|
|
2039
|
+
async run(args, h) {
|
|
2040
|
+
const id = chosenCustomer(h, args.customer_id);
|
|
2041
|
+
const keywords = args.keywords ?? [];
|
|
2042
|
+
if (args.site && (keywords.length || args.url)) throw new ToolFailure("Give site alone, or keywords and/or url. Nothing was sent.");
|
|
2043
|
+
if (!args.site && !keywords.length && !args.url) throw new ToolFailure("Give seed keywords, a url, both, or a site. Nothing was sent.");
|
|
2044
|
+
const seed = args.site ? { siteSeed: { site: args.site } } : keywords.length && args.url ? { keywordAndUrlSeed: { url: args.url, keywords } } : args.url ? { urlSeed: { url: args.url } } : { keywordSeed: { keywords } };
|
|
2045
|
+
const state = h.cursor(args.cursor);
|
|
2046
|
+
const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
2047
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
2048
|
+
const login = await loginFor(h, id, args.login_customer_id);
|
|
2049
|
+
const { data } = await h.api({
|
|
2050
|
+
method: "POST",
|
|
2051
|
+
path: `/${VERSION}/customers/${id}:generateKeywordIdeas`,
|
|
2052
|
+
headers: loginHeaders(login),
|
|
2053
|
+
json: compact({
|
|
2054
|
+
language: `languageConstants/${args.language.replace(/^languageConstants\//, "")}`,
|
|
2055
|
+
geoTargetConstants: args.geo_target_constants?.length ? args.geo_target_constants.map((geo) => `geoTargetConstants/${geo.replace(/^geoTargetConstants\//, "")}`) : void 0,
|
|
2056
|
+
keywordPlanNetwork: args.keyword_plan_network,
|
|
2057
|
+
includeAdultKeywords: args.include_adult_keywords,
|
|
2058
|
+
pageSize: args.page_size,
|
|
2059
|
+
pageToken,
|
|
2060
|
+
...seed
|
|
2061
|
+
}),
|
|
2062
|
+
safe: true,
|
|
2063
|
+
errors: { ...ERRORS, 400: "Google Ads did not accept the keyword request: check the language and location IDs and the seeds" }
|
|
2064
|
+
});
|
|
2065
|
+
const number = (value) => value === void 0 || value === null ? void 0 : Number(value);
|
|
2066
|
+
const ideas = (Array.isArray(data?.results) ? data.results : []).map((idea) => compact({
|
|
2067
|
+
text: idea?.text,
|
|
2068
|
+
avg_monthly_searches: number(idea?.keywordIdeaMetrics?.avgMonthlySearches),
|
|
2069
|
+
competition: idea?.keywordIdeaMetrics?.competition,
|
|
2070
|
+
competition_index: number(idea?.keywordIdeaMetrics?.competitionIndex),
|
|
2071
|
+
low_top_of_page_bid_micros: idea?.keywordIdeaMetrics?.lowTopOfPageBidMicros,
|
|
2072
|
+
high_top_of_page_bid_micros: idea?.keywordIdeaMetrics?.highTopOfPageBidMicros
|
|
2073
|
+
}));
|
|
2074
|
+
return h.page({
|
|
2075
|
+
key: "ideas",
|
|
2076
|
+
items: ideas.slice(skip),
|
|
2077
|
+
extra: compact({ customer_id: id, total: number(data?.totalSize) }),
|
|
2078
|
+
resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index }),
|
|
2079
|
+
...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0 }) } : {}
|
|
2080
|
+
});
|
|
2081
|
+
}
|
|
2082
|
+
},
|
|
2083
|
+
{
|
|
2084
|
+
name: "upload_customer_match",
|
|
2085
|
+
kind: "write",
|
|
2086
|
+
check: "search",
|
|
2087
|
+
title: "Add or remove Google Ads Customer Match members",
|
|
2088
|
+
description: "Adds people to, or removes them from, a Customer Match user list (a CRM-based list with upload key type CONTACT_INFO) by email or phone through the Google Ads API: normalizes and hashes them with SHA-256 here, then creates an offline user data job, adds them and runs it. Up to 10,000 identifiers per call; matching takes up to 48 hours. Google Ads takes these only from Cloud projects it allowlisted (those that uploaded Customer Match data between October 2025 and March 2026): add_audience_members and remove_audience_members do the same for any project. Returns the job to check with search.",
|
|
2089
|
+
inputSchema: {
|
|
2090
|
+
type: "object",
|
|
2091
|
+
properties: {
|
|
2092
|
+
customer_id: CUSTOMER_ID,
|
|
2093
|
+
login_customer_id: LOGIN_CUSTOMER_ID,
|
|
2094
|
+
user_list: { type: "string", pattern: "^(customers/[0-9]{10}/userLists/)?[0-9]{1,20}$", description: "The user list ID or its resource name customers/{customer_id}/userLists/{id}." },
|
|
2095
|
+
operation: { type: "string", enum: ["add", "remove"], default: "add", description: "add (default) or remove these people." },
|
|
2096
|
+
...IDENTIFIER_LISTS,
|
|
2097
|
+
...HASHED_LISTS,
|
|
2098
|
+
...CONSENT
|
|
2099
|
+
},
|
|
2100
|
+
required: ["customer_id", "user_list"],
|
|
2101
|
+
additionalProperties: false
|
|
2102
|
+
},
|
|
2103
|
+
async run(args, h) {
|
|
2104
|
+
const id = chosenCustomer(h, args.customer_id);
|
|
2105
|
+
const listMatch = /^customers\/([0-9]{10})\/userLists\/([0-9]+)$/.exec(args.user_list);
|
|
2106
|
+
if (listMatch && listMatch[1] !== id) throw new ToolFailure(`The user list belongs to another account than ${id}. Nothing was changed.`);
|
|
2107
|
+
const userList = `customers/${id}/userLists/${listMatch ? listMatch[2] : args.user_list}`;
|
|
2108
|
+
const total = identifierCount(args);
|
|
2109
|
+
if (!total) throw new ToolFailure("Give at least one email or phone number. Nothing was changed.");
|
|
2110
|
+
if (total > MAX_MATCH_IDENTIFIERS) throw new ToolFailure(`Give at most ${MAX_MATCH_IDENTIFIERS} identifiers per call (got ${total}). Nothing was changed.`);
|
|
2111
|
+
const hashed = await hashIdentifiers(args);
|
|
2112
|
+
const identifiers = [...hashed.emails.map((hash) => ({ hashedEmail: hash })), ...hashed.phones.map((hash) => ({ hashedPhoneNumber: hash }))];
|
|
2113
|
+
if (!identifiers.length) throw new ToolFailure('None of the emails or phone numbers is valid (phones need E.164 form, e.g. "+15551234567"). Nothing was changed.');
|
|
2114
|
+
const headers = loginHeaders(await loginFor(h, id, args.login_customer_id));
|
|
2115
|
+
const consent = compact({ adUserData: args.ad_user_data_consent, adPersonalization: args.ad_personalization_consent });
|
|
2116
|
+
const created = await h.api({
|
|
2117
|
+
method: "POST",
|
|
2118
|
+
path: `/${VERSION}/customers/${id}/offlineUserDataJobs:create`,
|
|
2119
|
+
headers,
|
|
2120
|
+
json: { job: { type: "CUSTOMER_MATCH_USER_LIST", customerMatchUserListMetadata: compact({ userList, consent: Object.keys(consent).length ? consent : void 0 }) } },
|
|
2121
|
+
write: true,
|
|
2122
|
+
errors: MATCH_ERRORS
|
|
2123
|
+
});
|
|
2124
|
+
const job = created.data?.resourceName;
|
|
2125
|
+
if (typeof job !== "string" || !new RegExp(`^customers/${id}/offlineUserDataJobs/[0-9]+$`).test(job)) {
|
|
2126
|
+
throw new OutcomeUnknown(`${LABEL2} answered without the new job's name, so it is not known whether a job was created.`);
|
|
2127
|
+
}
|
|
2128
|
+
const statusQuery = `SELECT offline_user_data_job.resource_name, offline_user_data_job.status, offline_user_data_job.failure_reason FROM offline_user_data_job WHERE offline_user_data_job.resource_name = '${job}'`;
|
|
2129
|
+
const verb = args.operation === "remove" ? "remove" : "create";
|
|
2130
|
+
const added = await h.api({
|
|
2131
|
+
method: "POST",
|
|
2132
|
+
path: `/${VERSION}/${job}:addOperations`,
|
|
2133
|
+
headers,
|
|
2134
|
+
json: { enablePartialFailure: true, operations: identifiers.map((identifier) => ({ [verb]: { userIdentifiers: [identifier] } })) },
|
|
2135
|
+
write: true,
|
|
2136
|
+
errors: MUTATE_ERRORS
|
|
2137
|
+
});
|
|
2138
|
+
let operationName;
|
|
2139
|
+
try {
|
|
2140
|
+
const ran = await h.api({ method: "POST", path: `/${VERSION}/${job}:run`, headers, json: {}, write: true, errors: MUTATE_ERRORS });
|
|
2141
|
+
operationName = ran.data?.name;
|
|
2142
|
+
} catch (error) {
|
|
2143
|
+
if (error instanceof OutcomeUnknown) throw new OutcomeUnknown(`${error.message} The job is ${job}; check its status with: ${statusQuery}.`);
|
|
2144
|
+
throw error;
|
|
2145
|
+
}
|
|
2146
|
+
return compact({
|
|
2147
|
+
customer_id: id,
|
|
2148
|
+
user_list: userList,
|
|
2149
|
+
operation: args.operation,
|
|
2150
|
+
job,
|
|
2151
|
+
long_running_operation: typeof operationName === "string" ? operationName : void 0,
|
|
2152
|
+
identifiers_sent: identifiers.length,
|
|
2153
|
+
skipped_emails: skippedSummary(hashed.skippedEmails),
|
|
2154
|
+
skipped_phones: skippedSummary(hashed.skippedPhones),
|
|
2155
|
+
failures: hasPartialFailure(added.data) ? failuresOf(added.data.partialFailureError) : void 0,
|
|
2156
|
+
status_query: statusQuery,
|
|
2157
|
+
note: "The job runs in the background; matching can take up to 48 hours. Run status_query with search to follow it."
|
|
2158
|
+
});
|
|
2159
|
+
}
|
|
2160
|
+
},
|
|
2161
|
+
// Customer Match members and offline conversions through the Data Manager API, and the status of those uploads.
|
|
2162
|
+
...dataManagerTools(),
|
|
2163
|
+
{
|
|
2164
|
+
name: "hash_user_identifiers",
|
|
2165
|
+
kind: "read",
|
|
2166
|
+
title: "Hash emails and phones for Google Ads",
|
|
2167
|
+
description: "Normalizes emails (trimmed, lower case, and for gmail.com and googlemail.com no dots and no +suffix in the name) and E.164 phone numbers the way Google requires and hashes them with SHA-256 (hex), for user identifiers sent with api_request, such as enhanced conversion adjustments. The upload tools hash on their own. Sends nothing anywhere.",
|
|
2168
|
+
inputSchema: {
|
|
2169
|
+
type: "object",
|
|
2170
|
+
properties: {
|
|
2171
|
+
emails: { ...IDENTIFIER_LISTS.emails, maxItems: 200, description: "Up to 200 email addresses in plain text." },
|
|
2172
|
+
phones: { ...IDENTIFIER_LISTS.phones, maxItems: 200, description: 'Up to 200 phone numbers in E.164 form, e.g. "+15551234567".' }
|
|
2173
|
+
},
|
|
2174
|
+
additionalProperties: false
|
|
2175
|
+
},
|
|
2176
|
+
async run(args) {
|
|
2177
|
+
if (!(args.emails?.length || args.phones?.length)) throw new ToolFailure("Give at least one email or phone number.");
|
|
2178
|
+
const hashAll = async (list, normalize) => {
|
|
2179
|
+
const out = [];
|
|
2180
|
+
for (const raw of list ?? []) {
|
|
2181
|
+
const normalized = normalize(raw);
|
|
2182
|
+
out.push(normalized ? await sha256Hex(normalized) : null);
|
|
2183
|
+
}
|
|
2184
|
+
return out;
|
|
2185
|
+
};
|
|
2186
|
+
const emails = await hashAll(args.emails, normalizeEmail);
|
|
2187
|
+
const phones = await hashAll(args.phones, normalizePhone);
|
|
2188
|
+
const invalid = (list) => list.flatMap((hash, index) => hash === null ? [index] : []);
|
|
2189
|
+
return compact({
|
|
2190
|
+
hashed_emails: emails.length ? emails : void 0,
|
|
2191
|
+
hashed_phone_numbers: phones.length ? phones : void 0,
|
|
2192
|
+
invalid_emails: invalid(emails).length ? invalid(emails) : void 0,
|
|
2193
|
+
invalid_phones: invalid(phones).length ? invalid(phones) : void 0
|
|
2194
|
+
});
|
|
2195
|
+
}
|
|
2196
|
+
},
|
|
2197
|
+
// The rest of the API: recommendations, conversion adjustments, keyword plans, batch jobs, field metadata.
|
|
2198
|
+
...genericTools()
|
|
2199
|
+
]
|
|
2200
|
+
});
|
|
2201
|
+
module.exports = connector;
|