@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,2499 @@
|
|
|
1
|
+
/* apollo connector module (MIT License). Built from src/vendors/apollo; 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
|
+
function truncate(text2, max) {
|
|
68
|
+
if (text2.length <= max) return text2;
|
|
69
|
+
const points = Array.from(text2);
|
|
70
|
+
if (points.length <= max) return text2;
|
|
71
|
+
return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
|
|
72
|
+
}
|
|
73
|
+
function cleanVendorText(text2, max = 300) {
|
|
74
|
+
if (typeof text2 !== "string") return void 0;
|
|
75
|
+
if (/^\s*</.test(text2)) return void 0;
|
|
76
|
+
const line = text2.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
77
|
+
return line ? truncate(line, max) : void 0;
|
|
78
|
+
}
|
|
79
|
+
function formatNumber(value) {
|
|
80
|
+
return value.toLocaleString("en-US");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/core/output.ts
|
|
84
|
+
var OUTPUT_LIMIT_BYTES = 32 * 1024;
|
|
85
|
+
function jsonSize(value) {
|
|
86
|
+
return utf8Length(JSON.stringify(value) ?? "");
|
|
87
|
+
}
|
|
88
|
+
function cutStrings(value, max) {
|
|
89
|
+
if (typeof value === "string") return truncate(value, max);
|
|
90
|
+
if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
|
|
91
|
+
if (typeof value === "object" && value !== null) {
|
|
92
|
+
const out = {};
|
|
93
|
+
for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
|
|
99
|
+
if (jsonSize(value) <= limit) return { value, truncated: false };
|
|
100
|
+
for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
|
|
101
|
+
const cut = cutStrings(value, max);
|
|
102
|
+
if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
|
|
103
|
+
}
|
|
104
|
+
return void 0;
|
|
105
|
+
}
|
|
106
|
+
function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
|
|
107
|
+
const build = (count) => {
|
|
108
|
+
const cut = count < input.items.length;
|
|
109
|
+
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
|
|
110
|
+
const next = cut ? input.resumeAt(count) : input.nextPage;
|
|
111
|
+
if (next) result2["nextCursor"] = next;
|
|
112
|
+
if (cut) result2["truncated"] = true;
|
|
113
|
+
return result2;
|
|
114
|
+
};
|
|
115
|
+
const all = build(input.items.length);
|
|
116
|
+
if (jsonSize(all) <= limit) return all;
|
|
117
|
+
let low = 1;
|
|
118
|
+
let high = input.items.length - 1;
|
|
119
|
+
while (low < high) {
|
|
120
|
+
const middle = Math.ceil((low + high) / 2);
|
|
121
|
+
if (jsonSize(build(middle)) <= limit) low = middle;
|
|
122
|
+
else high = middle - 1;
|
|
123
|
+
}
|
|
124
|
+
const best = build(low);
|
|
125
|
+
if (jsonSize(best) <= limit) return best;
|
|
126
|
+
const shrunk = shrinkToFit(best, limit);
|
|
127
|
+
if (shrunk) return { ...shrunk.value, truncated: true };
|
|
128
|
+
throw new ToolFailure("The result is too large to return, even one item at a time.");
|
|
129
|
+
}
|
|
130
|
+
function encodeCursor(tool, state) {
|
|
131
|
+
return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
|
|
132
|
+
}
|
|
133
|
+
function decodeCursor(tool, cursor) {
|
|
134
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
135
|
+
try {
|
|
136
|
+
const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
|
|
137
|
+
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
138
|
+
return state;
|
|
139
|
+
}
|
|
140
|
+
} catch {
|
|
141
|
+
}
|
|
142
|
+
throw new ToolFailure(
|
|
143
|
+
"The cursor is not valid for this tool. Pass the nextCursor value of the previous result unchanged, or leave cursor out to start from the beginning."
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/core/api-tools.ts
|
|
148
|
+
var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
|
|
149
|
+
var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
|
|
150
|
+
var NOTE_ROOM = 400;
|
|
151
|
+
var MAX_CUT_POINTS = 4e4;
|
|
152
|
+
function isQueryValue(value) {
|
|
153
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
154
|
+
}
|
|
155
|
+
function nothingSent(sentence) {
|
|
156
|
+
return new ToolFailure(`${sentence} Nothing was sent.`);
|
|
157
|
+
}
|
|
158
|
+
function fitReply(reply) {
|
|
159
|
+
if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
|
|
160
|
+
const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
|
|
161
|
+
if (shrunk) {
|
|
162
|
+
return {
|
|
163
|
+
...shrunk.value,
|
|
164
|
+
truncated: true,
|
|
165
|
+
note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
const text2 = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
|
|
169
|
+
const points = Array.from(text2.length > MAX_CUT_POINTS ? text2.slice(0, MAX_CUT_POINTS) : text2);
|
|
170
|
+
if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
|
|
171
|
+
const cut = (count) => ({
|
|
172
|
+
status: reply["status"],
|
|
173
|
+
...reply["headers"] ? { headers: reply["headers"] } : {},
|
|
174
|
+
truncated: true,
|
|
175
|
+
note: `The reply has ${formatNumber(utf8Length(text2))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
|
|
176
|
+
text: points.slice(0, count).join("")
|
|
177
|
+
});
|
|
178
|
+
let low = 0;
|
|
179
|
+
let high = points.length;
|
|
180
|
+
while (low < high) {
|
|
181
|
+
const middle = Math.ceil((low + high) / 2);
|
|
182
|
+
if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
|
|
183
|
+
else high = middle - 1;
|
|
184
|
+
}
|
|
185
|
+
return cut(low);
|
|
186
|
+
}
|
|
187
|
+
function shapeReply(response, headerNames) {
|
|
188
|
+
const reply = { status: response.status };
|
|
189
|
+
const headers = {};
|
|
190
|
+
for (const name2 of headerNames) {
|
|
191
|
+
const value = response.headers.get(name2);
|
|
192
|
+
if (value) headers[name2] = truncate(value, 2e3);
|
|
193
|
+
}
|
|
194
|
+
if (Object.keys(headers).length) reply["headers"] = headers;
|
|
195
|
+
const type = response.headers.get("content-type") ?? "";
|
|
196
|
+
if (type && !TEXT_TYPES.test(type)) {
|
|
197
|
+
reply["contentType"] = truncate(type, 200);
|
|
198
|
+
reply["note"] = "The reply is a binary file and is not shown.";
|
|
199
|
+
return reply;
|
|
200
|
+
}
|
|
201
|
+
if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
|
|
202
|
+
return fitReply(reply);
|
|
203
|
+
}
|
|
204
|
+
function checkAccounts(rule, request, h) {
|
|
205
|
+
const label = rule.label ?? "account";
|
|
206
|
+
const allowed = allowedAccounts(h.ctx.accounts, rule.key);
|
|
207
|
+
if (allowed === null) return;
|
|
208
|
+
const namesNone = nothingSent(
|
|
209
|
+
`This request names none of the ${label}s chosen for this connection. ` + (allowed.length ? `It must name one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`)
|
|
210
|
+
);
|
|
211
|
+
if (rule.ids) {
|
|
212
|
+
const ids = rule.ids(request).map(String);
|
|
213
|
+
if (!ids.length) throw namesNone;
|
|
214
|
+
requireAccounts(h.ctx.accounts, rule.key, ids, label);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
|
|
218
|
+
}
|
|
219
|
+
function apiTools(options) {
|
|
220
|
+
const { label, basePath } = options;
|
|
221
|
+
const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
|
|
222
|
+
const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
|
|
223
|
+
const base = basePath?.replace(/\/+$/, "");
|
|
224
|
+
const pathSchema = {
|
|
225
|
+
type: "string",
|
|
226
|
+
minLength: 1,
|
|
227
|
+
maxLength: 2e3,
|
|
228
|
+
pattern: "^(?!.*//)/[^?#]*$",
|
|
229
|
+
description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
|
|
230
|
+
};
|
|
231
|
+
const querySchema = {
|
|
232
|
+
type: "object",
|
|
233
|
+
description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
|
|
234
|
+
};
|
|
235
|
+
const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
|
|
236
|
+
async function run(method, args, h) {
|
|
237
|
+
let origin = h.origins[0];
|
|
238
|
+
if (args.origin !== void 0) {
|
|
239
|
+
let wanted;
|
|
240
|
+
try {
|
|
241
|
+
wanted = new URL(args.origin).origin;
|
|
242
|
+
} catch {
|
|
243
|
+
}
|
|
244
|
+
if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
|
|
245
|
+
origin = wanted;
|
|
246
|
+
}
|
|
247
|
+
const url = new URL(args.path, origin);
|
|
248
|
+
if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
|
|
249
|
+
const path = url.pathname;
|
|
250
|
+
if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
|
|
251
|
+
let segments;
|
|
252
|
+
try {
|
|
253
|
+
segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
|
|
254
|
+
} catch {
|
|
255
|
+
throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
|
|
256
|
+
}
|
|
257
|
+
if (segments[segments.length - 1] === "") segments.pop();
|
|
258
|
+
const query2 = {};
|
|
259
|
+
const queryLists = {};
|
|
260
|
+
for (const [key, value] of Object.entries(args.query ?? {})) {
|
|
261
|
+
if (value === void 0 || value === null) continue;
|
|
262
|
+
const list = Array.isArray(value) ? value : [value];
|
|
263
|
+
if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
|
|
264
|
+
query2[key] = Array.isArray(value) ? list : value;
|
|
265
|
+
queryLists[key] = list.map(String);
|
|
266
|
+
}
|
|
267
|
+
const request = { method, origin, path, query: query2 };
|
|
268
|
+
if (method !== "GET") {
|
|
269
|
+
if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
|
|
270
|
+
if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
|
|
271
|
+
if (args.json !== void 0 && !args.content_type) {
|
|
272
|
+
request.json = args.json;
|
|
273
|
+
} else if (args.json !== void 0 || args.body !== void 0) {
|
|
274
|
+
request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
|
|
275
|
+
request.contentType = args.content_type;
|
|
276
|
+
}
|
|
277
|
+
request.write = true;
|
|
278
|
+
}
|
|
279
|
+
const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
|
|
280
|
+
if (options.accounts) checkAccounts(options.accounts, info, h);
|
|
281
|
+
await options.guard?.(info, h);
|
|
282
|
+
const response = options.send ? await options.send(request, h) : await h.api(request);
|
|
283
|
+
return shapeReply(response, headerNames);
|
|
284
|
+
}
|
|
285
|
+
return [
|
|
286
|
+
{
|
|
287
|
+
name: "api_get",
|
|
288
|
+
kind: "read",
|
|
289
|
+
title: `Call the ${label} API (GET)`,
|
|
290
|
+
description: `${options.description} Sends one GET request with the connection's credentials and returns the HTTP status and the reply, JSON or text, cut to fit 32 KB (use the API's own paging and field parameters for long lists). It changes nothing.`,
|
|
291
|
+
inputSchema: {
|
|
292
|
+
type: "object",
|
|
293
|
+
properties: { path: pathSchema, query: querySchema, ...originSchema },
|
|
294
|
+
required: ["path"],
|
|
295
|
+
additionalProperties: false
|
|
296
|
+
},
|
|
297
|
+
run: (args, h) => run("GET", args, h)
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
name: "api_request",
|
|
301
|
+
kind: "write",
|
|
302
|
+
check: "api_get",
|
|
303
|
+
title: `Send a request to the ${label} API`,
|
|
304
|
+
description: `${options.description} Sends one ${methods.join(", ")} request with the connection's credentials, with a JSON body (json) or another body (body and content_type), and returns the HTTP status and the reply. It can create, change or delete data. It is never retried: when the outcome is unclear, check with api_get before sending it again.`,
|
|
305
|
+
inputSchema: {
|
|
306
|
+
type: "object",
|
|
307
|
+
properties: {
|
|
308
|
+
method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
|
|
309
|
+
path: pathSchema,
|
|
310
|
+
query: querySchema,
|
|
311
|
+
json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
|
|
312
|
+
body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
|
|
313
|
+
content_type: {
|
|
314
|
+
type: "string",
|
|
315
|
+
pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
|
|
316
|
+
maxLength: 200,
|
|
317
|
+
description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
|
|
318
|
+
},
|
|
319
|
+
...originSchema
|
|
320
|
+
},
|
|
321
|
+
required: ["method", "path"],
|
|
322
|
+
additionalProperties: false
|
|
323
|
+
},
|
|
324
|
+
run: (args, h) => run(args.method, args, h)
|
|
325
|
+
}
|
|
326
|
+
];
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// src/core/credentials.ts
|
|
330
|
+
function requiredAlternatives(module2) {
|
|
331
|
+
return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
|
|
332
|
+
}
|
|
333
|
+
function unmetAlternatives(alternatives, has) {
|
|
334
|
+
const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
|
|
335
|
+
if (lacking.some((list) => list.length === 0)) return [];
|
|
336
|
+
return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
|
|
337
|
+
}
|
|
338
|
+
function andList(items) {
|
|
339
|
+
if (items.length <= 2) return items.join(" and ");
|
|
340
|
+
return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
|
|
341
|
+
}
|
|
342
|
+
function orList(items) {
|
|
343
|
+
if (items.length <= 1) return items.join("");
|
|
344
|
+
return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// src/core/files.ts
|
|
348
|
+
var ATTACHMENT_URI = "attachment:///";
|
|
349
|
+
var MAX_NAME = 200;
|
|
350
|
+
function fileLimitOf(ctx) {
|
|
351
|
+
const maxBytes = ctx.files?.maxBytes;
|
|
352
|
+
return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
|
|
353
|
+
}
|
|
354
|
+
function fileName(name2) {
|
|
355
|
+
const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
|
|
356
|
+
const points = Array.from(clean);
|
|
357
|
+
if (points.length <= MAX_NAME) return clean || "file";
|
|
358
|
+
const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
|
|
359
|
+
return points.slice(0, MAX_NAME - extension.length).join("") + extension;
|
|
360
|
+
}
|
|
361
|
+
function fileType(mimeType) {
|
|
362
|
+
const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
|
|
363
|
+
return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
|
|
364
|
+
}
|
|
365
|
+
function resourceBlock(file) {
|
|
366
|
+
return {
|
|
367
|
+
type: "resource",
|
|
368
|
+
resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// src/core/http.ts
|
|
373
|
+
var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
374
|
+
var USER_AGENT = "agent-connectors";
|
|
375
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
376
|
+
function errorCode(error) {
|
|
377
|
+
const code = error?.code;
|
|
378
|
+
return typeof code === "string" ? code : void 0;
|
|
379
|
+
}
|
|
380
|
+
function describe(error) {
|
|
381
|
+
const name2 = error?.name;
|
|
382
|
+
const code = errorCode(error);
|
|
383
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
384
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
385
|
+
if (code === "TOO_LARGE") return "the reply was too large";
|
|
386
|
+
return cleanVendorText(error?.message, 200) ?? "a network error";
|
|
387
|
+
}
|
|
388
|
+
function retryAfterSeconds(headers, now = Date.now()) {
|
|
389
|
+
const retryAfter = headers.get("retry-after");
|
|
390
|
+
if (retryAfter) {
|
|
391
|
+
const seconds = Number(retryAfter);
|
|
392
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
393
|
+
const date = Date.parse(retryAfter);
|
|
394
|
+
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
|
|
395
|
+
}
|
|
396
|
+
const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
|
|
397
|
+
if (reset) {
|
|
398
|
+
const value = Number(reset);
|
|
399
|
+
if (Number.isFinite(value) && value >= 0) {
|
|
400
|
+
return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return void 0;
|
|
404
|
+
}
|
|
405
|
+
function vendorCode(data) {
|
|
406
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
407
|
+
for (const key of ["error", "code"]) {
|
|
408
|
+
const value = data[key];
|
|
409
|
+
if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
|
|
410
|
+
}
|
|
411
|
+
return void 0;
|
|
412
|
+
}
|
|
413
|
+
function vendorMessage(data) {
|
|
414
|
+
if (typeof data === "string") return cleanVendorText(data);
|
|
415
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
416
|
+
const record = data;
|
|
417
|
+
for (const key of ["message", "error_description", "error", "detail", "title"]) {
|
|
418
|
+
const value = record[key];
|
|
419
|
+
if (typeof value === "string" && value.trim()) return cleanVendorText(value);
|
|
420
|
+
const nested = value?.message;
|
|
421
|
+
if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
|
|
422
|
+
}
|
|
423
|
+
if (Array.isArray(record["errors"])) {
|
|
424
|
+
const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
|
|
425
|
+
if (messages.length) return cleanVendorText(messages.join("; "));
|
|
426
|
+
}
|
|
427
|
+
return void 0;
|
|
428
|
+
}
|
|
429
|
+
var TooLarge = class extends Error {
|
|
430
|
+
constructor(limit) {
|
|
431
|
+
super(`the reply is larger than ${formatNumber(limit)} bytes`);
|
|
432
|
+
this.limit = limit;
|
|
433
|
+
}
|
|
434
|
+
limit;
|
|
435
|
+
};
|
|
436
|
+
async function readCapped(response, maxBytes) {
|
|
437
|
+
const declared = Number(response.headers.get("content-length"));
|
|
438
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
439
|
+
await response.body?.cancel().catch(() => {
|
|
440
|
+
});
|
|
441
|
+
throw new TooLarge(maxBytes);
|
|
442
|
+
}
|
|
443
|
+
if (!response.body) return new Uint8Array(0);
|
|
444
|
+
const reader = response.body.getReader();
|
|
445
|
+
const chunks = [];
|
|
446
|
+
let total = 0;
|
|
447
|
+
for (; ; ) {
|
|
448
|
+
const { done, value } = await reader.read();
|
|
449
|
+
if (done) break;
|
|
450
|
+
total += value.byteLength;
|
|
451
|
+
if (total > maxBytes) {
|
|
452
|
+
await reader.cancel().catch(() => {
|
|
453
|
+
});
|
|
454
|
+
throw new TooLarge(maxBytes);
|
|
455
|
+
}
|
|
456
|
+
chunks.push(value);
|
|
457
|
+
}
|
|
458
|
+
const bytes = new Uint8Array(total);
|
|
459
|
+
let offset = 0;
|
|
460
|
+
for (const chunk of chunks) {
|
|
461
|
+
bytes.set(chunk, offset);
|
|
462
|
+
offset += chunk.byteLength;
|
|
463
|
+
}
|
|
464
|
+
return bytes;
|
|
465
|
+
}
|
|
466
|
+
function parseBody(bytes, contentType) {
|
|
467
|
+
if (bytes.length === 0) return null;
|
|
468
|
+
const text2 = utf8Decode(bytes);
|
|
469
|
+
if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text2)) {
|
|
470
|
+
try {
|
|
471
|
+
return JSON.parse(text2);
|
|
472
|
+
} catch {
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return text2;
|
|
476
|
+
}
|
|
477
|
+
function createHttp(env) {
|
|
478
|
+
const { label, ctx } = env;
|
|
479
|
+
const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
|
|
480
|
+
const checkCredentials = env.credentialLabels.length ? `Check that the ${andList(env.credentialLabels)} ${env.credentialLabels.length > 1 ? "are" : "is"} correct and still active.` : `Check that the ${label} credentials are correct and still active.`;
|
|
481
|
+
function failureFor(status, headers, data, request) {
|
|
482
|
+
const message = vendorMessage(data);
|
|
483
|
+
const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
|
|
484
|
+
const retryAfter = retryAfterSeconds(headers);
|
|
485
|
+
const code = vendorCode(data);
|
|
486
|
+
const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
|
|
487
|
+
const custom = request.errors?.[status];
|
|
488
|
+
const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
|
|
489
|
+
if (status >= 500) {
|
|
490
|
+
if (request.write) {
|
|
491
|
+
return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
|
|
492
|
+
}
|
|
493
|
+
return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
|
|
494
|
+
}
|
|
495
|
+
if (status === 429) {
|
|
496
|
+
return new ToolFailure(
|
|
497
|
+
`${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
|
|
498
|
+
{ status, ...extra }
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
if (status === 401) {
|
|
502
|
+
return new ToolFailure(
|
|
503
|
+
withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
|
|
504
|
+
{ status, ...extra }
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
|
|
508
|
+
if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
|
|
509
|
+
if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
|
|
510
|
+
return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
|
|
511
|
+
}
|
|
512
|
+
async function api(request) {
|
|
513
|
+
const method = request.method ?? "GET";
|
|
514
|
+
if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
|
|
515
|
+
throw new Error(`read-only tool sent ${method}`);
|
|
516
|
+
}
|
|
517
|
+
const origin = request.origin ?? env.origins[0];
|
|
518
|
+
if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
|
|
519
|
+
const url = new URL(request.path, origin);
|
|
520
|
+
if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
|
|
521
|
+
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
522
|
+
if (value === void 0 || value === null) continue;
|
|
523
|
+
if (Array.isArray(value)) {
|
|
524
|
+
url.searchParams.delete(key);
|
|
525
|
+
for (const item of value) url.searchParams.append(key, String(item));
|
|
526
|
+
} else {
|
|
527
|
+
url.searchParams.set(key, String(value));
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
const headers = {
|
|
531
|
+
accept: "application/json",
|
|
532
|
+
"user-agent": USER_AGENT,
|
|
533
|
+
...request.auth === false ? {} : env.authHeaders(),
|
|
534
|
+
...request.headers
|
|
535
|
+
};
|
|
536
|
+
let body2;
|
|
537
|
+
if (request.json !== void 0) {
|
|
538
|
+
body2 = JSON.stringify(request.json);
|
|
539
|
+
headers["content-type"] = "application/json";
|
|
540
|
+
} else if (request.body) {
|
|
541
|
+
body2 = request.body;
|
|
542
|
+
headers["content-type"] = request.contentType ?? "application/octet-stream";
|
|
543
|
+
}
|
|
544
|
+
const started = Date.now();
|
|
545
|
+
if (request.write) env.onWriteSent();
|
|
546
|
+
let response;
|
|
547
|
+
try {
|
|
548
|
+
response = await ctx.fetch(url.toString(), { method, headers, ...body2 !== void 0 ? { body: body2 } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
|
|
549
|
+
} catch (error) {
|
|
550
|
+
env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
|
|
551
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
552
|
+
throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
|
|
553
|
+
}
|
|
554
|
+
if (request.write) {
|
|
555
|
+
throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
|
|
556
|
+
}
|
|
557
|
+
if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
|
|
558
|
+
throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
|
|
559
|
+
}
|
|
560
|
+
env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
|
|
561
|
+
let bytes;
|
|
562
|
+
try {
|
|
563
|
+
bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
|
|
564
|
+
} catch (error) {
|
|
565
|
+
if (request.write && (response.ok || response.status >= 500)) {
|
|
566
|
+
throw new OutcomeUnknown(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}), so it is not known whether the change was made.`);
|
|
567
|
+
}
|
|
568
|
+
throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
|
|
569
|
+
}
|
|
570
|
+
const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
|
|
571
|
+
if (response.ok) return { status: response.status, headers: response.headers, data };
|
|
572
|
+
throw failureFor(response.status, response.headers, data, request);
|
|
573
|
+
}
|
|
574
|
+
async function media(rawUrl, options) {
|
|
575
|
+
const { what } = options;
|
|
576
|
+
let url;
|
|
577
|
+
try {
|
|
578
|
+
url = new URL(rawUrl);
|
|
579
|
+
} catch {
|
|
580
|
+
throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
|
|
581
|
+
}
|
|
582
|
+
if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
|
|
583
|
+
const started = Date.now();
|
|
584
|
+
let response;
|
|
585
|
+
try {
|
|
586
|
+
response = await ctx.fetch(url.toString(), {
|
|
587
|
+
method: "GET",
|
|
588
|
+
headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
|
|
589
|
+
...ctx.signal ? { signal: ctx.signal } : {}
|
|
590
|
+
});
|
|
591
|
+
} catch (error) {
|
|
592
|
+
env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
|
|
593
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
594
|
+
throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
|
|
595
|
+
}
|
|
596
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
597
|
+
}
|
|
598
|
+
env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
|
|
599
|
+
if (!response.ok) {
|
|
600
|
+
await response.body?.cancel().catch(() => {
|
|
601
|
+
});
|
|
602
|
+
throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
|
|
603
|
+
}
|
|
604
|
+
try {
|
|
605
|
+
const bytes = await readCapped(response, options.maxBytes);
|
|
606
|
+
return { bytes, contentType: response.headers.get("content-type") };
|
|
607
|
+
} catch (error) {
|
|
608
|
+
if (error instanceof TooLarge) {
|
|
609
|
+
throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
|
|
610
|
+
}
|
|
611
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
return { api, media };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/core/origins.ts
|
|
618
|
+
function parseSiteUrl(value) {
|
|
619
|
+
const text2 = typeof value === "string" ? value.trim() : "";
|
|
620
|
+
if (!text2) return { ok: false, problem: "is empty" };
|
|
621
|
+
let url;
|
|
622
|
+
try {
|
|
623
|
+
url = new URL(text2.includes("://") ? text2 : `https://${text2}`);
|
|
624
|
+
} catch {
|
|
625
|
+
return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
|
|
626
|
+
}
|
|
627
|
+
if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
|
|
628
|
+
if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
|
|
629
|
+
if (!url.hostname) return { ok: false, problem: "has no host name" };
|
|
630
|
+
return { ok: true, url, origin: url.origin };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// src/core/schema.ts
|
|
634
|
+
var patterns = /* @__PURE__ */ new Map();
|
|
635
|
+
function patternOf(source) {
|
|
636
|
+
let compiled = patterns.get(source);
|
|
637
|
+
if (!compiled) {
|
|
638
|
+
compiled = new RegExp(source, "u");
|
|
639
|
+
patterns.set(source, compiled);
|
|
640
|
+
}
|
|
641
|
+
return compiled;
|
|
642
|
+
}
|
|
643
|
+
function isPlainObject(value) {
|
|
644
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
645
|
+
}
|
|
646
|
+
function isHttpUrl(value) {
|
|
647
|
+
try {
|
|
648
|
+
const url = new URL(value);
|
|
649
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
650
|
+
} catch {
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
function name(path) {
|
|
655
|
+
return `\`${path}\``;
|
|
656
|
+
}
|
|
657
|
+
function child(path, key) {
|
|
658
|
+
return path ? `${path}.${key}` : key;
|
|
659
|
+
}
|
|
660
|
+
function checkValue(schema, value, path, issues) {
|
|
661
|
+
switch (schema.type) {
|
|
662
|
+
case "object":
|
|
663
|
+
checkObject(schema, value, path, issues);
|
|
664
|
+
return;
|
|
665
|
+
case "array": {
|
|
666
|
+
if (!Array.isArray(value)) {
|
|
667
|
+
issues.push(`${name(path)} must be an array`);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
671
|
+
issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
|
|
672
|
+
}
|
|
673
|
+
if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
|
|
674
|
+
issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
|
|
675
|
+
}
|
|
676
|
+
if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
|
|
677
|
+
issues.push(`${name(path)} must not repeat an item`);
|
|
678
|
+
}
|
|
679
|
+
if (schema.items) {
|
|
680
|
+
value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
|
|
681
|
+
}
|
|
682
|
+
break;
|
|
683
|
+
}
|
|
684
|
+
case "string": {
|
|
685
|
+
if (typeof value !== "string") {
|
|
686
|
+
issues.push(`${name(path)} must be a string`);
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
const length = Array.from(value).length;
|
|
690
|
+
if (schema.minLength !== void 0 && length < schema.minLength) {
|
|
691
|
+
issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
|
|
692
|
+
}
|
|
693
|
+
if (schema.maxLength !== void 0 && length > schema.maxLength) {
|
|
694
|
+
issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
|
|
695
|
+
}
|
|
696
|
+
if (schema.format === "uri" && !isHttpUrl(value)) {
|
|
697
|
+
issues.push(`${name(path)} must be an absolute http(s) URL`);
|
|
698
|
+
} else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
|
|
699
|
+
issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
|
|
700
|
+
}
|
|
701
|
+
break;
|
|
702
|
+
}
|
|
703
|
+
case "integer":
|
|
704
|
+
case "number": {
|
|
705
|
+
if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
|
|
706
|
+
issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
710
|
+
issues.push(`${name(path)} must be at least ${schema.minimum}`);
|
|
711
|
+
}
|
|
712
|
+
if (schema.maximum !== void 0 && value > schema.maximum) {
|
|
713
|
+
issues.push(`${name(path)} must be at most ${schema.maximum}`);
|
|
714
|
+
}
|
|
715
|
+
break;
|
|
716
|
+
}
|
|
717
|
+
case "boolean":
|
|
718
|
+
if (typeof value !== "boolean") {
|
|
719
|
+
issues.push(`${name(path)} must be true or false`);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
break;
|
|
723
|
+
default:
|
|
724
|
+
break;
|
|
725
|
+
}
|
|
726
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
727
|
+
issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
function checkObject(schema, value, path, issues) {
|
|
731
|
+
if (!isPlainObject(value)) {
|
|
732
|
+
issues.push(`${path ? name(path) : "the arguments"} must be an object`);
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
const properties = schema.properties ?? {};
|
|
736
|
+
for (const key of schema.required ?? []) {
|
|
737
|
+
if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
|
|
738
|
+
}
|
|
739
|
+
const unknown = [];
|
|
740
|
+
for (const [key, item] of Object.entries(value)) {
|
|
741
|
+
const property = properties[key];
|
|
742
|
+
if (!property) {
|
|
743
|
+
if (schema.additionalProperties === false) unknown.push(key);
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
if (item === void 0 || item === null) continue;
|
|
747
|
+
checkValue(property, item, child(path, key), issues);
|
|
748
|
+
}
|
|
749
|
+
if (unknown.length) {
|
|
750
|
+
const known = Object.keys(properties);
|
|
751
|
+
issues.push(`unknown ${path ? `field${unknown.length > 1 ? "s" : ""} in ${name(path)}` : `argument${unknown.length > 1 ? "s" : ""}`} ${unknown.map((key) => JSON.stringify(key)).join(", ")}` + (known.length ? ` (expected: ${known.join(", ")})` : ""));
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
function copyDefault(value) {
|
|
755
|
+
return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
|
|
756
|
+
}
|
|
757
|
+
function validateArguments(schema, args) {
|
|
758
|
+
const input = args === void 0 || args === null ? {} : args;
|
|
759
|
+
if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
|
|
760
|
+
const value = { ...input };
|
|
761
|
+
if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
|
|
762
|
+
const issues = [];
|
|
763
|
+
checkObject(schema, value, "", issues);
|
|
764
|
+
if (issues.length) return { ok: false, issues };
|
|
765
|
+
for (const [key, property] of Object.entries(schema.properties ?? {})) {
|
|
766
|
+
if (value[key] === null) delete value[key];
|
|
767
|
+
if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
|
|
768
|
+
}
|
|
769
|
+
return { ok: true, value };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/core/upload-hosts.ts
|
|
773
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
774
|
+
function uploadHostProblem(entry) {
|
|
775
|
+
if (typeof entry !== "string") return "must be a host name";
|
|
776
|
+
const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
|
|
777
|
+
const labels = name2.split(".");
|
|
778
|
+
if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
|
|
779
|
+
return "must be a lowercase host name like uploads.example.com, or one with a leading dot like .example.com for every host under it";
|
|
780
|
+
}
|
|
781
|
+
if (labels.length < 2) return "needs at least two labels, like example.com";
|
|
782
|
+
if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
|
|
783
|
+
return void 0;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// src/core/connector.ts
|
|
787
|
+
var ANNOTATIONS = {
|
|
788
|
+
read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
789
|
+
create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
790
|
+
update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
791
|
+
delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
792
|
+
write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
|
|
793
|
+
};
|
|
794
|
+
var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
|
|
795
|
+
var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
796
|
+
var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
797
|
+
var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
798
|
+
var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
|
|
799
|
+
var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
800
|
+
var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
|
|
801
|
+
function deepFreeze(value) {
|
|
802
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
803
|
+
Object.freeze(value);
|
|
804
|
+
for (const item of Object.values(value)) deepFreeze(item);
|
|
805
|
+
}
|
|
806
|
+
return value;
|
|
807
|
+
}
|
|
808
|
+
function assertDefinition(def) {
|
|
809
|
+
const problem = (message) => {
|
|
810
|
+
throw new Error(`connector "${def.vendor}": ${message}`);
|
|
811
|
+
};
|
|
812
|
+
if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
|
|
813
|
+
if (!def.label?.trim()) problem("label is required");
|
|
814
|
+
const originFields = def.originFields ?? [];
|
|
815
|
+
if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
|
|
816
|
+
for (const origin of def.origins) {
|
|
817
|
+
let url;
|
|
818
|
+
try {
|
|
819
|
+
url = new URL(origin);
|
|
820
|
+
} catch {
|
|
821
|
+
}
|
|
822
|
+
if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
|
|
823
|
+
}
|
|
824
|
+
for (const name2 of def.credentials) {
|
|
825
|
+
if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
|
|
826
|
+
}
|
|
827
|
+
for (const [index, name2] of originFields.entries()) {
|
|
828
|
+
if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
|
|
829
|
+
if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
|
|
830
|
+
}
|
|
831
|
+
const names = /* @__PURE__ */ new Set();
|
|
832
|
+
for (const tool of def.tools) {
|
|
833
|
+
if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
834
|
+
if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
|
|
835
|
+
names.add(tool.name);
|
|
836
|
+
if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
|
|
837
|
+
if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
|
|
838
|
+
if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
|
|
839
|
+
if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
|
|
840
|
+
problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
for (const tool of def.tools) {
|
|
844
|
+
if (tool.kind === "read") continue;
|
|
845
|
+
const check = def.tools.find((candidate) => candidate.name === tool.check);
|
|
846
|
+
if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
|
|
847
|
+
}
|
|
848
|
+
assertUploadHosts(def, problem);
|
|
849
|
+
assertRequiredCredentials(def, problem);
|
|
850
|
+
assertAccountPickers(def, problem);
|
|
851
|
+
}
|
|
852
|
+
function assertUploadHosts(def, problem) {
|
|
853
|
+
const hosts = def.uploadHosts;
|
|
854
|
+
if (hosts === void 0) return;
|
|
855
|
+
if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
|
|
856
|
+
hosts.forEach((entry, index) => {
|
|
857
|
+
const wrong = uploadHostProblem(entry);
|
|
858
|
+
if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
|
|
859
|
+
if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
function assertRequiredCredentials(def, problem) {
|
|
863
|
+
const required = def.requiredCredentials;
|
|
864
|
+
if (required === void 0) return;
|
|
865
|
+
if (!Array.isArray(required) || !required.length) {
|
|
866
|
+
problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
|
|
867
|
+
}
|
|
868
|
+
required.forEach((list, index) => {
|
|
869
|
+
const which = `requiredCredentials[${index}]`;
|
|
870
|
+
if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
|
|
871
|
+
list.forEach((name2, position) => {
|
|
872
|
+
if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
|
|
873
|
+
if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
|
|
874
|
+
});
|
|
875
|
+
});
|
|
876
|
+
const lists = required;
|
|
877
|
+
lists.forEach((list, index) => {
|
|
878
|
+
const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
|
|
879
|
+
if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
|
|
880
|
+
if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
|
|
881
|
+
problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
|
|
882
|
+
}
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
function isDotPath(value) {
|
|
886
|
+
return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
|
|
887
|
+
}
|
|
888
|
+
function assertAccountPickers(def, problem) {
|
|
889
|
+
const pickers = def.accountPickers;
|
|
890
|
+
if (pickers === void 0) return;
|
|
891
|
+
if (!Array.isArray(pickers)) problem("accountPickers must be a list");
|
|
892
|
+
const keys = /* @__PURE__ */ new Set();
|
|
893
|
+
for (const item of pickers) {
|
|
894
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
|
|
895
|
+
const picker = item;
|
|
896
|
+
const key = picker["key"];
|
|
897
|
+
if (typeof key !== "string" || !PICKER_KEY_PATTERN.test(key)) problem(`account picker ${JSON.stringify(key)}: key must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
898
|
+
if (keys.has(key)) problem(`account picker ${key} is defined twice`);
|
|
899
|
+
keys.add(key);
|
|
900
|
+
const fail = (message) => problem(`account picker ${key}: ${message}`);
|
|
901
|
+
const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
|
|
902
|
+
if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
|
|
903
|
+
const { label, description, multiple, legacyField } = picker;
|
|
904
|
+
if (typeof label !== "string" || !label.trim()) fail("label is required");
|
|
905
|
+
if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
|
|
906
|
+
fail("description, when given, must be a text of 1 to 1024 characters");
|
|
907
|
+
}
|
|
908
|
+
if (typeof multiple !== "boolean") fail("multiple must be true or false");
|
|
909
|
+
const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
|
|
910
|
+
if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
|
|
911
|
+
if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
|
|
912
|
+
for (const field of ["idField", "nameField"]) {
|
|
913
|
+
if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
|
|
914
|
+
}
|
|
915
|
+
if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
|
|
916
|
+
fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
function copyPicker(picker) {
|
|
921
|
+
return {
|
|
922
|
+
key: picker.key,
|
|
923
|
+
label: picker.label,
|
|
924
|
+
...picker.description !== void 0 ? { description: picker.description } : {},
|
|
925
|
+
multiple: picker.multiple,
|
|
926
|
+
tool: picker.tool,
|
|
927
|
+
idField: picker.idField,
|
|
928
|
+
nameField: picker.nameField,
|
|
929
|
+
...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
function result(payload, isError, files = []) {
|
|
933
|
+
return {
|
|
934
|
+
content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
|
|
935
|
+
...isError ? { isError: true } : {}
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
function failure(message, details = {}) {
|
|
939
|
+
return result({ error: message, ...details }, true);
|
|
940
|
+
}
|
|
941
|
+
function trimmed(values) {
|
|
942
|
+
const out = {};
|
|
943
|
+
if (typeof values !== "object" || values === null) return out;
|
|
944
|
+
for (const [key, value] of Object.entries(values)) {
|
|
945
|
+
if (value === void 0 || value === null) continue;
|
|
946
|
+
const text2 = String(value).trim();
|
|
947
|
+
if (text2) out[key] = text2;
|
|
948
|
+
}
|
|
949
|
+
return out;
|
|
950
|
+
}
|
|
951
|
+
function defineConnector(def) {
|
|
952
|
+
assertDefinition(def);
|
|
953
|
+
const { label } = def;
|
|
954
|
+
const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
|
|
955
|
+
const toolList = def.tools.map((tool) => tool.name).join(", ");
|
|
956
|
+
const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
|
|
957
|
+
const required = requiredAlternatives(def);
|
|
958
|
+
const notConnected = (unmet) => {
|
|
959
|
+
const [first2] = unmet;
|
|
960
|
+
if (unmet.length === 1 && first2) {
|
|
961
|
+
return `${label} is not connected: the ${andList(first2.map(credentialLabel))} ${first2.length > 1 ? "are" : "is"} missing.`;
|
|
962
|
+
}
|
|
963
|
+
return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
|
|
964
|
+
};
|
|
965
|
+
const descriptors = def.tools.map((tool) => ({
|
|
966
|
+
name: tool.name,
|
|
967
|
+
title: tool.title,
|
|
968
|
+
description: tool.description,
|
|
969
|
+
inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
|
|
970
|
+
annotations: { ...ANNOTATIONS[tool.kind] }
|
|
971
|
+
}));
|
|
972
|
+
async function call(toolName, args, ctx) {
|
|
973
|
+
const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
|
|
974
|
+
if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
|
|
975
|
+
if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
|
|
976
|
+
const log = (text2) => {
|
|
977
|
+
try {
|
|
978
|
+
ctx.log?.(text2);
|
|
979
|
+
} catch {
|
|
980
|
+
}
|
|
981
|
+
};
|
|
982
|
+
const given = trimmed(ctx.credentials);
|
|
983
|
+
const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
|
|
984
|
+
const has = (name2) => Boolean(credentials[name2]);
|
|
985
|
+
const unmet = unmetAlternatives(required, has);
|
|
986
|
+
if (unmet.length) return failure(notConnected(unmet));
|
|
987
|
+
const complete = required.filter((list) => list.every(has));
|
|
988
|
+
const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
|
|
989
|
+
const fieldOrigins = /* @__PURE__ */ new Map();
|
|
990
|
+
for (const name2 of def.originFields ?? []) {
|
|
991
|
+
if (!given[name2] && !inUse.includes(name2)) continue;
|
|
992
|
+
const site = parseSiteUrl(given[name2] ?? "");
|
|
993
|
+
if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
|
|
994
|
+
fieldOrigins.set(name2, site.origin);
|
|
995
|
+
}
|
|
996
|
+
const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
|
|
997
|
+
const parsed = validateArguments(tool.inputSchema, args);
|
|
998
|
+
if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
|
|
999
|
+
const frozenCredentials = Object.freeze({ ...credentials });
|
|
1000
|
+
let writeSent = false;
|
|
1001
|
+
const fileLimit = fileLimitOf(ctx);
|
|
1002
|
+
const files = [];
|
|
1003
|
+
let fileBytes = 0;
|
|
1004
|
+
const http = createHttp({
|
|
1005
|
+
vendor: def.vendor,
|
|
1006
|
+
label,
|
|
1007
|
+
tool: tool.name,
|
|
1008
|
+
readOnly: tool.kind === "read",
|
|
1009
|
+
origins,
|
|
1010
|
+
// A 401 names the credentials in use (for a module that needs none, the ones given).
|
|
1011
|
+
credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
|
|
1012
|
+
ctx,
|
|
1013
|
+
authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
|
|
1014
|
+
log,
|
|
1015
|
+
onWriteSent: () => {
|
|
1016
|
+
writeSent = true;
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
const helpers = {
|
|
1020
|
+
tool: tool.name,
|
|
1021
|
+
credentials: frozenCredentials,
|
|
1022
|
+
ctx,
|
|
1023
|
+
origins: Object.freeze([...origins]),
|
|
1024
|
+
originOf: (credential) => {
|
|
1025
|
+
const origin = fieldOrigins.get(credential);
|
|
1026
|
+
if (!origin) throw new Error(`${credential} gives no origin in this call`);
|
|
1027
|
+
return origin;
|
|
1028
|
+
},
|
|
1029
|
+
api: http.api,
|
|
1030
|
+
media: http.media,
|
|
1031
|
+
page: (input) => fitPage(input),
|
|
1032
|
+
cursor: (cursor) => decodeCursor(tool.name, cursor),
|
|
1033
|
+
makeCursor: (state) => encodeCursor(tool.name, state),
|
|
1034
|
+
fileLimit: () => fileLimit,
|
|
1035
|
+
file: ({ name: name2, mimeType, bytes }) => {
|
|
1036
|
+
if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
|
|
1037
|
+
const total = fileBytes + bytes.byteLength;
|
|
1038
|
+
if (total > fileLimit) {
|
|
1039
|
+
throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total)} bytes in all, more than the ${formatNumber(fileLimit)} bytes this host takes from one call.` : `The file has ${formatNumber(bytes.byteLength)} bytes, more than the ${formatNumber(fileLimit)} bytes this host takes.`);
|
|
1040
|
+
}
|
|
1041
|
+
fileBytes = total;
|
|
1042
|
+
const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
|
|
1043
|
+
files.push({ ...info, bytes });
|
|
1044
|
+
return { ...info };
|
|
1045
|
+
},
|
|
1046
|
+
log
|
|
1047
|
+
};
|
|
1048
|
+
try {
|
|
1049
|
+
const data = await tool.run(parsed.value, helpers);
|
|
1050
|
+
const fitted = shrinkToFit(data ?? {});
|
|
1051
|
+
if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
|
|
1052
|
+
const payload = fitted.value;
|
|
1053
|
+
return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
|
|
1054
|
+
} catch (error) {
|
|
1055
|
+
if (error instanceof OutcomeUnknown) {
|
|
1056
|
+
return result({
|
|
1057
|
+
outcome: "unknown",
|
|
1058
|
+
check: tool.check,
|
|
1059
|
+
error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
|
|
1060
|
+
}, true);
|
|
1061
|
+
}
|
|
1062
|
+
if (error instanceof ToolFailure) return failure(error.message, error.details);
|
|
1063
|
+
log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
|
|
1064
|
+
if (writeSent) {
|
|
1065
|
+
return result({
|
|
1066
|
+
outcome: "unknown",
|
|
1067
|
+
check: tool.check,
|
|
1068
|
+
error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
|
|
1069
|
+
}, true);
|
|
1070
|
+
}
|
|
1071
|
+
return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
return deepFreeze({
|
|
1075
|
+
vendor: def.vendor,
|
|
1076
|
+
origins: [...def.origins],
|
|
1077
|
+
originFields: [...def.originFields ?? []],
|
|
1078
|
+
uploadHosts: [...def.uploadHosts ?? []],
|
|
1079
|
+
credentials: [...def.credentials],
|
|
1080
|
+
requiredCredentials: required.map((list) => [...list]),
|
|
1081
|
+
accountPickers: (def.accountPickers ?? []).map(copyPicker),
|
|
1082
|
+
tools: descriptors,
|
|
1083
|
+
call
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
// src/core/jwt.ts
|
|
1088
|
+
var TOKEN_EARLY_MS = 5 * 60 * 1e3;
|
|
1089
|
+
|
|
1090
|
+
// src/vendors/apollo/shape.ts
|
|
1091
|
+
function compact(value) {
|
|
1092
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => {
|
|
1093
|
+
if (item === void 0 || item === null || item === "") return false;
|
|
1094
|
+
if (Array.isArray(item)) return item.length > 0;
|
|
1095
|
+
if (typeof item === "object") return Object.keys(item).length > 0;
|
|
1096
|
+
return true;
|
|
1097
|
+
}));
|
|
1098
|
+
}
|
|
1099
|
+
var text = (value, max = 500) => typeof value === "string" && value ? truncate(value, max) : void 0;
|
|
1100
|
+
var first = (value, count) => Array.isArray(value) && value.length ? value.slice(0, count) : void 0;
|
|
1101
|
+
function trimOrganization(org) {
|
|
1102
|
+
if (!org || typeof org !== "object") return {};
|
|
1103
|
+
return compact({
|
|
1104
|
+
id: org.id,
|
|
1105
|
+
name: org.name,
|
|
1106
|
+
website_url: org.website_url,
|
|
1107
|
+
primary_domain: org.primary_domain,
|
|
1108
|
+
linkedin_url: org.linkedin_url,
|
|
1109
|
+
industry: org.industry,
|
|
1110
|
+
keywords: first(org.keywords, 15),
|
|
1111
|
+
estimated_num_employees: org.estimated_num_employees,
|
|
1112
|
+
annual_revenue: org.annual_revenue,
|
|
1113
|
+
annual_revenue_printed: org.annual_revenue_printed,
|
|
1114
|
+
total_funding: org.total_funding,
|
|
1115
|
+
total_funding_printed: org.total_funding_printed,
|
|
1116
|
+
latest_funding_stage: org.latest_funding_stage,
|
|
1117
|
+
latest_funding_round_date: org.latest_funding_round_date,
|
|
1118
|
+
founded_year: org.founded_year,
|
|
1119
|
+
publicly_traded_symbol: org.publicly_traded_symbol,
|
|
1120
|
+
phone: org.primary_phone?.sanitized_number ?? org.primary_phone?.number ?? org.phone,
|
|
1121
|
+
city: org.city,
|
|
1122
|
+
state: org.state,
|
|
1123
|
+
country: org.country,
|
|
1124
|
+
short_description: text(org.short_description),
|
|
1125
|
+
technology_names: first(org.technology_names, 30),
|
|
1126
|
+
// Fields of a people search result's organization: what Apollo has, without the values.
|
|
1127
|
+
has_industry: org.has_industry,
|
|
1128
|
+
has_phone: org.has_phone,
|
|
1129
|
+
has_employee_count: org.has_employee_count
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
function trimPerson(person) {
|
|
1133
|
+
if (!person || typeof person !== "object") return null;
|
|
1134
|
+
const history = Array.isArray(person.employment_history) ? person.employment_history : [];
|
|
1135
|
+
return compact({
|
|
1136
|
+
id: person.id,
|
|
1137
|
+
first_name: person.first_name,
|
|
1138
|
+
last_name: person.last_name,
|
|
1139
|
+
last_name_obfuscated: person.last_name_obfuscated,
|
|
1140
|
+
name: person.name,
|
|
1141
|
+
title: person.title,
|
|
1142
|
+
headline: text(person.headline, 200),
|
|
1143
|
+
email: person.email,
|
|
1144
|
+
email_status: person.email_status,
|
|
1145
|
+
personal_emails: first(person.personal_emails, 5),
|
|
1146
|
+
phone_numbers: first(person.phone_numbers, 5)?.map((phone) => compact({ number: phone?.sanitized_number ?? phone?.raw_number, type: phone?.type_cd ?? phone?.type, status: phone?.status_cd ?? phone?.status })),
|
|
1147
|
+
linkedin_url: person.linkedin_url,
|
|
1148
|
+
seniority: person.seniority,
|
|
1149
|
+
departments: first(person.departments, 5),
|
|
1150
|
+
city: person.city,
|
|
1151
|
+
state: person.state,
|
|
1152
|
+
country: person.country,
|
|
1153
|
+
has_email: person.has_email,
|
|
1154
|
+
has_direct_phone: person.has_direct_phone,
|
|
1155
|
+
has_city: person.has_city,
|
|
1156
|
+
has_country: person.has_country,
|
|
1157
|
+
organization_id: person.organization_id,
|
|
1158
|
+
organization: trimOrganization(person.organization),
|
|
1159
|
+
employment_history: history.length ? history.slice(0, 3).map((job) => compact({ title: job?.title, organization_name: job?.organization_name, start_date: job?.start_date, end_date: job?.end_date, current: job?.current })) : void 0
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
var phones = (value) => first(value, 5)?.map((phone) => compact({ number: phone?.sanitized_number ?? phone?.raw_number, type: phone?.type_cd ?? phone?.type }));
|
|
1163
|
+
function trimContact(contact) {
|
|
1164
|
+
return compact({
|
|
1165
|
+
id: contact?.id,
|
|
1166
|
+
first_name: contact?.first_name,
|
|
1167
|
+
last_name: contact?.last_name,
|
|
1168
|
+
name: contact?.name,
|
|
1169
|
+
title: contact?.title,
|
|
1170
|
+
email: contact?.email,
|
|
1171
|
+
email_status: contact?.email_status,
|
|
1172
|
+
organization_name: contact?.organization_name,
|
|
1173
|
+
account_id: contact?.account_id,
|
|
1174
|
+
owner_id: contact?.owner_id,
|
|
1175
|
+
contact_stage_id: contact?.contact_stage_id,
|
|
1176
|
+
label_ids: contact?.label_ids,
|
|
1177
|
+
linkedin_url: contact?.linkedin_url,
|
|
1178
|
+
phone_numbers: phones(contact?.phone_numbers),
|
|
1179
|
+
present_raw_address: contact?.present_raw_address,
|
|
1180
|
+
city: contact?.city,
|
|
1181
|
+
state: contact?.state,
|
|
1182
|
+
country: contact?.country,
|
|
1183
|
+
person_id: contact?.person_id,
|
|
1184
|
+
emailer_campaign_ids: contact?.emailer_campaign_ids,
|
|
1185
|
+
last_activity_date: contact?.last_activity_date,
|
|
1186
|
+
created_at: contact?.created_at,
|
|
1187
|
+
updated_at: contact?.updated_at,
|
|
1188
|
+
typed_custom_fields: contact?.typed_custom_fields
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
function trimAccount(account) {
|
|
1192
|
+
return compact({
|
|
1193
|
+
id: account?.id,
|
|
1194
|
+
name: account?.name,
|
|
1195
|
+
domain: account?.domain,
|
|
1196
|
+
website_url: account?.website_url,
|
|
1197
|
+
phone: account?.phone ?? account?.sanitized_phone,
|
|
1198
|
+
owner_id: account?.owner_id,
|
|
1199
|
+
account_stage_id: account?.account_stage_id,
|
|
1200
|
+
label_ids: account?.label_ids,
|
|
1201
|
+
organization_id: account?.organization_id,
|
|
1202
|
+
linkedin_url: account?.linkedin_url,
|
|
1203
|
+
raw_address: account?.raw_address,
|
|
1204
|
+
last_activity_date: account?.last_activity_date,
|
|
1205
|
+
created_at: account?.created_at,
|
|
1206
|
+
updated_at: account?.updated_at,
|
|
1207
|
+
typed_custom_fields: account?.typed_custom_fields
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
function trimDeal(deal) {
|
|
1211
|
+
return compact({
|
|
1212
|
+
id: deal?.id,
|
|
1213
|
+
name: deal?.name,
|
|
1214
|
+
amount: deal?.amount,
|
|
1215
|
+
opportunity_stage_id: deal?.opportunity_stage_id,
|
|
1216
|
+
opportunity_pipeline_id: deal?.opportunity_pipeline_id,
|
|
1217
|
+
owner_id: deal?.owner_id,
|
|
1218
|
+
account_id: deal?.account_id,
|
|
1219
|
+
closed_date: deal?.closed_date,
|
|
1220
|
+
is_closed: deal?.is_closed,
|
|
1221
|
+
is_won: deal?.is_won,
|
|
1222
|
+
forecast_category: deal?.forecast_category,
|
|
1223
|
+
deal_probability: deal?.deal_probability,
|
|
1224
|
+
source: deal?.source,
|
|
1225
|
+
created_at: deal?.created_at,
|
|
1226
|
+
updated_at: deal?.updated_at,
|
|
1227
|
+
typed_custom_fields: deal?.typed_custom_fields
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
function trimSequence(sequence) {
|
|
1231
|
+
return compact({
|
|
1232
|
+
id: sequence?.id,
|
|
1233
|
+
name: sequence?.name,
|
|
1234
|
+
active: sequence?.active,
|
|
1235
|
+
archived: sequence?.archived,
|
|
1236
|
+
num_steps: sequence?.num_steps,
|
|
1237
|
+
user_id: sequence?.user_id,
|
|
1238
|
+
created_at: sequence?.created_at,
|
|
1239
|
+
last_used_at: sequence?.last_used_at,
|
|
1240
|
+
unique_scheduled: sequence?.unique_scheduled,
|
|
1241
|
+
unique_delivered: sequence?.unique_delivered,
|
|
1242
|
+
unique_bounced: sequence?.unique_bounced,
|
|
1243
|
+
unique_opened: sequence?.unique_opened,
|
|
1244
|
+
unique_replied: sequence?.unique_replied,
|
|
1245
|
+
unique_clicked: sequence?.unique_clicked,
|
|
1246
|
+
unique_unsubscribed: sequence?.unique_unsubscribed,
|
|
1247
|
+
open_rate: sequence?.open_rate,
|
|
1248
|
+
reply_rate: sequence?.reply_rate,
|
|
1249
|
+
bounce_rate: sequence?.bounce_rate,
|
|
1250
|
+
click_rate: sequence?.click_rate
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
function trimTask(task) {
|
|
1254
|
+
return compact({
|
|
1255
|
+
id: task?.id,
|
|
1256
|
+
type: task?.type,
|
|
1257
|
+
status: task?.status,
|
|
1258
|
+
priority: task?.priority,
|
|
1259
|
+
title: task?.title ?? task?.subject,
|
|
1260
|
+
note: text(task?.note, 1e3),
|
|
1261
|
+
due_at: task?.due_at,
|
|
1262
|
+
completed_at: task?.completed_at,
|
|
1263
|
+
skipped_at: task?.skipped_at,
|
|
1264
|
+
contact_id: task?.contact_id,
|
|
1265
|
+
account_id: task?.account_id,
|
|
1266
|
+
user_id: task?.user_id,
|
|
1267
|
+
emailer_campaign_id: task?.emailer_campaign_id,
|
|
1268
|
+
created_at: task?.created_at
|
|
1269
|
+
});
|
|
1270
|
+
}
|
|
1271
|
+
function trimEmailMessage(message) {
|
|
1272
|
+
return compact({
|
|
1273
|
+
id: message?.id,
|
|
1274
|
+
emailer_campaign_id: message?.emailer_campaign_id,
|
|
1275
|
+
contact_id: message?.contact_id,
|
|
1276
|
+
user_id: message?.user_id,
|
|
1277
|
+
email_account_id: message?.email_account_id,
|
|
1278
|
+
to_email: message?.to_email,
|
|
1279
|
+
subject: text(message?.subject, 300),
|
|
1280
|
+
status: message?.status,
|
|
1281
|
+
reply_class: message?.reply_class,
|
|
1282
|
+
not_sent_reason: message?.not_sent_reason,
|
|
1283
|
+
due_at: message?.due_at,
|
|
1284
|
+
completed_at: message?.completed_at,
|
|
1285
|
+
num_opens: message?.num_opens,
|
|
1286
|
+
num_clicks: message?.num_clicks,
|
|
1287
|
+
replied: message?.replied
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
function trimCall(call) {
|
|
1291
|
+
return compact({
|
|
1292
|
+
id: call?.id,
|
|
1293
|
+
status: call?.status,
|
|
1294
|
+
inbound: call?.inbound,
|
|
1295
|
+
duration: call?.duration,
|
|
1296
|
+
start_time: call?.start_time,
|
|
1297
|
+
end_time: call?.end_time,
|
|
1298
|
+
note: text(call?.note, 1e3),
|
|
1299
|
+
contact_id: call?.contact_id,
|
|
1300
|
+
account_id: call?.account_id,
|
|
1301
|
+
user_id: call?.user_id,
|
|
1302
|
+
to_number: call?.to_number,
|
|
1303
|
+
from_number: call?.from_number,
|
|
1304
|
+
phone_call_outcome_id: call?.phone_call_outcome_id,
|
|
1305
|
+
phone_call_purpose_id: call?.phone_call_purpose_id,
|
|
1306
|
+
created_at: call?.created_at
|
|
1307
|
+
});
|
|
1308
|
+
}
|
|
1309
|
+
async function paged(h, cursor, options) {
|
|
1310
|
+
const state = h.cursor(cursor);
|
|
1311
|
+
const page = typeof state?.["p"] === "number" ? state["p"] : 1;
|
|
1312
|
+
const perPage = typeof state?.["n"] === "number" ? state["n"] : options.perPage;
|
|
1313
|
+
const skip = typeof state?.["s"] === "number" ? state["s"] : 0;
|
|
1314
|
+
const { data } = await h.api(options.request(page, perPage));
|
|
1315
|
+
const items = Array.isArray(data?.[options.listField ?? options.key]) ? data[options.listField ?? options.key] : [];
|
|
1316
|
+
const total = typeof data?.pagination?.total_entries === "number" ? data.pagination.total_entries : typeof data?.total_entries === "number" ? data.total_entries : void 0;
|
|
1317
|
+
const pages = typeof data?.pagination?.total_pages === "number" ? data.pagination.total_pages : total !== void 0 ? Math.ceil(total / perPage) : void 0;
|
|
1318
|
+
const more = (pages !== void 0 ? page < pages : items.length >= perPage) && page < (options.maxPage ?? Number.MAX_SAFE_INTEGER);
|
|
1319
|
+
return h.page({
|
|
1320
|
+
key: options.key,
|
|
1321
|
+
items: items.map(options.trim).slice(skip),
|
|
1322
|
+
extra: compact({ total_entries: total, page, ...options.extra?.(data) }),
|
|
1323
|
+
resumeAt: (index) => h.makeCursor({ p: page, n: perPage, s: skip + index }),
|
|
1324
|
+
...more && items.length ? { nextPage: h.makeCursor({ p: page + 1, n: perPage, s: 0 }) } : {}
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
// src/vendors/apollo/index.ts
|
|
1329
|
+
var LABEL2 = "Apollo";
|
|
1330
|
+
var BASE = "/api/v1";
|
|
1331
|
+
var NO_ACCESS = "Apollo refused the request: the API key cannot use this endpoint (a master API key, or a key given access to it, can) or the plan does not include it";
|
|
1332
|
+
function ap(h, request) {
|
|
1333
|
+
return h.api({ ...request, errors: { 403: NO_ACCESS, ...request.errors } });
|
|
1334
|
+
}
|
|
1335
|
+
var ID = { type: "string", pattern: "^[A-Za-z0-9_-]{1,64}$", description: "An Apollo id." };
|
|
1336
|
+
var IDS = (what, max) => ({ type: "array", items: ID, minItems: 1, maxItems: max, uniqueItems: true, description: `${what}, up to ${max}.` });
|
|
1337
|
+
var STRINGS = (what, max = 100) => ({
|
|
1338
|
+
type: "array",
|
|
1339
|
+
items: { type: "string", minLength: 1, maxLength: 300 },
|
|
1340
|
+
maxItems: max,
|
|
1341
|
+
uniqueItems: true,
|
|
1342
|
+
description: what
|
|
1343
|
+
});
|
|
1344
|
+
var PER_PAGE = (fallback = 25) => ({ type: "integer", minimum: 1, maximum: 100, default: fallback, description: `Results per page, 1 to 100 (default ${fallback}).` });
|
|
1345
|
+
var CURSOR = { type: "string", description: "nextCursor from the previous result; pass the other arguments unchanged." };
|
|
1346
|
+
var FILTERS = {
|
|
1347
|
+
type: "object",
|
|
1348
|
+
description: 'Any other parameter of this Apollo endpoint, by its documented name without [], e.g. {"organization_industries": ["software"], "revenue_range": {"min": 1000000}}.'
|
|
1349
|
+
};
|
|
1350
|
+
var EMAIL = { type: "string", minLength: 3, maxLength: 320, pattern: "^[^@\\s]+@[^@\\s]+$", description: "An email address." };
|
|
1351
|
+
var DATE_TIME = (what) => ({
|
|
1352
|
+
type: "string",
|
|
1353
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?)?$",
|
|
1354
|
+
description: `${what}, an ISO 8601 date or date-time.`
|
|
1355
|
+
});
|
|
1356
|
+
var CUSTOM_FIELDS = { type: "object", description: 'Custom field values by field id (see list_team_data custom_fields), e.g. {"6650f0c0a1b2c3d4e5f60789": "value"}.' };
|
|
1357
|
+
var DATE = { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$" };
|
|
1358
|
+
function merged(typed, filters) {
|
|
1359
|
+
const out = { ...filters };
|
|
1360
|
+
for (const [key, value] of Object.entries(typed)) {
|
|
1361
|
+
if (value !== void 0) out[key] = value;
|
|
1362
|
+
}
|
|
1363
|
+
return out;
|
|
1364
|
+
}
|
|
1365
|
+
function body(typed, filters) {
|
|
1366
|
+
return compact(merged(typed, filters));
|
|
1367
|
+
}
|
|
1368
|
+
function range(min, max) {
|
|
1369
|
+
return min === void 0 && max === void 0 ? void 0 : compact({ min, max });
|
|
1370
|
+
}
|
|
1371
|
+
function query(typed, filters) {
|
|
1372
|
+
const out = {};
|
|
1373
|
+
for (const [key, value] of Object.entries(merged(typed, filters))) {
|
|
1374
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
1375
|
+
if (Array.isArray(value)) {
|
|
1376
|
+
if (!value.length) continue;
|
|
1377
|
+
out[key.endsWith("]") ? key : `${key}[]`] = value.map((item) => typeof item === "object" ? JSON.stringify(item) : item);
|
|
1378
|
+
} else if (typeof value === "object") {
|
|
1379
|
+
for (const [part, inner] of Object.entries(value)) {
|
|
1380
|
+
if (typeof inner === "string" || typeof inner === "number" || typeof inner === "boolean") out[`${key}[${part}]`] = inner;
|
|
1381
|
+
}
|
|
1382
|
+
} else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
1383
|
+
out[key] = value;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
return out;
|
|
1387
|
+
}
|
|
1388
|
+
var PERSON_DETAILS = {
|
|
1389
|
+
type: "object",
|
|
1390
|
+
description: "Who to enrich: an Apollo person id, an email, a LinkedIn URL, or a name with a company domain or name.",
|
|
1391
|
+
properties: {
|
|
1392
|
+
id: ID,
|
|
1393
|
+
email: EMAIL,
|
|
1394
|
+
hashed_email: { type: "string", pattern: "^[0-9a-f]{32}([0-9a-f]{32})?$", description: "The MD5 or SHA-256 of the email." },
|
|
1395
|
+
linkedin_url: { type: "string", format: "uri", maxLength: 500 },
|
|
1396
|
+
first_name: { type: "string", maxLength: 100 },
|
|
1397
|
+
last_name: { type: "string", maxLength: 100 },
|
|
1398
|
+
name: { type: "string", maxLength: 200 },
|
|
1399
|
+
domain: { type: "string", maxLength: 200, description: "The employer's domain, without www." },
|
|
1400
|
+
organization_name: { type: "string", maxLength: 200 }
|
|
1401
|
+
},
|
|
1402
|
+
additionalProperties: false
|
|
1403
|
+
};
|
|
1404
|
+
var CONTACT_FIELDS = {
|
|
1405
|
+
first_name: { type: "string", maxLength: 100 },
|
|
1406
|
+
last_name: { type: "string", maxLength: 100 },
|
|
1407
|
+
email: EMAIL,
|
|
1408
|
+
title: { type: "string", maxLength: 300 },
|
|
1409
|
+
organization_name: { type: "string", maxLength: 300 },
|
|
1410
|
+
account_id: ID,
|
|
1411
|
+
owner_id: ID,
|
|
1412
|
+
website_url: { type: "string", maxLength: 500 },
|
|
1413
|
+
label_names: STRINGS("Lists (labels) the contact belongs to; on update this replaces them.", 50),
|
|
1414
|
+
contact_stage_id: ID,
|
|
1415
|
+
present_raw_address: { type: "string", maxLength: 300, description: 'Where the contact is, e.g. "Austin, United States".' },
|
|
1416
|
+
direct_phone: { type: "string", maxLength: 50 },
|
|
1417
|
+
corporate_phone: { type: "string", maxLength: 50 },
|
|
1418
|
+
mobile_phone: { type: "string", maxLength: 50 },
|
|
1419
|
+
home_phone: { type: "string", maxLength: 50 },
|
|
1420
|
+
other_phone: { type: "string", maxLength: 50 },
|
|
1421
|
+
linkedin_url: { type: "string", maxLength: 500 },
|
|
1422
|
+
typed_custom_fields: CUSTOM_FIELDS
|
|
1423
|
+
};
|
|
1424
|
+
var CONTACT = { type: "object", properties: CONTACT_FIELDS, additionalProperties: false };
|
|
1425
|
+
var ACCOUNT_FIELDS = {
|
|
1426
|
+
name: { type: "string", minLength: 1, maxLength: 300 },
|
|
1427
|
+
domain: { type: "string", maxLength: 200, description: "The company's domain, without www." },
|
|
1428
|
+
owner_id: ID,
|
|
1429
|
+
account_stage_id: ID,
|
|
1430
|
+
phone: { type: "string", maxLength: 50 },
|
|
1431
|
+
raw_address: { type: "string", maxLength: 300 },
|
|
1432
|
+
typed_custom_fields: CUSTOM_FIELDS
|
|
1433
|
+
};
|
|
1434
|
+
var TASK_TYPES = ["call", "outreach_manual_email", "linkedin_step_connect", "linkedin_step_message", "linkedin_step_view_profile", "linkedin_step_interact_post", "action_item"];
|
|
1435
|
+
async function createRecords(h, kind, records, options) {
|
|
1436
|
+
const trim = kind === "contacts" ? trimContact : trimAccount;
|
|
1437
|
+
if (records.length === 1 && !options.labels?.length) {
|
|
1438
|
+
const { data: data2 } = await ap(h, {
|
|
1439
|
+
method: "POST",
|
|
1440
|
+
path: `${BASE}/${kind}`,
|
|
1441
|
+
json: compact({ ...records[0], run_dedupe: options.dedupe || void 0 }),
|
|
1442
|
+
write: true,
|
|
1443
|
+
errors: { 422: `Apollo did not accept the ${kind === "contacts" ? "contact" : "account"}` }
|
|
1444
|
+
});
|
|
1445
|
+
const record = kind === "contacts" ? data2?.contact : data2?.account;
|
|
1446
|
+
return { [kind]: record ? [trim(record)] : [] };
|
|
1447
|
+
}
|
|
1448
|
+
const { data } = await ap(h, {
|
|
1449
|
+
method: "POST",
|
|
1450
|
+
path: `${BASE}/${kind}/bulk_create`,
|
|
1451
|
+
json: compact({ [kind]: records, run_dedupe: options.dedupe || void 0, append_label_names: options.labels }),
|
|
1452
|
+
write: true,
|
|
1453
|
+
errors: { 422: `Apollo did not accept the ${kind}` }
|
|
1454
|
+
});
|
|
1455
|
+
const created = Array.isArray(data?.[`created_${kind}`]) ? data[`created_${kind}`] : [];
|
|
1456
|
+
const existing = Array.isArray(data?.[`existing_${kind}`]) ? data[`existing_${kind}`] : [];
|
|
1457
|
+
if (!options.dedupe) return compact({ [kind]: created.map(trim), [`existing_${kind}`]: existing.map(trim) });
|
|
1458
|
+
return compact({
|
|
1459
|
+
[kind]: created.map(trim),
|
|
1460
|
+
[`unchanged_existing_${kind}`]: existing.map(trim),
|
|
1461
|
+
note: existing.length ? `Apollo matched ${existing.length} of them to existing ${kind} and left those unchanged: change them with update_${kind === "contacts" ? "contact" : "account"}.` : void 0
|
|
1462
|
+
});
|
|
1463
|
+
}
|
|
1464
|
+
function requireMatchKeys(contacts) {
|
|
1465
|
+
const given = (contact, key) => typeof contact[key] === "string" && contact[key].trim() !== "";
|
|
1466
|
+
const index = contacts.findIndex((contact) => !given(contact, "email") && !(given(contact, "first_name") && given(contact, "last_name") && given(contact, "organization_name")));
|
|
1467
|
+
if (index !== -1) {
|
|
1468
|
+
throw new ToolFailure(`contacts[${index}] needs an email, or a first_name and last_name with organization_name, for Apollo to match it on. Nothing was changed.`);
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
var REQUEST_ID = /^-?\d{1,19}$/;
|
|
1472
|
+
function phoneLookup(data) {
|
|
1473
|
+
const lookup = data?.phone_enrichment;
|
|
1474
|
+
if (!lookup || typeof lookup !== "object") return {};
|
|
1475
|
+
const message = typeof lookup.message === "string" && lookup.message ? truncate(lookup.message, 300) : void 0;
|
|
1476
|
+
if (lookup.status !== "pending") return { phone_enrichment: compact({ status: lookup.status, message }) };
|
|
1477
|
+
const id = [data?.request_id_str, data?.request_id].find((value) => typeof value === "string" && REQUEST_ID.test(value)) ?? (Number.isSafeInteger(data?.request_id) ? String(data.request_id) : void 0);
|
|
1478
|
+
if (!id) return { phone_enrichment: { status: "pending", message: "Apollo gave no request id that can be read exactly, so the phones cannot be polled." } };
|
|
1479
|
+
return { request_id: id, phone_enrichment: compact({ status: "pending", message }) };
|
|
1480
|
+
}
|
|
1481
|
+
function creditUsage(data) {
|
|
1482
|
+
const number = (key) => typeof data?.[key] === "number" ? data[key] : void 0;
|
|
1483
|
+
const kind = (limit, used) => compact({ limit: number(limit), used: number(used) });
|
|
1484
|
+
return compact({
|
|
1485
|
+
lead_credits: compact({ limit: number("effective_num_lead_credits"), used: number("num_lead_credits_used"), remaining: number("num_credits_remaining") }),
|
|
1486
|
+
direct_dial_credits: kind("effective_num_direct_dial_credits", "num_direct_dial_credits_used"),
|
|
1487
|
+
export_credits: kind("effective_num_export_credits", "num_export_credits_used"),
|
|
1488
|
+
ai_credits: kind("effective_num_ai_credits", "num_ai_credits_used"),
|
|
1489
|
+
power_up_credits: kind("effective_num_power_up_credits", "num_power_up_credits_used"),
|
|
1490
|
+
total_unified_credits_used: number("total_unified_credits_used")
|
|
1491
|
+
});
|
|
1492
|
+
}
|
|
1493
|
+
var EMAIL_STATUSES = ["delivered", "scheduled", "drafted", "not_opened", "opened", "clicked", "unsubscribed", "demoed", "bounced", "spam_blocked", "failed_other"];
|
|
1494
|
+
var REPLY_CLASSES = ["willing_to_meet", "follow_up_question", "person_referral", "out_of_office", "already_left_company_or_not_right_person", "not_interested", "unsubscribe", "none_of_the_above"];
|
|
1495
|
+
var LIST_KINDS = {
|
|
1496
|
+
users: { path: `${BASE}/users/search`, field: "users", paged: true, trim: (user) => compact({ id: user?.id, first_name: user?.first_name, last_name: user?.last_name, email: user?.email, title: user?.title }) },
|
|
1497
|
+
email_accounts: { path: `${BASE}/email_accounts`, field: "email_accounts", trim: (account) => compact({ id: account?.id, email: account?.email, type: account?.type, active: account?.active, default: account?.default, user_id: account?.user_id }) },
|
|
1498
|
+
contact_stages: { path: `${BASE}/contact_stages`, field: "contact_stages", trim: (stage) => compact({ id: stage?.id, name: stage?.name, display_order: stage?.display_order ?? stage?.order, category: stage?.category }) },
|
|
1499
|
+
account_stages: { path: `${BASE}/account_stages`, field: "account_stages", trim: (stage) => compact({ id: stage?.id, name: stage?.name, display_order: stage?.display_order ?? stage?.order, category: stage?.category }) },
|
|
1500
|
+
deal_stages: { path: `${BASE}/opportunity_stages`, field: "opportunity_stages", trim: (stage) => compact({ id: stage?.id, name: stage?.name, display_order: stage?.display_order, probability: stage?.probability, is_won: stage?.is_won, is_closed: stage?.is_closed, opportunity_pipeline_id: stage?.opportunity_pipeline_id }) },
|
|
1501
|
+
lists: { path: `${BASE}/labels`, field: "labels", trim: (label) => compact({ id: label?.id, name: label?.name, modality: label?.modality, cached_count: label?.cached_count }) },
|
|
1502
|
+
custom_fields: { path: `${BASE}/typed_custom_fields`, field: "typed_custom_fields", trim: (field) => compact({ id: field?.id, name: field?.name, type: field?.type, modality: field?.modality }) }
|
|
1503
|
+
};
|
|
1504
|
+
var connector = defineConnector({
|
|
1505
|
+
vendor: "apollo",
|
|
1506
|
+
label: LABEL2,
|
|
1507
|
+
origins: ["https://api.apollo.io"],
|
|
1508
|
+
credentials: ["apikey", "masterapikey"],
|
|
1509
|
+
requiredCredentials: [["apikey"], ["masterapikey"]],
|
|
1510
|
+
credentialLabels: { apikey: "Apollo API key", masterapikey: "Apollo master API key" },
|
|
1511
|
+
authHeaders: (credentials) => ({ "x-api-key": credentials["masterapikey"] || credentials["apikey"] }),
|
|
1512
|
+
tools: [
|
|
1513
|
+
{
|
|
1514
|
+
name: "get_profile",
|
|
1515
|
+
kind: "read",
|
|
1516
|
+
title: "Get the Apollo user and credits",
|
|
1517
|
+
description: "The Apollo user the API key belongs to (name, email, team) and, with credits, the user's credits: for lead, direct dial, export, AI and power-up credits the allowance and how many are used, and the lead credits left. Free; a quick connection check.",
|
|
1518
|
+
inputSchema: {
|
|
1519
|
+
type: "object",
|
|
1520
|
+
properties: { credits: { type: "boolean", default: true, description: "true (default) to include credit usage." } },
|
|
1521
|
+
additionalProperties: false
|
|
1522
|
+
},
|
|
1523
|
+
async run(args, h) {
|
|
1524
|
+
const { data } = await ap(h, { path: `${BASE}/users/api_profile`, query: { include_credit_usage: args.credits || void 0 } });
|
|
1525
|
+
return compact({
|
|
1526
|
+
id: data?.id,
|
|
1527
|
+
team_id: data?.team_id,
|
|
1528
|
+
first_name: data?.first_name,
|
|
1529
|
+
last_name: data?.last_name,
|
|
1530
|
+
email: data?.email,
|
|
1531
|
+
title: data?.title,
|
|
1532
|
+
credit_usage: args.credits ? creditUsage(data) : void 0,
|
|
1533
|
+
key: h.credentials["masterapikey"] ? "master API key" : "API key"
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
},
|
|
1537
|
+
{
|
|
1538
|
+
name: "get_usage",
|
|
1539
|
+
kind: "read",
|
|
1540
|
+
title: "Get Apollo API usage",
|
|
1541
|
+
description: "Apollo usage: per endpoint, the API calls made and the rate limits left this minute, hour and day (kind api), or the credits used by kind (kind credits). Free.",
|
|
1542
|
+
inputSchema: {
|
|
1543
|
+
type: "object",
|
|
1544
|
+
properties: {
|
|
1545
|
+
kind: { type: "string", enum: ["api", "credits"], default: "api", description: "api (rate limits) or credits." },
|
|
1546
|
+
endpoints: STRINGS('For kind api: only these endpoints, as Apollo names them, e.g. ["api/v1/contacts/search"].', 50)
|
|
1547
|
+
},
|
|
1548
|
+
additionalProperties: false
|
|
1549
|
+
},
|
|
1550
|
+
async run(args, h) {
|
|
1551
|
+
const { data } = await ap(h, {
|
|
1552
|
+
method: "POST",
|
|
1553
|
+
path: args.kind === "credits" ? `${BASE}/usage_stats/credit_usage_stats` : `${BASE}/usage_stats/api_usage_stats`,
|
|
1554
|
+
json: args.kind === "api" && args.endpoints?.length ? { endpoints: args.endpoints } : {},
|
|
1555
|
+
safe: true
|
|
1556
|
+
});
|
|
1557
|
+
return data ?? {};
|
|
1558
|
+
}
|
|
1559
|
+
},
|
|
1560
|
+
{
|
|
1561
|
+
name: "search_people",
|
|
1562
|
+
kind: "read",
|
|
1563
|
+
title: "Search Apollo people",
|
|
1564
|
+
description: "Finds prospects in Apollo's database by titles, seniority, locations, company domains, sizes, industries and keywords. Free (no credits). Results have obfuscated last names and no emails or phones: enrich_people reveals those. Up to 100 a page, 500 pages. Pass nextCursor back as cursor for more.",
|
|
1565
|
+
inputSchema: {
|
|
1566
|
+
type: "object",
|
|
1567
|
+
properties: {
|
|
1568
|
+
person_titles: STRINGS('Job titles, e.g. ["CEO", "head of marketing"].'),
|
|
1569
|
+
include_similar_titles: { type: "boolean", description: "Also match similar titles (Apollo's default is true)." },
|
|
1570
|
+
person_seniorities: { type: "array", items: { type: "string", enum: ["owner", "founder", "c_suite", "partner", "vp", "head", "director", "manager", "senior", "entry", "intern"] }, uniqueItems: true, description: "Seniorities." },
|
|
1571
|
+
person_locations: STRINGS("Where people live: cities, US states, countries."),
|
|
1572
|
+
organization_locations: STRINGS("Where their employer is based."),
|
|
1573
|
+
organization_domains: STRINGS('Employer domains, e.g. ["example.com"].', 1e3),
|
|
1574
|
+
organization_ids: STRINGS("Apollo company ids of employers."),
|
|
1575
|
+
organization_num_employees_ranges: STRINGS('Employer headcounts as "min,max", e.g. ["1,50", "51,200"].'),
|
|
1576
|
+
contact_email_status: { type: "array", items: { type: "string", enum: ["verified", "unverified", "likely to engage", "unavailable"] }, uniqueItems: true, description: "Email statuses." },
|
|
1577
|
+
q_keywords: { type: "string", maxLength: 500, description: "Keywords over the whole profile." },
|
|
1578
|
+
filters: FILTERS,
|
|
1579
|
+
per_page: PER_PAGE(),
|
|
1580
|
+
cursor: CURSOR
|
|
1581
|
+
},
|
|
1582
|
+
additionalProperties: false
|
|
1583
|
+
},
|
|
1584
|
+
async run(args, h) {
|
|
1585
|
+
return paged(h, args["cursor"], {
|
|
1586
|
+
key: "people",
|
|
1587
|
+
perPage: args["per_page"],
|
|
1588
|
+
maxPage: 500,
|
|
1589
|
+
request: (page, perPage) => ({
|
|
1590
|
+
method: "POST",
|
|
1591
|
+
path: `${BASE}/mixed_people/api_search`,
|
|
1592
|
+
json: body({
|
|
1593
|
+
person_titles: args["person_titles"],
|
|
1594
|
+
include_similar_titles: args["include_similar_titles"],
|
|
1595
|
+
person_seniorities: args["person_seniorities"],
|
|
1596
|
+
person_locations: args["person_locations"],
|
|
1597
|
+
organization_locations: args["organization_locations"],
|
|
1598
|
+
q_organization_domains_list: args["organization_domains"],
|
|
1599
|
+
organization_ids: args["organization_ids"],
|
|
1600
|
+
organization_num_employees_ranges: args["organization_num_employees_ranges"],
|
|
1601
|
+
contact_email_status: args["contact_email_status"],
|
|
1602
|
+
q_keywords: args["q_keywords"],
|
|
1603
|
+
page,
|
|
1604
|
+
per_page: perPage
|
|
1605
|
+
}, args["filters"]),
|
|
1606
|
+
safe: true,
|
|
1607
|
+
errors: { 403: NO_ACCESS }
|
|
1608
|
+
}),
|
|
1609
|
+
trim: trimPerson
|
|
1610
|
+
});
|
|
1611
|
+
}
|
|
1612
|
+
},
|
|
1613
|
+
{
|
|
1614
|
+
name: "enrich_people",
|
|
1615
|
+
kind: "read",
|
|
1616
|
+
title: "Enrich people with Apollo",
|
|
1617
|
+
description: "Looks up 1 to 10 people (by Apollo id, email, LinkedIn URL, or name with company) and returns their full profile: work email, title, location, employment and company. Uses Apollo credits: 1 per person for email or details found, 8 more for a mobile phone. Phones arrive later: with reveal_phone_number, phone_enrichment says whether Apollo is looking for them; while it is pending, the result has a request_id for get_enrichment_result. Skipped or not_attempted means there is nothing to wait for.",
|
|
1618
|
+
inputSchema: {
|
|
1619
|
+
type: "object",
|
|
1620
|
+
properties: {
|
|
1621
|
+
people: { type: "array", items: PERSON_DETAILS, minItems: 1, maxItems: 10, description: "The people to look up." },
|
|
1622
|
+
reveal_personal_emails: { type: "boolean", default: false, description: "true to also return personal emails (more credits; never for people in GDPR regions)." },
|
|
1623
|
+
reveal_phone_number: { type: "boolean", default: false, description: "true to look for phone numbers too (8 credits for a mobile); they come by get_enrichment_result." }
|
|
1624
|
+
},
|
|
1625
|
+
required: ["people"],
|
|
1626
|
+
additionalProperties: false
|
|
1627
|
+
},
|
|
1628
|
+
async run(args, h) {
|
|
1629
|
+
const index = args.people.findIndex((person) => !person["id"] && !person["email"] && !person["hashed_email"] && !person["linkedin_url"] && !person["name"] && !(person["first_name"] && person["last_name"]));
|
|
1630
|
+
if (index !== -1) throw new ToolFailure(`people[${index}] needs an id, an email, a LinkedIn URL or a name. Nothing was sent.`);
|
|
1631
|
+
const options = compact({
|
|
1632
|
+
reveal_personal_emails: args.reveal_personal_emails || void 0,
|
|
1633
|
+
reveal_phone_number: args.reveal_phone_number || void 0,
|
|
1634
|
+
// Apollo sends phone results to a webhook or keeps them for polling: this connector polls.
|
|
1635
|
+
poll_only: args.reveal_phone_number || void 0
|
|
1636
|
+
});
|
|
1637
|
+
if (args.people.length === 1) {
|
|
1638
|
+
const { data: data2 } = await ap(h, { method: "POST", path: `${BASE}/people/match`, json: { ...args.people[0], ...options }, safe: true });
|
|
1639
|
+
return compact({ matches: [trimPerson(data2?.person)], credits_consumed: data2?.credits_consumed, ...phoneLookup(data2) });
|
|
1640
|
+
}
|
|
1641
|
+
const { data } = await ap(h, { method: "POST", path: `${BASE}/people/bulk_match`, json: { details: args.people, ...options }, safe: true });
|
|
1642
|
+
const matches = Array.isArray(data?.matches) ? data.matches : [];
|
|
1643
|
+
return compact({
|
|
1644
|
+
matches: matches.map(trimPerson),
|
|
1645
|
+
missing_records: data?.missing_records,
|
|
1646
|
+
credits_consumed: data?.credits_consumed,
|
|
1647
|
+
...phoneLookup(data)
|
|
1648
|
+
});
|
|
1649
|
+
}
|
|
1650
|
+
},
|
|
1651
|
+
{
|
|
1652
|
+
name: "get_enrichment_result",
|
|
1653
|
+
kind: "read",
|
|
1654
|
+
title: "Get an Apollo enrichment result",
|
|
1655
|
+
description: "The phone numbers (or waterfall results) of an earlier enrich_people with reveal_phone_number, by the request_id it returned while phone_enrichment was pending. While Apollo is still looking it answers 404: try again in about 10 seconds, a few times at most.",
|
|
1656
|
+
inputSchema: {
|
|
1657
|
+
type: "object",
|
|
1658
|
+
properties: { request_id: { type: "string", pattern: REQUEST_ID.source, description: 'The request_id from enrich_people, exactly as given, e.g. "-9045486258674686251".' } },
|
|
1659
|
+
required: ["request_id"],
|
|
1660
|
+
additionalProperties: false
|
|
1661
|
+
},
|
|
1662
|
+
async run(args, h) {
|
|
1663
|
+
const { data } = await ap(h, {
|
|
1664
|
+
path: `${BASE}/webhook_result/${args.request_id}`,
|
|
1665
|
+
errors: {
|
|
1666
|
+
// Apollo's 404 is either result_pending (still looking) or request_id_unknown (an id it never issued). Its
|
|
1667
|
+
// body carries only that code, under error_code, so the sentence says what to do in each case.
|
|
1668
|
+
404: "Apollo has no result for that request_id. If its phone lookup is still running (result_pending), try again in about 10 seconds, a few times at most; if it keeps answering 404, Apollo does not know the id (request_id_unknown): stop, since only a request_id that enrich_people returned with phone_enrichment pending can be polled",
|
|
1669
|
+
400: "Apollo did not take that request_id (it must be the signed number enrich_people returned)",
|
|
1670
|
+
410: "Apollo no longer keeps that result (it is older than 30 days)"
|
|
1671
|
+
}
|
|
1672
|
+
});
|
|
1673
|
+
const result2 = data?.webhook_result ?? data;
|
|
1674
|
+
const people = Array.isArray(result2?.people) ? result2.people : Array.isArray(result2?.matches) ? result2.matches : result2?.person ? [result2.person] : [];
|
|
1675
|
+
return compact({
|
|
1676
|
+
request_type: data?.request_type,
|
|
1677
|
+
status: result2?.status ?? data?.webhook_status,
|
|
1678
|
+
failure_reason: data?.failure_reason,
|
|
1679
|
+
credits_consumed: result2?.credits_consumed,
|
|
1680
|
+
people: people.map(trimPerson)
|
|
1681
|
+
});
|
|
1682
|
+
}
|
|
1683
|
+
},
|
|
1684
|
+
{
|
|
1685
|
+
name: "enrich_organizations",
|
|
1686
|
+
kind: "read",
|
|
1687
|
+
title: "Enrich companies with Apollo",
|
|
1688
|
+
description: "Looks up 1 to 10 companies by domain and returns their profile: industry, size, revenue, funding, location, technologies, links. Uses 1 Apollo credit per company.",
|
|
1689
|
+
inputSchema: {
|
|
1690
|
+
type: "object",
|
|
1691
|
+
properties: { domains: { type: "array", items: { type: "string", pattern: "^(?!www\\.)[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$", description: "A domain without www, e.g. example.com." }, minItems: 1, maxItems: 10, uniqueItems: true, description: "Company domains." } },
|
|
1692
|
+
required: ["domains"],
|
|
1693
|
+
additionalProperties: false
|
|
1694
|
+
},
|
|
1695
|
+
async run(args, h) {
|
|
1696
|
+
if (args.domains.length === 1) {
|
|
1697
|
+
const { data: data2 } = await ap(h, { path: `${BASE}/organizations/enrich`, query: { domain: args.domains[0] } });
|
|
1698
|
+
return { organizations: data2?.organization ? [trimOrganization(data2.organization)] : [] };
|
|
1699
|
+
}
|
|
1700
|
+
const { data } = await ap(h, { method: "POST", path: `${BASE}/organizations/bulk_enrich`, json: { domains: args.domains }, safe: true });
|
|
1701
|
+
const organizations = Array.isArray(data?.organizations) ? data.organizations : [];
|
|
1702
|
+
return compact({ organizations: organizations.map(trimOrganization), missing_records: data?.missing_records });
|
|
1703
|
+
}
|
|
1704
|
+
},
|
|
1705
|
+
{
|
|
1706
|
+
name: "search_organizations",
|
|
1707
|
+
kind: "read",
|
|
1708
|
+
title: "Search Apollo companies",
|
|
1709
|
+
description: "Finds companies in Apollo's database by name, domains, headcount, locations, keywords, technologies, revenue or funding. Uses 1 Apollo credit per page (up to 100 companies). Pass nextCursor back as cursor for more.",
|
|
1710
|
+
inputSchema: {
|
|
1711
|
+
type: "object",
|
|
1712
|
+
properties: {
|
|
1713
|
+
q_organization_name: { type: "string", maxLength: 200, description: "Part of the company name." },
|
|
1714
|
+
organization_domains: STRINGS("Company domains.", 1e3),
|
|
1715
|
+
organization_num_employees_ranges: STRINGS('Headcounts as "min,max", e.g. ["51,200"].'),
|
|
1716
|
+
organization_locations: STRINGS("Headquarters locations."),
|
|
1717
|
+
organization_not_locations: STRINGS("Headquarters locations to leave out."),
|
|
1718
|
+
q_organization_keyword_tags: STRINGS('Industry keywords, e.g. ["saas"].'),
|
|
1719
|
+
currently_using_any_of_technology_uids: STRINGS('Technologies, with underscores, e.g. ["google_analytics"].'),
|
|
1720
|
+
organization_ids: STRINGS("Apollo company ids."),
|
|
1721
|
+
filters: FILTERS,
|
|
1722
|
+
per_page: PER_PAGE(),
|
|
1723
|
+
cursor: CURSOR
|
|
1724
|
+
},
|
|
1725
|
+
additionalProperties: false
|
|
1726
|
+
},
|
|
1727
|
+
async run(args, h) {
|
|
1728
|
+
return paged(h, args["cursor"], {
|
|
1729
|
+
key: "organizations",
|
|
1730
|
+
perPage: args["per_page"],
|
|
1731
|
+
request: (page, perPage) => ({
|
|
1732
|
+
method: "POST",
|
|
1733
|
+
path: `${BASE}/mixed_companies/search`,
|
|
1734
|
+
json: body({
|
|
1735
|
+
q_organization_name: args["q_organization_name"],
|
|
1736
|
+
q_organization_domains_list: args["organization_domains"],
|
|
1737
|
+
organization_num_employees_ranges: args["organization_num_employees_ranges"],
|
|
1738
|
+
organization_locations: args["organization_locations"],
|
|
1739
|
+
organization_not_locations: args["organization_not_locations"],
|
|
1740
|
+
q_organization_keyword_tags: args["q_organization_keyword_tags"],
|
|
1741
|
+
currently_using_any_of_technology_uids: args["currently_using_any_of_technology_uids"],
|
|
1742
|
+
organization_ids: args["organization_ids"],
|
|
1743
|
+
page,
|
|
1744
|
+
per_page: perPage
|
|
1745
|
+
}, args["filters"]),
|
|
1746
|
+
safe: true,
|
|
1747
|
+
errors: { 403: NO_ACCESS }
|
|
1748
|
+
}),
|
|
1749
|
+
trim: trimOrganization,
|
|
1750
|
+
extra: (data) => ({ saved_accounts: Array.isArray(data?.accounts) && data.accounts.length ? data.accounts.map(trimAccount) : void 0 })
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
},
|
|
1754
|
+
{
|
|
1755
|
+
name: "list_job_postings",
|
|
1756
|
+
kind: "read",
|
|
1757
|
+
title: "List an Apollo company's job postings",
|
|
1758
|
+
description: "A company's open job postings (title, location, URL, date). Uses 1 Apollo credit per page. Pass nextCursor back as cursor for more.",
|
|
1759
|
+
inputSchema: {
|
|
1760
|
+
type: "object",
|
|
1761
|
+
properties: { organization_id: { ...ID, description: "The Apollo company id (from search_organizations or enrich_organizations)." }, per_page: PER_PAGE(25), cursor: CURSOR },
|
|
1762
|
+
required: ["organization_id"],
|
|
1763
|
+
additionalProperties: false
|
|
1764
|
+
},
|
|
1765
|
+
async run(args, h) {
|
|
1766
|
+
return paged(h, args.cursor, {
|
|
1767
|
+
key: "organization_job_postings",
|
|
1768
|
+
perPage: args.per_page,
|
|
1769
|
+
request: (page, perPage) => ({ path: `${BASE}/organizations/${args.organization_id}/job_postings`, query: { page, per_page: perPage }, errors: { 403: NO_ACCESS } }),
|
|
1770
|
+
trim: (job) => compact({ id: job?.id, title: job?.title, url: job?.url, city: job?.city, state: job?.state, country: job?.country, posted_at: job?.posted_at, last_seen_at: job?.last_seen_at })
|
|
1771
|
+
});
|
|
1772
|
+
}
|
|
1773
|
+
},
|
|
1774
|
+
{
|
|
1775
|
+
name: "search_news",
|
|
1776
|
+
kind: "read",
|
|
1777
|
+
title: "Search Apollo news about companies",
|
|
1778
|
+
description: "News articles about given companies (funding, hires, launches, partnerships), newest first, optionally by category and date. Uses 1 Apollo credit per page. Pass nextCursor back as cursor for more.",
|
|
1779
|
+
inputSchema: {
|
|
1780
|
+
type: "object",
|
|
1781
|
+
properties: {
|
|
1782
|
+
organization_ids: { type: "array", items: ID, minItems: 1, maxItems: 100, uniqueItems: true, description: "Apollo company ids." },
|
|
1783
|
+
categories: STRINGS('News categories, e.g. ["hires", "investment"].', 20),
|
|
1784
|
+
published_after: DATE_TIME("Only articles published on or after this date"),
|
|
1785
|
+
published_before: DATE_TIME("Only articles published on or before this date"),
|
|
1786
|
+
per_page: { type: "integer", minimum: 1, maximum: 25, default: 10, description: "Articles per page, 1 to 25 (default 10)." },
|
|
1787
|
+
cursor: CURSOR
|
|
1788
|
+
},
|
|
1789
|
+
required: ["organization_ids"],
|
|
1790
|
+
additionalProperties: false
|
|
1791
|
+
},
|
|
1792
|
+
async run(args, h) {
|
|
1793
|
+
return paged(h, args.cursor, {
|
|
1794
|
+
key: "news_articles",
|
|
1795
|
+
perPage: args.per_page,
|
|
1796
|
+
request: (page, perPage) => ({
|
|
1797
|
+
method: "POST",
|
|
1798
|
+
path: `${BASE}/news_articles/search`,
|
|
1799
|
+
json: body({
|
|
1800
|
+
organization_ids: args.organization_ids,
|
|
1801
|
+
categories: args.categories,
|
|
1802
|
+
published_at: range(args.published_after, args.published_before),
|
|
1803
|
+
page,
|
|
1804
|
+
per_page: perPage
|
|
1805
|
+
}),
|
|
1806
|
+
safe: true,
|
|
1807
|
+
errors: { 403: NO_ACCESS }
|
|
1808
|
+
}),
|
|
1809
|
+
trim: (article) => compact({ id: article?.id, title: article?.title, url: article?.url, domain: article?.domain, published_at: article?.published_at, event_categories: article?.event_categories, organization_id: article?.organization_id, snippet: typeof article?.snippet === "string" ? article.snippet.slice(0, 400) : void 0 })
|
|
1810
|
+
});
|
|
1811
|
+
}
|
|
1812
|
+
},
|
|
1813
|
+
{
|
|
1814
|
+
name: "create_contacts",
|
|
1815
|
+
kind: "create",
|
|
1816
|
+
check: "search_contacts",
|
|
1817
|
+
title: "Create Apollo contacts",
|
|
1818
|
+
description: "Saves 1 to 100 people as contacts in your Apollo account, with their email, title, company, phones, lists and owner. Apollo does not check for duplicates here: to avoid them, use upsert_contacts. Free.",
|
|
1819
|
+
inputSchema: {
|
|
1820
|
+
type: "object",
|
|
1821
|
+
properties: {
|
|
1822
|
+
contacts: { type: "array", items: CONTACT, minItems: 1, maxItems: 100, description: "The contacts." },
|
|
1823
|
+
append_label_names: STRINGS("Lists (labels) to add every contact to.", 50)
|
|
1824
|
+
},
|
|
1825
|
+
required: ["contacts"],
|
|
1826
|
+
additionalProperties: false
|
|
1827
|
+
},
|
|
1828
|
+
async run(args, h) {
|
|
1829
|
+
return createRecords(h, "contacts", args.contacts, { dedupe: false, labels: args.append_label_names });
|
|
1830
|
+
}
|
|
1831
|
+
},
|
|
1832
|
+
{
|
|
1833
|
+
name: "upsert_contacts",
|
|
1834
|
+
kind: "update",
|
|
1835
|
+
check: "search_contacts",
|
|
1836
|
+
title: "Create or update Apollo contacts",
|
|
1837
|
+
description: "Saves 1 to 100 contacts without adding duplicates. Each needs an email, or a first and last name with organization_name, for Apollo to match on. One contact (without append_label_names): the contact Apollo matches is updated in place with the values given (others are kept), or a new one is created. Several, or append_label_names: Apollo creates the new ones and leaves those it matches unchanged; they come back in unchanged_existing_contacts, to change with update_contact. Free.",
|
|
1838
|
+
inputSchema: {
|
|
1839
|
+
type: "object",
|
|
1840
|
+
properties: {
|
|
1841
|
+
contacts: { type: "array", items: CONTACT, minItems: 1, maxItems: 100, description: "The contacts." },
|
|
1842
|
+
append_label_names: STRINGS("Lists (labels) to add the contacts to. Given, it makes this a bulk save: contacts Apollo matches are left as they are.", 50)
|
|
1843
|
+
},
|
|
1844
|
+
required: ["contacts"],
|
|
1845
|
+
additionalProperties: false
|
|
1846
|
+
},
|
|
1847
|
+
async run(args, h) {
|
|
1848
|
+
requireMatchKeys(args.contacts);
|
|
1849
|
+
return createRecords(h, "contacts", args.contacts, { dedupe: true, labels: args.append_label_names });
|
|
1850
|
+
}
|
|
1851
|
+
},
|
|
1852
|
+
{
|
|
1853
|
+
name: "update_contact",
|
|
1854
|
+
kind: "update",
|
|
1855
|
+
check: "get_contact",
|
|
1856
|
+
title: "Update an Apollo contact",
|
|
1857
|
+
description: "Changes one contact: only the fields given. label_names replaces the contact's lists. Free.",
|
|
1858
|
+
inputSchema: {
|
|
1859
|
+
type: "object",
|
|
1860
|
+
properties: { contact_id: { ...ID, description: "The contact id." }, ...CONTACT_FIELDS },
|
|
1861
|
+
required: ["contact_id"],
|
|
1862
|
+
additionalProperties: false
|
|
1863
|
+
},
|
|
1864
|
+
async run(args, h) {
|
|
1865
|
+
const { contact_id: id, ...fields } = args;
|
|
1866
|
+
if (!Object.keys(compact(fields)).length) throw new ToolFailure("Nothing to change: give at least one field. Nothing was changed.");
|
|
1867
|
+
const { data } = await ap(h, {
|
|
1868
|
+
method: "PATCH",
|
|
1869
|
+
path: `${BASE}/contacts/${id}`,
|
|
1870
|
+
json: compact(fields),
|
|
1871
|
+
write: true,
|
|
1872
|
+
errors: { 404: "Apollo has no contact with that id", 422: "Apollo did not accept the change" }
|
|
1873
|
+
});
|
|
1874
|
+
return trimContact(data?.contact ?? data);
|
|
1875
|
+
}
|
|
1876
|
+
},
|
|
1877
|
+
{
|
|
1878
|
+
name: "search_contacts",
|
|
1879
|
+
kind: "read",
|
|
1880
|
+
title: "Search Apollo contacts",
|
|
1881
|
+
description: "Your saved contacts by keywords (name, title, company, email), stages or lists, sorted by activity, creation or update. Free. Pass nextCursor back as cursor for more.",
|
|
1882
|
+
inputSchema: {
|
|
1883
|
+
type: "object",
|
|
1884
|
+
properties: {
|
|
1885
|
+
q_keywords: { type: "string", maxLength: 500, description: "Keywords: a name, title, company or email." },
|
|
1886
|
+
contact_stage_ids: STRINGS("Contact stage ids (see list_team_data contact_stages)."),
|
|
1887
|
+
contact_label_ids: STRINGS("List (label) ids (see list_team_data lists)."),
|
|
1888
|
+
sort_by_field: { type: "string", enum: ["contact_last_activity_date", "contact_email_last_opened_at", "contact_email_last_clicked_at", "contact_created_at", "contact_updated_at"], description: "Sort by this field." },
|
|
1889
|
+
sort_ascending: { type: "boolean", description: "true for ascending (with sort_by_field)." },
|
|
1890
|
+
filters: FILTERS,
|
|
1891
|
+
per_page: PER_PAGE(),
|
|
1892
|
+
cursor: CURSOR
|
|
1893
|
+
},
|
|
1894
|
+
additionalProperties: false
|
|
1895
|
+
},
|
|
1896
|
+
async run(args, h) {
|
|
1897
|
+
return paged(h, args["cursor"], {
|
|
1898
|
+
key: "contacts",
|
|
1899
|
+
perPage: args["per_page"],
|
|
1900
|
+
request: (page, perPage) => ({
|
|
1901
|
+
method: "POST",
|
|
1902
|
+
path: `${BASE}/contacts/search`,
|
|
1903
|
+
json: body({
|
|
1904
|
+
q_keywords: args["q_keywords"],
|
|
1905
|
+
contact_stage_ids: args["contact_stage_ids"],
|
|
1906
|
+
contact_label_ids: args["contact_label_ids"],
|
|
1907
|
+
sort_by_field: args["sort_by_field"],
|
|
1908
|
+
sort_ascending: args["sort_ascending"],
|
|
1909
|
+
page,
|
|
1910
|
+
per_page: perPage
|
|
1911
|
+
}, args["filters"]),
|
|
1912
|
+
safe: true,
|
|
1913
|
+
errors: { 403: NO_ACCESS }
|
|
1914
|
+
}),
|
|
1915
|
+
trim: trimContact
|
|
1916
|
+
});
|
|
1917
|
+
}
|
|
1918
|
+
},
|
|
1919
|
+
{
|
|
1920
|
+
name: "get_contact",
|
|
1921
|
+
kind: "read",
|
|
1922
|
+
title: "Get an Apollo contact",
|
|
1923
|
+
description: "One saved contact with its email, phones, company, stage, lists, owner, sequences and custom fields. Free.",
|
|
1924
|
+
inputSchema: { type: "object", properties: { contact_id: { ...ID, description: "The contact id." } }, required: ["contact_id"], additionalProperties: false },
|
|
1925
|
+
async run(args, h) {
|
|
1926
|
+
const { data } = await ap(h, { path: `${BASE}/contacts/${args.contact_id}`, errors: { 404: "Apollo has no contact with that id" } });
|
|
1927
|
+
return trimContact(data?.contact ?? data);
|
|
1928
|
+
}
|
|
1929
|
+
},
|
|
1930
|
+
{
|
|
1931
|
+
name: "create_accounts",
|
|
1932
|
+
kind: "create",
|
|
1933
|
+
check: "search_accounts",
|
|
1934
|
+
title: "Create Apollo accounts",
|
|
1935
|
+
description: "Saves 1 to 100 companies as accounts in your Apollo account, with name, domain, owner, stage, phone and address. Free.",
|
|
1936
|
+
inputSchema: {
|
|
1937
|
+
type: "object",
|
|
1938
|
+
properties: {
|
|
1939
|
+
accounts: { type: "array", items: { type: "object", properties: ACCOUNT_FIELDS, required: ["name"], additionalProperties: false }, minItems: 1, maxItems: 100, description: "The accounts." },
|
|
1940
|
+
append_label_names: STRINGS("Lists (labels) to add every account to.", 50)
|
|
1941
|
+
},
|
|
1942
|
+
required: ["accounts"],
|
|
1943
|
+
additionalProperties: false
|
|
1944
|
+
},
|
|
1945
|
+
async run(args, h) {
|
|
1946
|
+
return createRecords(h, "accounts", args.accounts, { dedupe: false, labels: args.append_label_names });
|
|
1947
|
+
}
|
|
1948
|
+
},
|
|
1949
|
+
{
|
|
1950
|
+
name: "update_account",
|
|
1951
|
+
kind: "update",
|
|
1952
|
+
check: "get_account",
|
|
1953
|
+
title: "Update an Apollo account",
|
|
1954
|
+
description: "Changes one account (a saved company): only the fields given. Free.",
|
|
1955
|
+
inputSchema: {
|
|
1956
|
+
type: "object",
|
|
1957
|
+
properties: { account_id: { ...ID, description: "The account id." }, ...ACCOUNT_FIELDS },
|
|
1958
|
+
required: ["account_id"],
|
|
1959
|
+
additionalProperties: false
|
|
1960
|
+
},
|
|
1961
|
+
async run(args, h) {
|
|
1962
|
+
const { account_id: id, ...fields } = args;
|
|
1963
|
+
if (!Object.keys(compact(fields)).length) throw new ToolFailure("Nothing to change: give at least one field. Nothing was changed.");
|
|
1964
|
+
const { data } = await ap(h, {
|
|
1965
|
+
method: "PATCH",
|
|
1966
|
+
path: `${BASE}/accounts/${id}`,
|
|
1967
|
+
json: compact(fields),
|
|
1968
|
+
write: true,
|
|
1969
|
+
errors: { 404: "Apollo has no account with that id", 422: "Apollo did not accept the change" }
|
|
1970
|
+
});
|
|
1971
|
+
return trimAccount(data?.account ?? data);
|
|
1972
|
+
}
|
|
1973
|
+
},
|
|
1974
|
+
{
|
|
1975
|
+
name: "search_accounts",
|
|
1976
|
+
kind: "read",
|
|
1977
|
+
title: "Search Apollo accounts",
|
|
1978
|
+
description: "Your saved accounts (companies) by name, stages or lists, sorted by activity, creation or update. Free. Pass nextCursor back as cursor for more.",
|
|
1979
|
+
inputSchema: {
|
|
1980
|
+
type: "object",
|
|
1981
|
+
properties: {
|
|
1982
|
+
q_organization_name: { type: "string", maxLength: 200, description: "Part of the company name." },
|
|
1983
|
+
account_stage_ids: STRINGS("Account stage ids (see list_team_data account_stages)."),
|
|
1984
|
+
account_label_ids: STRINGS("List (label) ids."),
|
|
1985
|
+
sort_by_field: { type: "string", enum: ["account_last_activity_date", "account_created_at", "account_updated_at"], description: "Sort by this field." },
|
|
1986
|
+
sort_ascending: { type: "boolean", description: "true for ascending (with sort_by_field)." },
|
|
1987
|
+
filters: FILTERS,
|
|
1988
|
+
per_page: PER_PAGE(),
|
|
1989
|
+
cursor: CURSOR
|
|
1990
|
+
},
|
|
1991
|
+
additionalProperties: false
|
|
1992
|
+
},
|
|
1993
|
+
async run(args, h) {
|
|
1994
|
+
return paged(h, args["cursor"], {
|
|
1995
|
+
key: "accounts",
|
|
1996
|
+
perPage: args["per_page"],
|
|
1997
|
+
request: (page, perPage) => ({
|
|
1998
|
+
method: "POST",
|
|
1999
|
+
path: `${BASE}/accounts/search`,
|
|
2000
|
+
json: body({
|
|
2001
|
+
q_organization_name: args["q_organization_name"],
|
|
2002
|
+
account_stage_ids: args["account_stage_ids"],
|
|
2003
|
+
account_label_ids: args["account_label_ids"],
|
|
2004
|
+
sort_by_field: args["sort_by_field"],
|
|
2005
|
+
sort_ascending: args["sort_ascending"],
|
|
2006
|
+
page,
|
|
2007
|
+
per_page: perPage
|
|
2008
|
+
}, args["filters"]),
|
|
2009
|
+
safe: true,
|
|
2010
|
+
errors: { 403: NO_ACCESS }
|
|
2011
|
+
}),
|
|
2012
|
+
trim: trimAccount
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
},
|
|
2016
|
+
{
|
|
2017
|
+
name: "get_account",
|
|
2018
|
+
kind: "read",
|
|
2019
|
+
title: "Get an Apollo account",
|
|
2020
|
+
description: "One saved account (company) with its domain, owner, stage, lists and custom fields. Free.",
|
|
2021
|
+
inputSchema: { type: "object", properties: { account_id: { ...ID, description: "The account id." } }, required: ["account_id"], additionalProperties: false },
|
|
2022
|
+
async run(args, h) {
|
|
2023
|
+
const { data } = await ap(h, { path: `${BASE}/accounts/${args.account_id}`, errors: { 404: "Apollo has no account with that id" } });
|
|
2024
|
+
return trimAccount(data?.account ?? data);
|
|
2025
|
+
}
|
|
2026
|
+
},
|
|
2027
|
+
{
|
|
2028
|
+
name: "search_sequences",
|
|
2029
|
+
kind: "read",
|
|
2030
|
+
title: "Search Apollo sequences",
|
|
2031
|
+
description: "Sequences (email outreach campaigns) by name, with whether they are active, their steps, and contacts scheduled, delivered, opened, replied and bounced with rates. Free. Pass nextCursor back as cursor for more.",
|
|
2032
|
+
inputSchema: {
|
|
2033
|
+
type: "object",
|
|
2034
|
+
properties: { q_name: { type: "string", maxLength: 200, description: "Part of the sequence name." }, per_page: PER_PAGE(), cursor: CURSOR },
|
|
2035
|
+
additionalProperties: false
|
|
2036
|
+
},
|
|
2037
|
+
async run(args, h) {
|
|
2038
|
+
return paged(h, args.cursor, {
|
|
2039
|
+
key: "emailer_campaigns",
|
|
2040
|
+
perPage: args.per_page,
|
|
2041
|
+
request: (page, perPage) => ({ method: "POST", path: `${BASE}/emailer_campaigns/search`, json: body({ q_name: args.q_name, page, per_page: perPage }), safe: true, errors: { 403: NO_ACCESS } }),
|
|
2042
|
+
trim: trimSequence
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
},
|
|
2046
|
+
{
|
|
2047
|
+
name: "add_contacts_to_sequence",
|
|
2048
|
+
kind: "create",
|
|
2049
|
+
check: "get_contact",
|
|
2050
|
+
title: "Add contacts to an Apollo sequence",
|
|
2051
|
+
description: "Adds contacts (by id, or every contact of some lists) to a sequence, sending from one of your email accounts (list_team_data email_accounts). In an active sequence they start getting its emails. Contacts without email, unverified, or active in other sequences are skipped unless allowed; the result names those skipped and why.",
|
|
2052
|
+
inputSchema: {
|
|
2053
|
+
type: "object",
|
|
2054
|
+
properties: {
|
|
2055
|
+
sequence_id: { ...ID, description: "The sequence id (see search_sequences)." },
|
|
2056
|
+
contact_ids: IDS("Contact ids", 100),
|
|
2057
|
+
label_names: STRINGS("Instead of contact_ids: add every contact of these lists.", 20),
|
|
2058
|
+
send_email_from_email_account_id: { ...ID, description: "The email account to send from." },
|
|
2059
|
+
sequence_no_email: { type: "boolean", description: "Also add contacts without an email." },
|
|
2060
|
+
sequence_unverified_email: { type: "boolean", description: "Also add contacts with an unverified email." },
|
|
2061
|
+
sequence_job_change: { type: "boolean", description: "Also add contacts who recently changed jobs." },
|
|
2062
|
+
sequence_active_in_other_campaigns: { type: "boolean", description: "Also add contacts active in other sequences." },
|
|
2063
|
+
sequence_finished_in_other_campaigns: { type: "boolean", description: "Also add contacts finished in other sequences." },
|
|
2064
|
+
sequence_same_company_in_same_campaign: { type: "boolean", description: "Also add contacts whose colleagues are in this sequence." },
|
|
2065
|
+
user_id: { ...ID, description: "The user adding them (see list_team_data users)." },
|
|
2066
|
+
status: { type: "string", enum: ["active", "paused"], description: "Start them active (default) or paused." },
|
|
2067
|
+
auto_unpause_at: DATE_TIME("With status paused: when they start")
|
|
2068
|
+
},
|
|
2069
|
+
required: ["sequence_id", "send_email_from_email_account_id"],
|
|
2070
|
+
additionalProperties: false
|
|
2071
|
+
},
|
|
2072
|
+
async run(args, h) {
|
|
2073
|
+
if (!args["contact_ids"]?.length === !args["label_names"]?.length) throw new ToolFailure("Give contact_ids or label_names (one of the two). Nothing was changed.");
|
|
2074
|
+
const { sequence_id: id, ...rest } = args;
|
|
2075
|
+
const { data } = await ap(h, {
|
|
2076
|
+
method: "POST",
|
|
2077
|
+
path: `${BASE}/emailer_campaigns/${id}/add_contact_ids`,
|
|
2078
|
+
json: body({ ...rest, emailer_campaign_id: id }),
|
|
2079
|
+
write: true,
|
|
2080
|
+
errors: { 404: "Apollo has no sequence with that id", 422: "Apollo did not add the contacts" }
|
|
2081
|
+
});
|
|
2082
|
+
const added = Array.isArray(data?.contacts) ? data.contacts : [];
|
|
2083
|
+
return compact({
|
|
2084
|
+
added: added.map((contact) => compact({ id: contact?.id, name: contact?.name, email: contact?.email })),
|
|
2085
|
+
skipped_contact_ids: data?.skipped_contact_ids,
|
|
2086
|
+
sequence: data?.emailer_campaign ? trimSequence(data.emailer_campaign) : void 0
|
|
2087
|
+
});
|
|
2088
|
+
}
|
|
2089
|
+
},
|
|
2090
|
+
{
|
|
2091
|
+
name: "update_sequence_contacts",
|
|
2092
|
+
kind: "update",
|
|
2093
|
+
check: "get_contact",
|
|
2094
|
+
title: "Stop, finish or remove Apollo sequence contacts",
|
|
2095
|
+
description: "Changes contacts' status in sequences: stop (halt their progress), mark_as_finished, or remove them from the sequences.",
|
|
2096
|
+
inputSchema: {
|
|
2097
|
+
type: "object",
|
|
2098
|
+
properties: {
|
|
2099
|
+
sequence_ids: IDS("Sequence ids", 50),
|
|
2100
|
+
contact_ids: IDS("Contact ids", 100),
|
|
2101
|
+
mode: { type: "string", enum: ["stop", "mark_as_finished", "remove"], description: "stop, mark_as_finished or remove." }
|
|
2102
|
+
},
|
|
2103
|
+
required: ["sequence_ids", "contact_ids", "mode"],
|
|
2104
|
+
additionalProperties: false
|
|
2105
|
+
},
|
|
2106
|
+
async run(args, h) {
|
|
2107
|
+
const { data } = await ap(h, {
|
|
2108
|
+
method: "POST",
|
|
2109
|
+
path: `${BASE}/emailer_campaigns/remove_or_stop_contact_ids`,
|
|
2110
|
+
json: { emailer_campaign_ids: args.sequence_ids, contact_ids: args.contact_ids, mode: args.mode },
|
|
2111
|
+
write: true,
|
|
2112
|
+
errors: { 422: "Apollo did not change the contacts" }
|
|
2113
|
+
});
|
|
2114
|
+
const contacts = Array.isArray(data?.contacts) ? data.contacts : [];
|
|
2115
|
+
return compact({ mode: args.mode, contacts: contacts.map((contact) => compact({ id: contact?.id, name: contact?.name })), sequences: args.sequence_ids });
|
|
2116
|
+
}
|
|
2117
|
+
},
|
|
2118
|
+
{
|
|
2119
|
+
name: "set_sequence_active",
|
|
2120
|
+
kind: "update",
|
|
2121
|
+
check: "search_sequences",
|
|
2122
|
+
title: "Activate or deactivate an Apollo sequence",
|
|
2123
|
+
description: "Activates a sequence (its contacts start getting its emails; it needs at least one step) or deactivates it (sending stops).",
|
|
2124
|
+
inputSchema: {
|
|
2125
|
+
type: "object",
|
|
2126
|
+
properties: {
|
|
2127
|
+
sequence_id: { ...ID, description: "The sequence id." },
|
|
2128
|
+
active: { type: "boolean", description: "true to activate, false to deactivate." }
|
|
2129
|
+
},
|
|
2130
|
+
required: ["sequence_id", "active"],
|
|
2131
|
+
additionalProperties: false
|
|
2132
|
+
},
|
|
2133
|
+
async run(args, h) {
|
|
2134
|
+
const { data } = await ap(h, {
|
|
2135
|
+
method: "POST",
|
|
2136
|
+
path: `${BASE}/emailer_campaigns/${args.sequence_id}/${args.active ? "approve" : "abort"}`,
|
|
2137
|
+
write: true,
|
|
2138
|
+
errors: { 404: "Apollo has no sequence with that id", 422: `Apollo could not ${args.active ? "activate" : "deactivate"} the sequence` }
|
|
2139
|
+
});
|
|
2140
|
+
return compact({ id: args.sequence_id, active: data?.emailer_campaign?.active ?? args.active });
|
|
2141
|
+
}
|
|
2142
|
+
},
|
|
2143
|
+
{
|
|
2144
|
+
name: "search_outreach_emails",
|
|
2145
|
+
kind: "read",
|
|
2146
|
+
title: "Search Apollo outreach emails",
|
|
2147
|
+
description: "Emails sent or scheduled by your sequences: by sequence, status (delivered, opened, clicked, bounced...), reply class (replies are found by reply_classes, not by a status), user, keywords, or a range of the dates they were due or sent. Free. Pass nextCursor back as cursor for more.",
|
|
2148
|
+
inputSchema: {
|
|
2149
|
+
type: "object",
|
|
2150
|
+
properties: {
|
|
2151
|
+
sequence_ids: STRINGS("Only emails of these sequences."),
|
|
2152
|
+
statuses: { type: "array", items: { type: "string", enum: EMAIL_STATUSES }, uniqueItems: true, description: `Only emails in these statuses: ${EMAIL_STATUSES.join(", ")}.` },
|
|
2153
|
+
reply_classes: {
|
|
2154
|
+
type: "array",
|
|
2155
|
+
items: { type: "string", enum: REPLY_CLASSES },
|
|
2156
|
+
uniqueItems: true,
|
|
2157
|
+
description: `Only emails whose reply Apollo classed as one of these: ${REPLY_CLASSES.join(", ")}. All of them find every reply.`
|
|
2158
|
+
},
|
|
2159
|
+
user_ids: STRINGS("Only emails of these users."),
|
|
2160
|
+
q_keywords: { type: "string", maxLength: 300, description: "Keywords." },
|
|
2161
|
+
date_after: { ...DATE, description: "Only emails due or sent (see date_mode) on or after this date, YYYY-MM-DD." },
|
|
2162
|
+
date_before: { ...DATE, description: "Only emails due or sent (see date_mode) on or before this date, YYYY-MM-DD." },
|
|
2163
|
+
date_mode: { type: "string", enum: ["completed_at", "due_at"], default: "completed_at", description: "What date_after and date_before apply to: completed_at (default), when the email was sent, or due_at, when it is due." },
|
|
2164
|
+
filters: FILTERS,
|
|
2165
|
+
per_page: PER_PAGE(),
|
|
2166
|
+
cursor: CURSOR
|
|
2167
|
+
},
|
|
2168
|
+
additionalProperties: false
|
|
2169
|
+
},
|
|
2170
|
+
async run(args, h) {
|
|
2171
|
+
const dated = Boolean(args["date_after"] || args["date_before"]);
|
|
2172
|
+
return paged(h, args["cursor"], {
|
|
2173
|
+
key: "emailer_messages",
|
|
2174
|
+
perPage: args["per_page"],
|
|
2175
|
+
request: (page, perPage) => ({
|
|
2176
|
+
path: `${BASE}/emailer_messages/search`,
|
|
2177
|
+
query: query({
|
|
2178
|
+
emailer_campaign_ids: args["sequence_ids"],
|
|
2179
|
+
emailer_message_stats: args["statuses"],
|
|
2180
|
+
emailer_message_reply_classes: args["reply_classes"],
|
|
2181
|
+
user_ids: args["user_ids"],
|
|
2182
|
+
q_keywords: args["q_keywords"],
|
|
2183
|
+
emailer_message_date_range_mode: dated ? args["date_mode"] : void 0,
|
|
2184
|
+
emailer_message_date_range: range(args["date_after"], args["date_before"]),
|
|
2185
|
+
page,
|
|
2186
|
+
per_page: perPage
|
|
2187
|
+
}, args["filters"]),
|
|
2188
|
+
errors: { 403: NO_ACCESS }
|
|
2189
|
+
}),
|
|
2190
|
+
trim: trimEmailMessage
|
|
2191
|
+
});
|
|
2192
|
+
}
|
|
2193
|
+
},
|
|
2194
|
+
{
|
|
2195
|
+
name: "get_outreach_email_activities",
|
|
2196
|
+
kind: "read",
|
|
2197
|
+
title: "Get an Apollo outreach email's activity",
|
|
2198
|
+
description: "The activity of one outreach email: when it was delivered, opened and clicked, and the reply. Free.",
|
|
2199
|
+
inputSchema: { type: "object", properties: { email_id: { ...ID, description: "The outreach email id (see search_outreach_emails)." } }, required: ["email_id"], additionalProperties: false },
|
|
2200
|
+
async run(args, h) {
|
|
2201
|
+
const { data } = await ap(h, { path: `${BASE}/emailer_messages/${args.email_id}/activities`, errors: { 404: "Apollo has no outreach email with that id" } });
|
|
2202
|
+
return data ?? {};
|
|
2203
|
+
}
|
|
2204
|
+
},
|
|
2205
|
+
{
|
|
2206
|
+
name: "create_deal",
|
|
2207
|
+
kind: "create",
|
|
2208
|
+
check: "search_deals",
|
|
2209
|
+
title: "Create an Apollo deal",
|
|
2210
|
+
description: "Creates a deal (opportunity) with its name, amount, stage (list_team_data deal_stages), owner, account and close date. Free.",
|
|
2211
|
+
inputSchema: {
|
|
2212
|
+
type: "object",
|
|
2213
|
+
properties: {
|
|
2214
|
+
name: { type: "string", minLength: 1, maxLength: 300, description: "The deal name." },
|
|
2215
|
+
amount: { type: "number", minimum: 0, description: "The value, without currency." },
|
|
2216
|
+
opportunity_stage_id: ID,
|
|
2217
|
+
owner_id: ID,
|
|
2218
|
+
account_id: ID,
|
|
2219
|
+
closed_date: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "The expected close date, YYYY-MM-DD." },
|
|
2220
|
+
typed_custom_fields: CUSTOM_FIELDS
|
|
2221
|
+
},
|
|
2222
|
+
required: ["name"],
|
|
2223
|
+
additionalProperties: false
|
|
2224
|
+
},
|
|
2225
|
+
async run(args, h) {
|
|
2226
|
+
const { data } = await ap(h, {
|
|
2227
|
+
method: "POST",
|
|
2228
|
+
path: `${BASE}/opportunities`,
|
|
2229
|
+
json: compact({ ...args, amount: args["amount"] !== void 0 ? String(args["amount"]) : void 0 }),
|
|
2230
|
+
write: true,
|
|
2231
|
+
errors: { 422: "Apollo did not accept the deal" }
|
|
2232
|
+
});
|
|
2233
|
+
return trimDeal(data?.opportunity ?? data);
|
|
2234
|
+
}
|
|
2235
|
+
},
|
|
2236
|
+
{
|
|
2237
|
+
name: "search_deals",
|
|
2238
|
+
kind: "read",
|
|
2239
|
+
title: "Search Apollo deals",
|
|
2240
|
+
description: "Deals by name, accounts, owners, stages, open or closed, amount or close date, sorted as asked. Free. Pass nextCursor back as cursor for more.",
|
|
2241
|
+
inputSchema: {
|
|
2242
|
+
type: "object",
|
|
2243
|
+
properties: {
|
|
2244
|
+
q_opportunity_name: { type: "string", maxLength: 300, description: "Keywords in the deal or account name." },
|
|
2245
|
+
account_ids: STRINGS("Account ids."),
|
|
2246
|
+
owner_ids: STRINGS("Owner (user) ids."),
|
|
2247
|
+
stage_ids: STRINGS("Deal stage ids."),
|
|
2248
|
+
is_closed: { type: "boolean", description: "true for closed deals only, false for open ones." },
|
|
2249
|
+
sort_by_field: { type: "string", enum: ["amount", "is_closed", "is_won"], description: "Sort by this field." },
|
|
2250
|
+
filters: FILTERS,
|
|
2251
|
+
per_page: PER_PAGE(),
|
|
2252
|
+
cursor: CURSOR
|
|
2253
|
+
},
|
|
2254
|
+
additionalProperties: false
|
|
2255
|
+
},
|
|
2256
|
+
async run(args, h) {
|
|
2257
|
+
return paged(h, args["cursor"], {
|
|
2258
|
+
key: "opportunities",
|
|
2259
|
+
perPage: args["per_page"],
|
|
2260
|
+
request: (page, perPage) => ({
|
|
2261
|
+
path: `${BASE}/opportunities/search`,
|
|
2262
|
+
query: query({
|
|
2263
|
+
q_opportunity_name: args["q_opportunity_name"],
|
|
2264
|
+
account_ids: args["account_ids"],
|
|
2265
|
+
opportunity_owner_ids: args["owner_ids"],
|
|
2266
|
+
opportunity_stage_ids: args["stage_ids"],
|
|
2267
|
+
opportunity_is_closed: args["is_closed"],
|
|
2268
|
+
sort_by_field: args["sort_by_field"],
|
|
2269
|
+
page,
|
|
2270
|
+
per_page: perPage
|
|
2271
|
+
}, args["filters"]),
|
|
2272
|
+
errors: { 403: NO_ACCESS }
|
|
2273
|
+
}),
|
|
2274
|
+
trim: trimDeal
|
|
2275
|
+
});
|
|
2276
|
+
}
|
|
2277
|
+
},
|
|
2278
|
+
{
|
|
2279
|
+
name: "update_deal",
|
|
2280
|
+
kind: "update",
|
|
2281
|
+
check: "get_deal",
|
|
2282
|
+
title: "Update an Apollo deal",
|
|
2283
|
+
description: "Changes a deal: only the fields given, such as a new stage, amount or close date. Free.",
|
|
2284
|
+
inputSchema: {
|
|
2285
|
+
type: "object",
|
|
2286
|
+
properties: {
|
|
2287
|
+
deal_id: { ...ID, description: "The deal id." },
|
|
2288
|
+
name: { type: "string", minLength: 1, maxLength: 300 },
|
|
2289
|
+
amount: { type: "number", minimum: 0 },
|
|
2290
|
+
opportunity_stage_id: ID,
|
|
2291
|
+
owner_id: ID,
|
|
2292
|
+
closed_date: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "YYYY-MM-DD." },
|
|
2293
|
+
typed_custom_fields: CUSTOM_FIELDS
|
|
2294
|
+
},
|
|
2295
|
+
required: ["deal_id"],
|
|
2296
|
+
additionalProperties: false
|
|
2297
|
+
},
|
|
2298
|
+
async run(args, h) {
|
|
2299
|
+
const { deal_id: id, ...fields } = args;
|
|
2300
|
+
const changes = compact({ ...fields, amount: fields["amount"] !== void 0 ? String(fields["amount"]) : void 0 });
|
|
2301
|
+
if (!Object.keys(changes).length) throw new ToolFailure("Nothing to change: give at least one field. Nothing was changed.");
|
|
2302
|
+
const { data } = await ap(h, {
|
|
2303
|
+
method: "PATCH",
|
|
2304
|
+
path: `${BASE}/opportunities/${id}`,
|
|
2305
|
+
json: changes,
|
|
2306
|
+
write: true,
|
|
2307
|
+
errors: { 404: "Apollo has no deal with that id", 422: "Apollo did not accept the change" }
|
|
2308
|
+
});
|
|
2309
|
+
return trimDeal(data?.opportunity ?? data);
|
|
2310
|
+
}
|
|
2311
|
+
},
|
|
2312
|
+
{
|
|
2313
|
+
name: "get_deal",
|
|
2314
|
+
kind: "read",
|
|
2315
|
+
title: "Get an Apollo deal",
|
|
2316
|
+
description: "One deal with its amount, stage, owner, account, close date and whether it is closed or won. Free.",
|
|
2317
|
+
inputSchema: { type: "object", properties: { deal_id: { ...ID, description: "The deal id." } }, required: ["deal_id"], additionalProperties: false },
|
|
2318
|
+
async run(args, h) {
|
|
2319
|
+
const { data } = await ap(h, { path: `${BASE}/opportunities/${args.deal_id}`, errors: { 404: "Apollo has no deal with that id" } });
|
|
2320
|
+
return trimDeal(data?.opportunity ?? data);
|
|
2321
|
+
}
|
|
2322
|
+
},
|
|
2323
|
+
{
|
|
2324
|
+
name: "create_tasks",
|
|
2325
|
+
kind: "create",
|
|
2326
|
+
check: "search_tasks",
|
|
2327
|
+
title: "Create Apollo tasks",
|
|
2328
|
+
description: `A task for a user about 1 to 100 contacts (one task each): a call, a manual email, a LinkedIn step or an action item, with priority, due time and note. Types: ${TASK_TYPES.join(", ")}. Free.`,
|
|
2329
|
+
inputSchema: {
|
|
2330
|
+
type: "object",
|
|
2331
|
+
properties: {
|
|
2332
|
+
user_id: { ...ID, description: "The user who does the task (see list_team_data users)." },
|
|
2333
|
+
contact_ids: IDS("The contacts the task is about", 100),
|
|
2334
|
+
type: { type: "string", enum: TASK_TYPES, description: "The kind of task." },
|
|
2335
|
+
status: { type: "string", enum: ["scheduled", "completed", "skipped"], default: "scheduled", description: "scheduled (default) for future tasks." },
|
|
2336
|
+
priority: { type: "string", enum: ["high", "medium", "low"], description: "The priority." },
|
|
2337
|
+
due_at: DATE_TIME("When it is due"),
|
|
2338
|
+
title: { type: "string", maxLength: 300, description: "A title (one task only); Apollo makes one when left out." },
|
|
2339
|
+
note: { type: "string", maxLength: 5e3, description: "What to do." }
|
|
2340
|
+
},
|
|
2341
|
+
required: ["user_id", "contact_ids", "type", "due_at"],
|
|
2342
|
+
additionalProperties: false
|
|
2343
|
+
},
|
|
2344
|
+
async run(args, h) {
|
|
2345
|
+
const shared = { user_id: args.user_id, type: args.type, status: args.status, priority: args.priority, due_at: args.due_at, note: args.note };
|
|
2346
|
+
if (args.contact_ids.length === 1) {
|
|
2347
|
+
const { data: data2 } = await ap(h, { method: "POST", path: `${BASE}/tasks`, json: compact({ ...shared, contact_id: args.contact_ids[0], title: args.title }), write: true, errors: { 422: "Apollo did not accept the task" } });
|
|
2348
|
+
return { tasks: [trimTask(data2?.task ?? data2)] };
|
|
2349
|
+
}
|
|
2350
|
+
const { data } = await ap(h, { method: "POST", path: `${BASE}/tasks/bulk_create`, json: compact({ ...shared, contact_ids: args.contact_ids }), write: true, errors: { 422: "Apollo did not accept the tasks" } });
|
|
2351
|
+
return { tasks: (Array.isArray(data?.tasks) ? data.tasks : []).map(trimTask) };
|
|
2352
|
+
}
|
|
2353
|
+
},
|
|
2354
|
+
{
|
|
2355
|
+
name: "search_tasks",
|
|
2356
|
+
kind: "read",
|
|
2357
|
+
title: "Search Apollo tasks",
|
|
2358
|
+
description: "Tasks sorted by due date or priority, with their type, status, contact and note. Free. Pass nextCursor back as cursor for more.",
|
|
2359
|
+
inputSchema: {
|
|
2360
|
+
type: "object",
|
|
2361
|
+
properties: {
|
|
2362
|
+
sort_by_field: { type: "string", enum: ["task_due_at", "task_priority"], default: "task_due_at", description: "task_due_at (default) or task_priority." },
|
|
2363
|
+
sort_ascending: { type: "boolean", description: "true for ascending." },
|
|
2364
|
+
filters: FILTERS,
|
|
2365
|
+
per_page: PER_PAGE(),
|
|
2366
|
+
cursor: CURSOR
|
|
2367
|
+
},
|
|
2368
|
+
additionalProperties: false
|
|
2369
|
+
},
|
|
2370
|
+
async run(args, h) {
|
|
2371
|
+
return paged(h, args["cursor"], {
|
|
2372
|
+
key: "tasks",
|
|
2373
|
+
perPage: args["per_page"],
|
|
2374
|
+
request: (page, perPage) => ({
|
|
2375
|
+
method: "POST",
|
|
2376
|
+
path: `${BASE}/tasks/search`,
|
|
2377
|
+
json: body({ sort_by_field: args["sort_by_field"], sort_ascending: args["sort_ascending"], page, per_page: perPage }, args["filters"]),
|
|
2378
|
+
safe: true,
|
|
2379
|
+
errors: { 403: NO_ACCESS }
|
|
2380
|
+
}),
|
|
2381
|
+
trim: trimTask
|
|
2382
|
+
});
|
|
2383
|
+
}
|
|
2384
|
+
},
|
|
2385
|
+
{
|
|
2386
|
+
name: "log_call",
|
|
2387
|
+
kind: "create",
|
|
2388
|
+
check: "search_calls",
|
|
2389
|
+
title: "Log a call in Apollo",
|
|
2390
|
+
description: "Records a phone call made outside Apollo against a contact or account: status, duration, numbers, times, purpose and outcome, and a note. Free.",
|
|
2391
|
+
inputSchema: {
|
|
2392
|
+
type: "object",
|
|
2393
|
+
properties: {
|
|
2394
|
+
contact_id: ID,
|
|
2395
|
+
account_id: ID,
|
|
2396
|
+
user_ids: { type: "array", items: ID, maxItems: 5, description: "The users on the call (see list_team_data users)." },
|
|
2397
|
+
status: { type: "string", enum: ["queued", "ringing", "in-progress", "completed", "no_answer", "failed", "busy"], description: "The call status." },
|
|
2398
|
+
duration: { type: "integer", minimum: 0, description: "The length in seconds." },
|
|
2399
|
+
to_number: { type: "string", maxLength: 50 },
|
|
2400
|
+
from_number: { type: "string", maxLength: 50 },
|
|
2401
|
+
start_time: DATE_TIME("When it started"),
|
|
2402
|
+
end_time: DATE_TIME("When it ended"),
|
|
2403
|
+
phone_call_purpose_id: ID,
|
|
2404
|
+
phone_call_outcome_id: ID,
|
|
2405
|
+
note: { type: "string", maxLength: 5e3, description: "A note about the call." }
|
|
2406
|
+
},
|
|
2407
|
+
additionalProperties: false
|
|
2408
|
+
},
|
|
2409
|
+
async run(args, h) {
|
|
2410
|
+
if (!args["contact_id"] && !args["account_id"]) throw new ToolFailure("Give the contact_id or account_id the call was with. Nothing was changed.");
|
|
2411
|
+
const { user_ids: users, ...rest } = args;
|
|
2412
|
+
const { data } = await ap(h, {
|
|
2413
|
+
method: "POST",
|
|
2414
|
+
path: `${BASE}/phone_calls`,
|
|
2415
|
+
json: compact({ ...rest, user_id: users, logged: true }),
|
|
2416
|
+
write: true,
|
|
2417
|
+
errors: { 422: "Apollo did not accept the call" }
|
|
2418
|
+
});
|
|
2419
|
+
return trimCall(data?.phone_call ?? data);
|
|
2420
|
+
}
|
|
2421
|
+
},
|
|
2422
|
+
{
|
|
2423
|
+
name: "search_calls",
|
|
2424
|
+
kind: "read",
|
|
2425
|
+
title: "Search Apollo calls",
|
|
2426
|
+
description: "Calls made or received, by date range, duration, direction, users, purposes, outcomes or keywords. Free. Pass nextCursor back as cursor for more.",
|
|
2427
|
+
inputSchema: {
|
|
2428
|
+
type: "object",
|
|
2429
|
+
properties: {
|
|
2430
|
+
date_after: DATE_TIME("Only calls on or after this date"),
|
|
2431
|
+
date_before: DATE_TIME("Only calls on or before this date"),
|
|
2432
|
+
inbound: { type: "string", enum: ["incoming", "outgoing"], description: "incoming or outgoing calls." },
|
|
2433
|
+
user_ids: STRINGS("Only calls of these users."),
|
|
2434
|
+
q_keywords: { type: "string", maxLength: 300, description: "Keywords." },
|
|
2435
|
+
filters: FILTERS,
|
|
2436
|
+
per_page: PER_PAGE(),
|
|
2437
|
+
cursor: CURSOR
|
|
2438
|
+
},
|
|
2439
|
+
additionalProperties: false
|
|
2440
|
+
},
|
|
2441
|
+
async run(args, h) {
|
|
2442
|
+
return paged(h, args["cursor"], {
|
|
2443
|
+
key: "phone_calls",
|
|
2444
|
+
perPage: args["per_page"],
|
|
2445
|
+
request: (page, perPage) => ({
|
|
2446
|
+
path: `${BASE}/phone_calls/search`,
|
|
2447
|
+
query: query({
|
|
2448
|
+
date_range: range(args["date_after"], args["date_before"]),
|
|
2449
|
+
inbound: args["inbound"],
|
|
2450
|
+
user_ids: args["user_ids"],
|
|
2451
|
+
q_keywords: args["q_keywords"],
|
|
2452
|
+
page,
|
|
2453
|
+
per_page: perPage
|
|
2454
|
+
}, args["filters"]),
|
|
2455
|
+
errors: { 403: NO_ACCESS }
|
|
2456
|
+
}),
|
|
2457
|
+
trim: trimCall
|
|
2458
|
+
});
|
|
2459
|
+
}
|
|
2460
|
+
},
|
|
2461
|
+
{
|
|
2462
|
+
name: "list_team_data",
|
|
2463
|
+
kind: "read",
|
|
2464
|
+
title: "List Apollo team settings",
|
|
2465
|
+
description: "The ids other tools take: users (owner_id, user_id), email_accounts (to send sequences from), contact_stages, account_stages, deal_stages, lists (labels) and custom_fields (typed_custom_fields). Free. Pass nextCursor back as cursor for more.",
|
|
2466
|
+
inputSchema: {
|
|
2467
|
+
type: "object",
|
|
2468
|
+
properties: {
|
|
2469
|
+
kind: { type: "string", enum: Object.keys(LIST_KINDS), description: "What to list." },
|
|
2470
|
+
cursor: CURSOR
|
|
2471
|
+
},
|
|
2472
|
+
required: ["kind"],
|
|
2473
|
+
additionalProperties: false
|
|
2474
|
+
},
|
|
2475
|
+
async run(args, h) {
|
|
2476
|
+
const kind = LIST_KINDS[args.kind];
|
|
2477
|
+
if (kind.paged) {
|
|
2478
|
+
return paged(h, args.cursor, {
|
|
2479
|
+
key: kind.field,
|
|
2480
|
+
perPage: 100,
|
|
2481
|
+
request: (page, perPage) => ({ path: kind.path, query: { page, per_page: perPage }, errors: { 403: NO_ACCESS } }),
|
|
2482
|
+
trim: kind.trim
|
|
2483
|
+
});
|
|
2484
|
+
}
|
|
2485
|
+
const state = h.cursor(args.cursor);
|
|
2486
|
+
const skip = typeof state?.["s"] === "number" ? state["s"] : 0;
|
|
2487
|
+
const { data } = await ap(h, { path: kind.path });
|
|
2488
|
+
const items = Array.isArray(data?.[kind.field]) ? data[kind.field] : Array.isArray(data) ? data : [];
|
|
2489
|
+
return h.page({ key: kind.field, items: items.map(kind.trim).slice(skip), resumeAt: (index) => h.makeCursor({ s: skip + index }) });
|
|
2490
|
+
}
|
|
2491
|
+
},
|
|
2492
|
+
...apiTools({
|
|
2493
|
+
label: LABEL2,
|
|
2494
|
+
description: "The Apollo REST API v1 at https://api.apollo.io/api/v1, with the connected key (the master key when there is one): paths start with /api/v1/, such as /api/v1/contacts/{id}/opportunities, /api/v1/contacts/update_stages, /api/v1/accounts/bulk_update, /api/v1/labels, /api/v1/notes, /api/v1/tasks/{id}/complete or /api/v1/emailer_messages/{id}/send_now. Reference: https://docs.apollo.io/reference.",
|
|
2495
|
+
basePath: "/api/v1/"
|
|
2496
|
+
})
|
|
2497
|
+
]
|
|
2498
|
+
});
|
|
2499
|
+
module.exports = connector;
|