@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
package/dist/vendors/serper.js
CHANGED
|
@@ -29,12 +29,15 @@ function utf8Length(text2) {
|
|
|
29
29
|
function utf8Decode(bytes) {
|
|
30
30
|
return decoder.decode(bytes);
|
|
31
31
|
}
|
|
32
|
-
function
|
|
32
|
+
function base64Encode(bytes) {
|
|
33
33
|
let binary = "";
|
|
34
34
|
for (let i = 0; i < bytes.length; i += 32768) {
|
|
35
35
|
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
36
36
|
}
|
|
37
|
-
return btoa(binary)
|
|
37
|
+
return btoa(binary);
|
|
38
|
+
}
|
|
39
|
+
function base64UrlEncode(bytes) {
|
|
40
|
+
return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
38
41
|
}
|
|
39
42
|
function base64UrlDecode(text2) {
|
|
40
43
|
if (!/^[A-Za-z0-9_-]*$/.test(text2)) throw new Error("not base64url");
|
|
@@ -60,6 +63,113 @@ function formatNumber(value) {
|
|
|
60
63
|
return value.toLocaleString("en-US");
|
|
61
64
|
}
|
|
62
65
|
|
|
66
|
+
// src/core/output.ts
|
|
67
|
+
var OUTPUT_LIMIT_BYTES = 32 * 1024;
|
|
68
|
+
function jsonSize(value) {
|
|
69
|
+
return utf8Length(JSON.stringify(value) ?? "");
|
|
70
|
+
}
|
|
71
|
+
function cutStrings(value, max) {
|
|
72
|
+
if (typeof value === "string") return truncate(value, max);
|
|
73
|
+
if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
|
|
74
|
+
if (typeof value === "object" && value !== null) {
|
|
75
|
+
const out = {};
|
|
76
|
+
for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
|
|
82
|
+
if (jsonSize(value) <= limit) return { value, truncated: false };
|
|
83
|
+
for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
|
|
84
|
+
const cut = cutStrings(value, max);
|
|
85
|
+
if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
|
|
86
|
+
}
|
|
87
|
+
return void 0;
|
|
88
|
+
}
|
|
89
|
+
function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
|
|
90
|
+
const build = (count) => {
|
|
91
|
+
const cut = count < input.items.length;
|
|
92
|
+
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
|
|
93
|
+
const next = cut ? input.resumeAt(count) : input.nextPage;
|
|
94
|
+
if (next) result2["nextCursor"] = next;
|
|
95
|
+
if (cut) result2["truncated"] = true;
|
|
96
|
+
return result2;
|
|
97
|
+
};
|
|
98
|
+
const all = build(input.items.length);
|
|
99
|
+
if (jsonSize(all) <= limit) return all;
|
|
100
|
+
let low = 1;
|
|
101
|
+
let high = input.items.length - 1;
|
|
102
|
+
while (low < high) {
|
|
103
|
+
const middle = Math.ceil((low + high) / 2);
|
|
104
|
+
if (jsonSize(build(middle)) <= limit) low = middle;
|
|
105
|
+
else high = middle - 1;
|
|
106
|
+
}
|
|
107
|
+
const best = build(low);
|
|
108
|
+
if (jsonSize(best) <= limit) return best;
|
|
109
|
+
const shrunk = shrinkToFit(best, limit);
|
|
110
|
+
if (shrunk) return { ...shrunk.value, truncated: true };
|
|
111
|
+
throw new ToolFailure("The result is too large to return, even one item at a time.");
|
|
112
|
+
}
|
|
113
|
+
function encodeCursor(tool, state) {
|
|
114
|
+
return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
|
|
115
|
+
}
|
|
116
|
+
function decodeCursor(tool, cursor) {
|
|
117
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
118
|
+
try {
|
|
119
|
+
const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
|
|
120
|
+
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
121
|
+
return state;
|
|
122
|
+
}
|
|
123
|
+
} catch {
|
|
124
|
+
}
|
|
125
|
+
throw new ToolFailure(
|
|
126
|
+
"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."
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/core/credentials.ts
|
|
131
|
+
function requiredAlternatives(module2) {
|
|
132
|
+
return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
|
|
133
|
+
}
|
|
134
|
+
function unmetAlternatives(alternatives, has) {
|
|
135
|
+
const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
|
|
136
|
+
if (lacking.some((list) => list.length === 0)) return [];
|
|
137
|
+
return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
|
|
138
|
+
}
|
|
139
|
+
function andList(items) {
|
|
140
|
+
if (items.length <= 2) return items.join(" and ");
|
|
141
|
+
return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
|
|
142
|
+
}
|
|
143
|
+
function orList(items) {
|
|
144
|
+
if (items.length <= 1) return items.join("");
|
|
145
|
+
return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/core/files.ts
|
|
149
|
+
var ATTACHMENT_URI = "attachment:///";
|
|
150
|
+
var MAX_NAME = 200;
|
|
151
|
+
function fileLimitOf(ctx) {
|
|
152
|
+
const maxBytes = ctx.files?.maxBytes;
|
|
153
|
+
return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
|
|
154
|
+
}
|
|
155
|
+
function fileName(name2) {
|
|
156
|
+
const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
|
|
157
|
+
const points = Array.from(clean);
|
|
158
|
+
if (points.length <= MAX_NAME) return clean || "file";
|
|
159
|
+
const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
|
|
160
|
+
return points.slice(0, MAX_NAME - extension.length).join("") + extension;
|
|
161
|
+
}
|
|
162
|
+
function fileType(mimeType) {
|
|
163
|
+
const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
|
|
164
|
+
return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
|
|
165
|
+
}
|
|
166
|
+
function resourceBlock(file) {
|
|
167
|
+
return {
|
|
168
|
+
type: "resource",
|
|
169
|
+
resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
63
173
|
// src/core/http.ts
|
|
64
174
|
var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
65
175
|
var USER_AGENT = "agent-connectors";
|
|
@@ -104,15 +214,15 @@ function vendorCode(data) {
|
|
|
104
214
|
function vendorMessage(data) {
|
|
105
215
|
if (typeof data === "string") return cleanVendorText(data);
|
|
106
216
|
if (typeof data !== "object" || data === null) return void 0;
|
|
107
|
-
const
|
|
217
|
+
const record2 = data;
|
|
108
218
|
for (const key of ["message", "error_description", "error", "detail", "title"]) {
|
|
109
|
-
const value =
|
|
219
|
+
const value = record2[key];
|
|
110
220
|
if (typeof value === "string" && value.trim()) return cleanVendorText(value);
|
|
111
221
|
const nested = value?.message;
|
|
112
222
|
if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
|
|
113
223
|
}
|
|
114
|
-
if (Array.isArray(
|
|
115
|
-
const messages =
|
|
224
|
+
if (Array.isArray(record2["errors"])) {
|
|
225
|
+
const messages = record2["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
|
|
116
226
|
if (messages.length) return cleanVendorText(messages.join("; "));
|
|
117
227
|
}
|
|
118
228
|
return void 0;
|
|
@@ -168,6 +278,7 @@ function parseBody(bytes, contentType) {
|
|
|
168
278
|
function createHttp(env) {
|
|
169
279
|
const { label, ctx } = env;
|
|
170
280
|
const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
|
|
281
|
+
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.`;
|
|
171
282
|
function failureFor(status, headers, data, request) {
|
|
172
283
|
const message = vendorMessage(data);
|
|
173
284
|
const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
|
|
@@ -190,7 +301,7 @@ function createHttp(env) {
|
|
|
190
301
|
}
|
|
191
302
|
if (status === 401) {
|
|
192
303
|
return new ToolFailure(
|
|
193
|
-
withCustom(`${label} rejected the credentials (HTTP 401)${said}.
|
|
304
|
+
withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
|
|
194
305
|
{ status, ...extra }
|
|
195
306
|
);
|
|
196
307
|
}
|
|
@@ -206,10 +317,16 @@ function createHttp(env) {
|
|
|
206
317
|
}
|
|
207
318
|
const origin = request.origin ?? env.origins[0];
|
|
208
319
|
if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
|
|
209
|
-
const
|
|
210
|
-
if (
|
|
320
|
+
const url2 = new URL(request.path, origin);
|
|
321
|
+
if (url2.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
|
|
211
322
|
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
212
|
-
if (value
|
|
323
|
+
if (value === void 0 || value === null) continue;
|
|
324
|
+
if (Array.isArray(value)) {
|
|
325
|
+
url2.searchParams.delete(key);
|
|
326
|
+
for (const item of value) url2.searchParams.append(key, String(item));
|
|
327
|
+
} else {
|
|
328
|
+
url2.searchParams.set(key, String(value));
|
|
329
|
+
}
|
|
213
330
|
}
|
|
214
331
|
const headers = {
|
|
215
332
|
accept: "application/json",
|
|
@@ -229,7 +346,7 @@ function createHttp(env) {
|
|
|
229
346
|
if (request.write) env.onWriteSent();
|
|
230
347
|
let response;
|
|
231
348
|
try {
|
|
232
|
-
response = await ctx.fetch(
|
|
349
|
+
response = await ctx.fetch(url2.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
|
|
233
350
|
} catch (error) {
|
|
234
351
|
env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
|
|
235
352
|
if (errorCode(error) === "URL_REFUSED") {
|
|
@@ -238,6 +355,7 @@ function createHttp(env) {
|
|
|
238
355
|
if (request.write) {
|
|
239
356
|
throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
|
|
240
357
|
}
|
|
358
|
+
if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
|
|
241
359
|
throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
|
|
242
360
|
}
|
|
243
361
|
env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
|
|
@@ -250,23 +368,23 @@ function createHttp(env) {
|
|
|
250
368
|
}
|
|
251
369
|
throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
|
|
252
370
|
}
|
|
253
|
-
const data = parseBody(bytes, response.headers.get("content-type"));
|
|
371
|
+
const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
|
|
254
372
|
if (response.ok) return { status: response.status, headers: response.headers, data };
|
|
255
373
|
throw failureFor(response.status, response.headers, data, request);
|
|
256
374
|
}
|
|
257
375
|
async function media(rawUrl, options) {
|
|
258
376
|
const { what } = options;
|
|
259
|
-
let
|
|
377
|
+
let url2;
|
|
260
378
|
try {
|
|
261
|
-
|
|
379
|
+
url2 = new URL(rawUrl);
|
|
262
380
|
} catch {
|
|
263
381
|
throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
|
|
264
382
|
}
|
|
265
|
-
if (
|
|
383
|
+
if (url2.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
|
|
266
384
|
const started = Date.now();
|
|
267
385
|
let response;
|
|
268
386
|
try {
|
|
269
|
-
response = await ctx.fetch(
|
|
387
|
+
response = await ctx.fetch(url2.toString(), {
|
|
270
388
|
method: "GET",
|
|
271
389
|
headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
|
|
272
390
|
...ctx.signal ? { signal: ctx.signal } : {}
|
|
@@ -297,68 +415,20 @@ function createHttp(env) {
|
|
|
297
415
|
return { api, media };
|
|
298
416
|
}
|
|
299
417
|
|
|
300
|
-
// src/core/
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
function cutStrings(value, max) {
|
|
306
|
-
if (typeof value === "string") return truncate(value, max);
|
|
307
|
-
if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
|
|
308
|
-
if (typeof value === "object" && value !== null) {
|
|
309
|
-
const out = {};
|
|
310
|
-
for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
|
|
311
|
-
return out;
|
|
312
|
-
}
|
|
313
|
-
return value;
|
|
314
|
-
}
|
|
315
|
-
function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
|
|
316
|
-
if (jsonSize(value) <= limit) return { value, truncated: false };
|
|
317
|
-
for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
|
|
318
|
-
const cut = cutStrings(value, max);
|
|
319
|
-
if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
|
|
320
|
-
}
|
|
321
|
-
return void 0;
|
|
322
|
-
}
|
|
323
|
-
function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
|
|
324
|
-
const build = (count) => {
|
|
325
|
-
const cut = count < input.items.length;
|
|
326
|
-
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
|
|
327
|
-
const next = cut ? input.resumeAt(count) : input.nextPage;
|
|
328
|
-
if (next) result2["nextCursor"] = next;
|
|
329
|
-
if (cut) result2["truncated"] = true;
|
|
330
|
-
return result2;
|
|
331
|
-
};
|
|
332
|
-
const all = build(input.items.length);
|
|
333
|
-
if (jsonSize(all) <= limit) return all;
|
|
334
|
-
let low = 1;
|
|
335
|
-
let high = input.items.length - 1;
|
|
336
|
-
while (low < high) {
|
|
337
|
-
const middle = Math.ceil((low + high) / 2);
|
|
338
|
-
if (jsonSize(build(middle)) <= limit) low = middle;
|
|
339
|
-
else high = middle - 1;
|
|
340
|
-
}
|
|
341
|
-
const best = build(low);
|
|
342
|
-
if (jsonSize(best) <= limit) return best;
|
|
343
|
-
const shrunk = shrinkToFit(best, limit);
|
|
344
|
-
if (shrunk) return { ...shrunk.value, truncated: true };
|
|
345
|
-
throw new ToolFailure("The result is too large to return, even one item at a time.");
|
|
346
|
-
}
|
|
347
|
-
function encodeCursor(tool, state) {
|
|
348
|
-
return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
|
|
349
|
-
}
|
|
350
|
-
function decodeCursor(tool, cursor) {
|
|
351
|
-
if (cursor === void 0 || cursor === "") return null;
|
|
418
|
+
// src/core/origins.ts
|
|
419
|
+
function parseSiteUrl(value) {
|
|
420
|
+
const text2 = typeof value === "string" ? value.trim() : "";
|
|
421
|
+
if (!text2) return { ok: false, problem: "is empty" };
|
|
422
|
+
let url2;
|
|
352
423
|
try {
|
|
353
|
-
|
|
354
|
-
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
355
|
-
return state;
|
|
356
|
-
}
|
|
424
|
+
url2 = new URL(text2.includes("://") ? text2 : `https://${text2}`);
|
|
357
425
|
} catch {
|
|
426
|
+
return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
|
|
358
427
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
);
|
|
428
|
+
if (url2.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url2.protocol}//` };
|
|
429
|
+
if (url2.username || url2.password) return { ok: false, problem: "must not contain a user name or password" };
|
|
430
|
+
if (!url2.hostname) return { ok: false, problem: "has no host name" };
|
|
431
|
+
return { ok: true, url: url2, origin: url2.origin };
|
|
362
432
|
}
|
|
363
433
|
|
|
364
434
|
// src/core/schema.ts
|
|
@@ -376,8 +446,8 @@ function isPlainObject(value) {
|
|
|
376
446
|
}
|
|
377
447
|
function isHttpUrl(value) {
|
|
378
448
|
try {
|
|
379
|
-
const
|
|
380
|
-
return
|
|
449
|
+
const url2 = new URL(value);
|
|
450
|
+
return url2.protocol === "https:" || url2.protocol === "http:";
|
|
381
451
|
} catch {
|
|
382
452
|
return false;
|
|
383
453
|
}
|
|
@@ -500,16 +570,35 @@ function validateArguments(schema, args) {
|
|
|
500
570
|
return { ok: true, value };
|
|
501
571
|
}
|
|
502
572
|
|
|
573
|
+
// src/core/upload-hosts.ts
|
|
574
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
575
|
+
function uploadHostProblem(entry) {
|
|
576
|
+
if (typeof entry !== "string") return "must be a host name";
|
|
577
|
+
const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
|
|
578
|
+
const labels = name2.split(".");
|
|
579
|
+
if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
|
|
580
|
+
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";
|
|
581
|
+
}
|
|
582
|
+
if (labels.length < 2) return "needs at least two labels, like example.com";
|
|
583
|
+
if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
|
|
584
|
+
return void 0;
|
|
585
|
+
}
|
|
586
|
+
|
|
503
587
|
// src/core/connector.ts
|
|
504
588
|
var ANNOTATIONS = {
|
|
505
589
|
read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
506
590
|
create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
507
591
|
update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
508
|
-
delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true }
|
|
592
|
+
delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
593
|
+
write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
|
|
509
594
|
};
|
|
510
595
|
var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
|
|
511
596
|
var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
512
597
|
var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
598
|
+
var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
599
|
+
var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
|
|
600
|
+
var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
601
|
+
var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
|
|
513
602
|
function deepFreeze(value) {
|
|
514
603
|
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
515
604
|
Object.freeze(value);
|
|
@@ -523,18 +612,23 @@ function assertDefinition(def) {
|
|
|
523
612
|
};
|
|
524
613
|
if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
|
|
525
614
|
if (!def.label?.trim()) problem("label is required");
|
|
526
|
-
|
|
615
|
+
const originFields = def.originFields ?? [];
|
|
616
|
+
if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
|
|
527
617
|
for (const origin of def.origins) {
|
|
528
|
-
let
|
|
618
|
+
let url2;
|
|
529
619
|
try {
|
|
530
|
-
|
|
620
|
+
url2 = new URL(origin);
|
|
531
621
|
} catch {
|
|
532
622
|
}
|
|
533
|
-
if (!
|
|
623
|
+
if (!url2 || url2.protocol !== "https:" || url2.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
|
|
534
624
|
}
|
|
535
625
|
for (const name2 of def.credentials) {
|
|
536
626
|
if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
|
|
537
627
|
}
|
|
628
|
+
for (const [index, name2] of originFields.entries()) {
|
|
629
|
+
if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
|
|
630
|
+
if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
|
|
631
|
+
}
|
|
538
632
|
const names = /* @__PURE__ */ new Set();
|
|
539
633
|
for (const tool of def.tools) {
|
|
540
634
|
if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
@@ -542,7 +636,7 @@ function assertDefinition(def) {
|
|
|
542
636
|
names.add(tool.name);
|
|
543
637
|
if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
|
|
544
638
|
if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
|
|
545
|
-
if (!(tool.kind
|
|
639
|
+
if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
|
|
546
640
|
if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
|
|
547
641
|
problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
|
|
548
642
|
}
|
|
@@ -552,9 +646,95 @@ function assertDefinition(def) {
|
|
|
552
646
|
const check = def.tools.find((candidate) => candidate.name === tool.check);
|
|
553
647
|
if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
|
|
554
648
|
}
|
|
649
|
+
assertUploadHosts(def, problem);
|
|
650
|
+
assertRequiredCredentials(def, problem);
|
|
651
|
+
assertAccountPickers(def, problem);
|
|
652
|
+
}
|
|
653
|
+
function assertUploadHosts(def, problem) {
|
|
654
|
+
const hosts = def.uploadHosts;
|
|
655
|
+
if (hosts === void 0) return;
|
|
656
|
+
if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
|
|
657
|
+
hosts.forEach((entry, index) => {
|
|
658
|
+
const wrong = uploadHostProblem(entry);
|
|
659
|
+
if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
|
|
660
|
+
if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
function assertRequiredCredentials(def, problem) {
|
|
664
|
+
const required = def.requiredCredentials;
|
|
665
|
+
if (required === void 0) return;
|
|
666
|
+
if (!Array.isArray(required) || !required.length) {
|
|
667
|
+
problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
|
|
668
|
+
}
|
|
669
|
+
required.forEach((list, index) => {
|
|
670
|
+
const which = `requiredCredentials[${index}]`;
|
|
671
|
+
if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
|
|
672
|
+
list.forEach((name2, position2) => {
|
|
673
|
+
if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
|
|
674
|
+
if (list.indexOf(name2) !== position2) problem(`${which} lists ${name2} twice`);
|
|
675
|
+
});
|
|
676
|
+
});
|
|
677
|
+
const lists = required;
|
|
678
|
+
lists.forEach((list, index) => {
|
|
679
|
+
const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
|
|
680
|
+
if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
|
|
681
|
+
if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
|
|
682
|
+
problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
function isDotPath(value) {
|
|
687
|
+
return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
|
|
688
|
+
}
|
|
689
|
+
function assertAccountPickers(def, problem) {
|
|
690
|
+
const pickers = def.accountPickers;
|
|
691
|
+
if (pickers === void 0) return;
|
|
692
|
+
if (!Array.isArray(pickers)) problem("accountPickers must be a list");
|
|
693
|
+
const keys = /* @__PURE__ */ new Set();
|
|
694
|
+
for (const item of pickers) {
|
|
695
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
|
|
696
|
+
const picker = item;
|
|
697
|
+
const key = picker["key"];
|
|
698
|
+
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}$`);
|
|
699
|
+
if (keys.has(key)) problem(`account picker ${key} is defined twice`);
|
|
700
|
+
keys.add(key);
|
|
701
|
+
const fail = (message) => problem(`account picker ${key}: ${message}`);
|
|
702
|
+
const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
|
|
703
|
+
if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
|
|
704
|
+
const { label, description, multiple, legacyField } = picker;
|
|
705
|
+
if (typeof label !== "string" || !label.trim()) fail("label is required");
|
|
706
|
+
if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
|
|
707
|
+
fail("description, when given, must be a text of 1 to 1024 characters");
|
|
708
|
+
}
|
|
709
|
+
if (typeof multiple !== "boolean") fail("multiple must be true or false");
|
|
710
|
+
const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
|
|
711
|
+
if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
|
|
712
|
+
if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
|
|
713
|
+
for (const field of ["idField", "nameField"]) {
|
|
714
|
+
if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
|
|
715
|
+
}
|
|
716
|
+
if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
|
|
717
|
+
fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
function copyPicker(picker) {
|
|
722
|
+
return {
|
|
723
|
+
key: picker.key,
|
|
724
|
+
label: picker.label,
|
|
725
|
+
...picker.description !== void 0 ? { description: picker.description } : {},
|
|
726
|
+
multiple: picker.multiple,
|
|
727
|
+
tool: picker.tool,
|
|
728
|
+
idField: picker.idField,
|
|
729
|
+
nameField: picker.nameField,
|
|
730
|
+
...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
|
|
731
|
+
};
|
|
555
732
|
}
|
|
556
|
-
function result(payload, isError) {
|
|
557
|
-
return {
|
|
733
|
+
function result(payload, isError, files = []) {
|
|
734
|
+
return {
|
|
735
|
+
content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
|
|
736
|
+
...isError ? { isError: true } : {}
|
|
737
|
+
};
|
|
558
738
|
}
|
|
559
739
|
function failure(message, details = {}) {
|
|
560
740
|
return result({ error: message, ...details }, true);
|
|
@@ -575,6 +755,14 @@ function defineConnector(def) {
|
|
|
575
755
|
const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
|
|
576
756
|
const toolList = def.tools.map((tool) => tool.name).join(", ");
|
|
577
757
|
const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
|
|
758
|
+
const required = requiredAlternatives(def);
|
|
759
|
+
const notConnected = (unmet) => {
|
|
760
|
+
const [first] = unmet;
|
|
761
|
+
if (unmet.length === 1 && first) {
|
|
762
|
+
return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
|
|
763
|
+
}
|
|
764
|
+
return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
|
|
765
|
+
};
|
|
578
766
|
const descriptors = def.tools.map((tool) => ({
|
|
579
767
|
name: tool.name,
|
|
580
768
|
title: tool.title,
|
|
@@ -592,23 +780,36 @@ function defineConnector(def) {
|
|
|
592
780
|
} catch {
|
|
593
781
|
}
|
|
594
782
|
};
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
const
|
|
598
|
-
|
|
599
|
-
|
|
783
|
+
const given = trimmed(ctx.credentials);
|
|
784
|
+
const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
|
|
785
|
+
const has = (name2) => Boolean(credentials[name2]);
|
|
786
|
+
const unmet = unmetAlternatives(required, has);
|
|
787
|
+
if (unmet.length) return failure(notConnected(unmet));
|
|
788
|
+
const complete = required.filter((list) => list.every(has));
|
|
789
|
+
const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
|
|
790
|
+
const fieldOrigins = /* @__PURE__ */ new Map();
|
|
791
|
+
for (const name2 of def.originFields ?? []) {
|
|
792
|
+
if (!given[name2] && !inUse.includes(name2)) continue;
|
|
793
|
+
const site = parseSiteUrl(given[name2] ?? "");
|
|
794
|
+
if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
|
|
795
|
+
fieldOrigins.set(name2, site.origin);
|
|
600
796
|
}
|
|
797
|
+
const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
|
|
601
798
|
const parsed = validateArguments(tool.inputSchema, args);
|
|
602
799
|
if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
|
|
603
800
|
const frozenCredentials = Object.freeze({ ...credentials });
|
|
604
801
|
let writeSent = false;
|
|
802
|
+
const fileLimit = fileLimitOf(ctx);
|
|
803
|
+
const files = [];
|
|
804
|
+
let fileBytes = 0;
|
|
605
805
|
const http = createHttp({
|
|
606
806
|
vendor: def.vendor,
|
|
607
807
|
label,
|
|
608
808
|
tool: tool.name,
|
|
609
809
|
readOnly: tool.kind === "read",
|
|
610
|
-
origins
|
|
611
|
-
|
|
810
|
+
origins,
|
|
811
|
+
// A 401 names the credentials in use (for a module that needs none, the ones given).
|
|
812
|
+
credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
|
|
612
813
|
ctx,
|
|
613
814
|
authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
|
|
614
815
|
log,
|
|
@@ -620,11 +821,29 @@ function defineConnector(def) {
|
|
|
620
821
|
tool: tool.name,
|
|
621
822
|
credentials: frozenCredentials,
|
|
622
823
|
ctx,
|
|
824
|
+
origins: Object.freeze([...origins]),
|
|
825
|
+
originOf: (credential) => {
|
|
826
|
+
const origin = fieldOrigins.get(credential);
|
|
827
|
+
if (!origin) throw new Error(`${credential} gives no origin in this call`);
|
|
828
|
+
return origin;
|
|
829
|
+
},
|
|
623
830
|
api: http.api,
|
|
624
831
|
media: http.media,
|
|
625
832
|
page: (input) => fitPage(input),
|
|
626
833
|
cursor: (cursor) => decodeCursor(tool.name, cursor),
|
|
627
834
|
makeCursor: (state) => encodeCursor(tool.name, state),
|
|
835
|
+
fileLimit: () => fileLimit,
|
|
836
|
+
file: ({ name: name2, mimeType, bytes }) => {
|
|
837
|
+
if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
|
|
838
|
+
const total = fileBytes + bytes.byteLength;
|
|
839
|
+
if (total > fileLimit) {
|
|
840
|
+
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.`);
|
|
841
|
+
}
|
|
842
|
+
fileBytes = total;
|
|
843
|
+
const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
|
|
844
|
+
files.push({ ...info, bytes });
|
|
845
|
+
return { ...info };
|
|
846
|
+
},
|
|
628
847
|
log
|
|
629
848
|
};
|
|
630
849
|
try {
|
|
@@ -632,7 +851,7 @@ function defineConnector(def) {
|
|
|
632
851
|
const fitted = shrinkToFit(data ?? {});
|
|
633
852
|
if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
|
|
634
853
|
const payload = fitted.value;
|
|
635
|
-
return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false);
|
|
854
|
+
return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
|
|
636
855
|
} catch (error) {
|
|
637
856
|
if (error instanceof OutcomeUnknown) {
|
|
638
857
|
return result({
|
|
@@ -656,116 +875,619 @@ function defineConnector(def) {
|
|
|
656
875
|
return deepFreeze({
|
|
657
876
|
vendor: def.vendor,
|
|
658
877
|
origins: [...def.origins],
|
|
878
|
+
originFields: [...def.originFields ?? []],
|
|
879
|
+
uploadHosts: [...def.uploadHosts ?? []],
|
|
659
880
|
credentials: [...def.credentials],
|
|
881
|
+
requiredCredentials: required.map((list) => [...list]),
|
|
882
|
+
accountPickers: (def.accountPickers ?? []).map(copyPicker),
|
|
660
883
|
tools: descriptors,
|
|
661
884
|
call
|
|
662
885
|
});
|
|
663
886
|
}
|
|
664
887
|
|
|
665
|
-
// src/
|
|
666
|
-
var
|
|
888
|
+
// src/core/jwt.ts
|
|
889
|
+
var TOKEN_EARLY_MS = 5 * 60 * 1e3;
|
|
890
|
+
|
|
891
|
+
// src/vendors/serper/trim.ts
|
|
667
892
|
function text(value, max) {
|
|
668
893
|
return typeof value === "string" && value.trim() ? truncate(value.trim(), max) : void 0;
|
|
669
894
|
}
|
|
895
|
+
function num(value) {
|
|
896
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
897
|
+
}
|
|
898
|
+
function url(value) {
|
|
899
|
+
return typeof value === "string" && /^https?:\/\//i.test(value) && value.length <= 2e3 ? value : void 0;
|
|
900
|
+
}
|
|
670
901
|
function compact(value) {
|
|
671
902
|
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
|
|
672
903
|
}
|
|
904
|
+
function record(value) {
|
|
905
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
906
|
+
}
|
|
907
|
+
function listOf(data, key) {
|
|
908
|
+
const list = record(data)[key];
|
|
909
|
+
return Array.isArray(list) ? list.map(record) : [];
|
|
910
|
+
}
|
|
911
|
+
function texts(value, max, count) {
|
|
912
|
+
if (!Array.isArray(value)) return void 0;
|
|
913
|
+
const list = value.map((item) => text(item, max)).filter((item) => item !== void 0).slice(0, count);
|
|
914
|
+
return list.length ? list : void 0;
|
|
915
|
+
}
|
|
673
916
|
function trimOrganic(item) {
|
|
674
917
|
return compact({
|
|
675
|
-
position:
|
|
676
|
-
title: text(item
|
|
677
|
-
link:
|
|
678
|
-
snippet: text(item
|
|
679
|
-
date: text(item
|
|
918
|
+
position: num(item["position"]),
|
|
919
|
+
title: text(item["title"], 300),
|
|
920
|
+
link: url(item["link"]),
|
|
921
|
+
snippet: text(item["snippet"], 600),
|
|
922
|
+
date: text(item["date"], 40)
|
|
680
923
|
});
|
|
681
924
|
}
|
|
682
|
-
function trimAnswerBox(
|
|
683
|
-
|
|
684
|
-
const
|
|
685
|
-
title: text(box
|
|
686
|
-
answer: text(box
|
|
687
|
-
snippet: text(box
|
|
688
|
-
link:
|
|
925
|
+
function trimAnswerBox(value) {
|
|
926
|
+
const box = record(value);
|
|
927
|
+
const trimmed2 = compact({
|
|
928
|
+
title: text(box["title"], 300),
|
|
929
|
+
answer: text(box["answer"], 600),
|
|
930
|
+
snippet: text(box["snippet"], 1e3),
|
|
931
|
+
link: url(box["link"])
|
|
689
932
|
});
|
|
690
|
-
return Object.keys(
|
|
691
|
-
}
|
|
692
|
-
function trimKnowledgeGraph(
|
|
693
|
-
|
|
694
|
-
const
|
|
695
|
-
const
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
933
|
+
return Object.keys(trimmed2).length ? trimmed2 : void 0;
|
|
934
|
+
}
|
|
935
|
+
function trimKnowledgeGraph(value) {
|
|
936
|
+
const graph = record(value);
|
|
937
|
+
const rawAttributes = record(graph["attributes"]);
|
|
938
|
+
const attributes = Object.keys(rawAttributes).length ? Object.fromEntries(Object.entries(rawAttributes).slice(0, 12).map(([key, item]) => [truncate(key, 80), text(item, 200) ?? ""])) : void 0;
|
|
939
|
+
const trimmed2 = compact({
|
|
940
|
+
title: text(graph["title"], 300),
|
|
941
|
+
type: text(graph["type"], 120),
|
|
942
|
+
description: text(graph["description"], 1e3),
|
|
943
|
+
website: url(graph["website"]),
|
|
700
944
|
attributes
|
|
701
945
|
});
|
|
702
|
-
return Object.keys(
|
|
946
|
+
return Object.keys(trimmed2).length ? trimmed2 : void 0;
|
|
947
|
+
}
|
|
948
|
+
function trimNews(item) {
|
|
949
|
+
return compact({
|
|
950
|
+
position: num(item["position"]),
|
|
951
|
+
title: text(item["title"], 300),
|
|
952
|
+
link: url(item["link"]),
|
|
953
|
+
snippet: text(item["snippet"], 600),
|
|
954
|
+
date: text(item["date"], 60),
|
|
955
|
+
source: text(item["source"], 120),
|
|
956
|
+
imageUrl: url(item["imageUrl"])
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
function trimImage(item) {
|
|
960
|
+
return compact({
|
|
961
|
+
position: num(item["position"]),
|
|
962
|
+
title: text(item["title"], 300),
|
|
963
|
+
imageUrl: url(item["imageUrl"]),
|
|
964
|
+
imageWidth: num(item["imageWidth"]),
|
|
965
|
+
imageHeight: num(item["imageHeight"]),
|
|
966
|
+
thumbnailUrl: url(item["thumbnailUrl"]),
|
|
967
|
+
source: text(item["source"], 120),
|
|
968
|
+
domain: text(item["domain"], 200),
|
|
969
|
+
link: url(item["link"])
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
function trimVideo(item) {
|
|
973
|
+
return compact({
|
|
974
|
+
position: num(item["position"]),
|
|
975
|
+
title: text(item["title"], 300),
|
|
976
|
+
link: url(item["link"]),
|
|
977
|
+
snippet: text(item["snippet"], 600),
|
|
978
|
+
date: text(item["date"], 60),
|
|
979
|
+
duration: text(item["duration"], 30),
|
|
980
|
+
source: text(item["source"], 120),
|
|
981
|
+
channel: text(item["channel"], 200),
|
|
982
|
+
imageUrl: url(item["imageUrl"])
|
|
983
|
+
});
|
|
984
|
+
}
|
|
985
|
+
function trimPlace(item) {
|
|
986
|
+
const hours = record(item["openingHours"]);
|
|
987
|
+
return compact({
|
|
988
|
+
position: num(item["position"]),
|
|
989
|
+
title: text(item["title"], 300),
|
|
990
|
+
address: text(item["address"], 300),
|
|
991
|
+
latitude: num(item["latitude"]),
|
|
992
|
+
longitude: num(item["longitude"]),
|
|
993
|
+
rating: num(item["rating"]),
|
|
994
|
+
ratingCount: num(item["ratingCount"]),
|
|
995
|
+
priceLevel: text(item["priceLevel"], 20),
|
|
996
|
+
category: text(item["category"], 120),
|
|
997
|
+
type: text(item["type"], 120),
|
|
998
|
+
types: texts(item["types"], 80, 10),
|
|
999
|
+
description: text(item["description"], 600),
|
|
1000
|
+
phoneNumber: text(item["phoneNumber"], 60),
|
|
1001
|
+
website: url(item["website"]),
|
|
1002
|
+
openingHours: Object.keys(hours).length ? Object.fromEntries(Object.entries(hours).slice(0, 7).map(([day, value]) => [truncate(day, 20), text(value, 100) ?? ""])) : void 0,
|
|
1003
|
+
cid: text(item["cid"], 40),
|
|
1004
|
+
fid: text(item["fid"], 80),
|
|
1005
|
+
placeId: text(item["placeId"], 120)
|
|
1006
|
+
});
|
|
703
1007
|
}
|
|
1008
|
+
function trimShopping(item) {
|
|
1009
|
+
return compact({
|
|
1010
|
+
position: num(item["position"]),
|
|
1011
|
+
title: text(item["title"], 300),
|
|
1012
|
+
source: text(item["source"], 120),
|
|
1013
|
+
link: url(item["link"]),
|
|
1014
|
+
price: text(item["price"], 60),
|
|
1015
|
+
delivery: text(item["delivery"], 120),
|
|
1016
|
+
rating: num(item["rating"]),
|
|
1017
|
+
ratingCount: num(item["ratingCount"]),
|
|
1018
|
+
offers: text(item["offers"], 60),
|
|
1019
|
+
productId: text(item["productId"], 80),
|
|
1020
|
+
imageUrl: url(item["imageUrl"])
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
function trimScholar(item) {
|
|
1024
|
+
return compact({
|
|
1025
|
+
position: num(item["position"]),
|
|
1026
|
+
title: text(item["title"], 300),
|
|
1027
|
+
link: url(item["link"]),
|
|
1028
|
+
publicationInfo: text(item["publicationInfo"], 300),
|
|
1029
|
+
snippet: text(item["snippet"], 600),
|
|
1030
|
+
year: num(item["year"]),
|
|
1031
|
+
citedBy: num(item["citedBy"]),
|
|
1032
|
+
pdfUrl: url(item["pdfUrl"]),
|
|
1033
|
+
id: text(item["id"], 80)
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
function trimPatent(item) {
|
|
1037
|
+
return compact({
|
|
1038
|
+
position: num(item["position"]),
|
|
1039
|
+
title: text(item["title"], 300),
|
|
1040
|
+
snippet: text(item["snippet"], 600),
|
|
1041
|
+
link: url(item["link"]),
|
|
1042
|
+
publicationNumber: text(item["publicationNumber"], 60),
|
|
1043
|
+
priorityDate: text(item["priorityDate"], 20),
|
|
1044
|
+
filingDate: text(item["filingDate"], 20),
|
|
1045
|
+
grantDate: text(item["grantDate"], 20),
|
|
1046
|
+
publicationDate: text(item["publicationDate"], 20),
|
|
1047
|
+
inventor: text(item["inventor"], 300),
|
|
1048
|
+
assignee: text(item["assignee"], 300),
|
|
1049
|
+
language: text(item["language"], 20),
|
|
1050
|
+
pdfUrl: url(item["pdfUrl"])
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
function trimReview(item) {
|
|
1054
|
+
const user = record(item["user"]);
|
|
1055
|
+
const response = record(item["response"]);
|
|
1056
|
+
const reply = compact({
|
|
1057
|
+
date: text(response["date"], 60),
|
|
1058
|
+
snippet: text(response["snippet"] ?? response["text"], 1e3)
|
|
1059
|
+
});
|
|
1060
|
+
return compact({
|
|
1061
|
+
rating: num(item["rating"]),
|
|
1062
|
+
date: text(item["date"], 60),
|
|
1063
|
+
isoDate: text(item["isoDate"], 40),
|
|
1064
|
+
snippet: text(item["snippet"], 1500),
|
|
1065
|
+
likes: num(item["likes"]),
|
|
1066
|
+
user: Object.keys(user).length ? compact({ name: text(user["name"], 120), reviews: num(user["reviews"]), photos: num(user["photos"]) }) : void 0,
|
|
1067
|
+
response: Object.keys(reply).length ? reply : void 0
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
function trimTopic(item) {
|
|
1071
|
+
return compact({ id: text(item["id"], 120), keyword: text(item["keyword"], 120), count: num(item["count"]) });
|
|
1072
|
+
}
|
|
1073
|
+
function trimLensMatch(item) {
|
|
1074
|
+
return compact({
|
|
1075
|
+
position: num(item["position"]),
|
|
1076
|
+
title: text(item["title"], 300),
|
|
1077
|
+
source: text(item["source"], 120),
|
|
1078
|
+
link: url(item["link"]),
|
|
1079
|
+
price: text(item["price"], 60),
|
|
1080
|
+
inStock: typeof item["inStock"] === "boolean" ? item["inStock"] : void 0,
|
|
1081
|
+
imageUrl: url(item["imageUrl"]),
|
|
1082
|
+
thumbnailUrl: url(item["thumbnailUrl"])
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
function trimLocation(item) {
|
|
1086
|
+
return compact({
|
|
1087
|
+
name: text(item["name"], 200),
|
|
1088
|
+
canonicalName: text(item["canonicalName"], 300),
|
|
1089
|
+
countryCode: text(item["countryCode"], 4),
|
|
1090
|
+
targetType: text(item["targetType"], 60)
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// src/vendors/serper/index.ts
|
|
1095
|
+
var SEARCH_ORIGIN = "https://google.serper.dev";
|
|
1096
|
+
var LOCATIONS_ORIGIN = "https://api.serper.dev";
|
|
1097
|
+
var MAX_PAGE = 10;
|
|
1098
|
+
var LL_PATTERN = "^@-?\\d{1,3}(\\.\\d+)?,-?\\d{1,3}(\\.\\d+)?(,\\d{1,2}(\\.\\d+)?z)?$";
|
|
1099
|
+
var LL = new RegExp(LL_PATTERN);
|
|
1100
|
+
var ERRORS = {
|
|
1101
|
+
400: "Serper could not run this search: check the query and the options.",
|
|
1102
|
+
403: "Serper refused the API key: it may be wrong, disabled, or out of credits."
|
|
1103
|
+
};
|
|
1104
|
+
var QUERY = { type: "string", minLength: 1, maxLength: 2048, description: "The search query, as you would type it into Google." };
|
|
1105
|
+
var CURSOR = { type: "string", description: "nextCursor from the previous result, for the next page." };
|
|
1106
|
+
var PAGE = {
|
|
1107
|
+
type: "integer",
|
|
1108
|
+
minimum: 1,
|
|
1109
|
+
maximum: MAX_PAGE,
|
|
1110
|
+
description: `The result page to start at, 1 to ${MAX_PAGE} (default 1). nextCursor goes on from there.`
|
|
1111
|
+
};
|
|
1112
|
+
var NUM_10 = { type: "integer", minimum: 1, maximum: 10, default: 10, description: "Results per page, 1 to 10 (default 10): Google shows at most 10 a page." };
|
|
1113
|
+
var OPTIONS = {
|
|
1114
|
+
num: NUM_10,
|
|
1115
|
+
gl: { type: "string", pattern: "^[A-Za-z]{2}$", description: 'Two-letter country code to search from, e.g. "us" or "de".' },
|
|
1116
|
+
hl: { type: "string", pattern: "^[A-Za-z]{2,3}(-[A-Za-z]{2,4})?$", description: 'Interface language code, e.g. "en" or "pt-br".' },
|
|
1117
|
+
location: {
|
|
1118
|
+
type: "string",
|
|
1119
|
+
minLength: 2,
|
|
1120
|
+
maxLength: 200,
|
|
1121
|
+
description: 'A place to search from, as Google names it, e.g. "Austin,Texas,United States" (find_locations gives the exact names).'
|
|
1122
|
+
},
|
|
1123
|
+
tbs: {
|
|
1124
|
+
type: "string",
|
|
1125
|
+
enum: ["qdr:h", "qdr:d", "qdr:w", "qdr:m", "qdr:y"],
|
|
1126
|
+
description: "Only results from the past hour (qdr:h), day (qdr:d), week (qdr:w), month (qdr:m) or year (qdr:y)."
|
|
1127
|
+
},
|
|
1128
|
+
autocorrect: { type: "boolean", description: "Let Google correct the spelling of the query (default true)." }
|
|
1129
|
+
};
|
|
1130
|
+
function searchBody(args, page) {
|
|
1131
|
+
return compact({
|
|
1132
|
+
q: args.q,
|
|
1133
|
+
num: args.num,
|
|
1134
|
+
page,
|
|
1135
|
+
gl: args.gl?.toLowerCase(),
|
|
1136
|
+
hl: args.hl?.toLowerCase(),
|
|
1137
|
+
location: args.location,
|
|
1138
|
+
tbs: args.tbs,
|
|
1139
|
+
autocorrect: args.autocorrect
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
async function search(h, path, body) {
|
|
1143
|
+
const { data } = await h.api({ method: "POST", origin: SEARCH_ORIGIN, path, json: body, safe: true, errors: ERRORS });
|
|
1144
|
+
return data;
|
|
1145
|
+
}
|
|
1146
|
+
function position(h, args) {
|
|
1147
|
+
const state = h.cursor(args.cursor);
|
|
1148
|
+
return {
|
|
1149
|
+
page: typeof state?.["p"] === "number" ? state["p"] : args.page ?? 1,
|
|
1150
|
+
skip: typeof state?.["o"] === "number" ? state["o"] : 0
|
|
1151
|
+
};
|
|
1152
|
+
}
|
|
1153
|
+
function notEmpty(item) {
|
|
1154
|
+
return Object.keys(item).length > 0;
|
|
1155
|
+
}
|
|
1156
|
+
function listSearch(spec) {
|
|
1157
|
+
const properties = { q: QUERY };
|
|
1158
|
+
if (spec.options.includes("num")) properties["num"] = spec.num ?? OPTIONS.num;
|
|
1159
|
+
properties["page"] = PAGE;
|
|
1160
|
+
for (const option of spec.options) if (option !== "num") properties[option] = OPTIONS[option];
|
|
1161
|
+
properties["cursor"] = CURSOR;
|
|
1162
|
+
return {
|
|
1163
|
+
name: spec.name,
|
|
1164
|
+
kind: "read",
|
|
1165
|
+
title: spec.title,
|
|
1166
|
+
description: spec.description,
|
|
1167
|
+
inputSchema: { type: "object", properties, required: ["q"], additionalProperties: false },
|
|
1168
|
+
async run(args, h) {
|
|
1169
|
+
const { page, skip } = position(h, args);
|
|
1170
|
+
const data = await search(h, spec.path, searchBody(args, page));
|
|
1171
|
+
const items = listOf(data, spec.listKey);
|
|
1172
|
+
const full = items.length >= (args.num ?? spec.pageSize);
|
|
1173
|
+
return h.page({
|
|
1174
|
+
key: spec.resultKey,
|
|
1175
|
+
items: items.map(spec.trim).filter(notEmpty).slice(skip),
|
|
1176
|
+
extra: compact({ query: args.q, page, creditsUsed: num(data?.credits) }),
|
|
1177
|
+
resumeAt: (index) => h.makeCursor({ p: page, o: skip + index }),
|
|
1178
|
+
...full && page < MAX_PAGE ? { nextPage: h.makeCursor({ p: page + 1, o: 0 }) } : {}
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
var webSearch = {
|
|
1184
|
+
name: "web_search",
|
|
1185
|
+
kind: "read",
|
|
1186
|
+
title: "Search the web (Google results via Serper)",
|
|
1187
|
+
description: "Searches Google through Serper and returns the organic results (title, link, snippet, position, date), plus the answer box, knowledge graph, related questions and related searches when Google shows them. Options for country, language, location, freshness and the page. Read the pages themselves with a fetch tool. Each call uses one Serper credit. Pass nextCursor back as cursor for the next page.",
|
|
1188
|
+
inputSchema: {
|
|
1189
|
+
type: "object",
|
|
1190
|
+
properties: {
|
|
1191
|
+
q: QUERY,
|
|
1192
|
+
num: OPTIONS.num,
|
|
1193
|
+
page: PAGE,
|
|
1194
|
+
gl: OPTIONS.gl,
|
|
1195
|
+
hl: OPTIONS.hl,
|
|
1196
|
+
location: OPTIONS.location,
|
|
1197
|
+
tbs: OPTIONS.tbs,
|
|
1198
|
+
autocorrect: OPTIONS.autocorrect,
|
|
1199
|
+
cursor: CURSOR
|
|
1200
|
+
},
|
|
1201
|
+
required: ["q"],
|
|
1202
|
+
additionalProperties: false
|
|
1203
|
+
},
|
|
1204
|
+
async run(args, h) {
|
|
1205
|
+
const { page, skip } = position(h, args);
|
|
1206
|
+
const data = await search(h, "/search", searchBody(args, page));
|
|
1207
|
+
const organic = listOf(data, "organic");
|
|
1208
|
+
const firstPage = page === 1 && skip === 0;
|
|
1209
|
+
return h.page({
|
|
1210
|
+
key: "results",
|
|
1211
|
+
items: organic.map(trimOrganic).filter(notEmpty).slice(skip),
|
|
1212
|
+
extra: compact({
|
|
1213
|
+
query: args.q,
|
|
1214
|
+
page,
|
|
1215
|
+
answerBox: firstPage ? trimAnswerBox(data?.answerBox) : void 0,
|
|
1216
|
+
knowledgeGraph: firstPage ? trimKnowledgeGraph(data?.knowledgeGraph) : void 0,
|
|
1217
|
+
peopleAlsoAsk: firstPage && Array.isArray(data?.peopleAlsoAsk) ? listOf(data, "peopleAlsoAsk").slice(0, 5).map((item) => compact({ question: text(item["question"], 300), snippet: text(item["snippet"], 600), link: text(item["link"], 2e3) })) : void 0,
|
|
1218
|
+
relatedSearches: firstPage && Array.isArray(data?.relatedSearches) ? listOf(data, "relatedSearches").slice(0, 8).map((item) => text(item["query"], 200)).filter(Boolean) : void 0
|
|
1219
|
+
}),
|
|
1220
|
+
resumeAt: (index) => h.makeCursor({ p: page, o: skip + index }),
|
|
1221
|
+
...organic.length >= args.num && page < MAX_PAGE ? { nextPage: h.makeCursor({ p: page + 1, o: 0 }) } : {}
|
|
1222
|
+
});
|
|
1223
|
+
}
|
|
1224
|
+
};
|
|
1225
|
+
var mapsSearch = {
|
|
1226
|
+
name: "maps_search",
|
|
1227
|
+
kind: "read",
|
|
1228
|
+
title: "Search Google Maps via Serper",
|
|
1229
|
+
description: "Searches Google Maps through Serper: places with address, coordinates, rating and review count, price level, type, opening hours, phone, website, and the cid, fid and placeId that place_reviews takes. Search around a point with ll, or look up one place by place_id or cid. Each call uses three Serper credits. Pass nextCursor back as cursor for the next page: it keeps the map position (ll) that pages after the first need.",
|
|
1230
|
+
inputSchema: {
|
|
1231
|
+
type: "object",
|
|
1232
|
+
properties: {
|
|
1233
|
+
q: QUERY,
|
|
1234
|
+
ll: {
|
|
1235
|
+
type: "string",
|
|
1236
|
+
pattern: LL_PATTERN,
|
|
1237
|
+
description: 'The map position and zoom to search around, as "@latitude,longitude,zoomz" (zoom 3 to 21, optional), e.g. "@40.7128,-74.0060,14z". Needed for a page after the first (each result gives the ll it used); not used by a place_id or cid lookup.'
|
|
1238
|
+
},
|
|
1239
|
+
place_id: { type: "string", minLength: 1, maxLength: 200, description: "Look up one place by its Google place ID." },
|
|
1240
|
+
cid: { type: "string", pattern: "^[0-9]{1,25}$", description: "Look up one place by its Google cid (a number)." },
|
|
1241
|
+
page: PAGE,
|
|
1242
|
+
gl: OPTIONS.gl,
|
|
1243
|
+
hl: OPTIONS.hl,
|
|
1244
|
+
cursor: CURSOR
|
|
1245
|
+
},
|
|
1246
|
+
required: ["q"],
|
|
1247
|
+
additionalProperties: false
|
|
1248
|
+
},
|
|
1249
|
+
async run(args, h) {
|
|
1250
|
+
const state = h.cursor(args.cursor);
|
|
1251
|
+
const page = typeof state?.["p"] === "number" ? state["p"] : args.page ?? 1;
|
|
1252
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1253
|
+
const ll = typeof state?.["l"] === "string" ? state["l"] : args.ll;
|
|
1254
|
+
const lookup = args.place_id !== void 0 || args.cid !== void 0;
|
|
1255
|
+
if (lookup && page > 1) throw new ToolFailure("A lookup by place_id or cid has one page only. Nothing was sent to Serper.");
|
|
1256
|
+
if (page > 1 && !ll) {
|
|
1257
|
+
throw new ToolFailure(
|
|
1258
|
+
"Google Maps pages after the first need ll, the map position: give the ll of the first page's result, or pass its nextCursor, which carries it. Nothing was sent to Serper."
|
|
1259
|
+
);
|
|
1260
|
+
}
|
|
1261
|
+
const data = await search(h, "/maps", compact({
|
|
1262
|
+
q: args.q,
|
|
1263
|
+
ll,
|
|
1264
|
+
placeId: args.place_id,
|
|
1265
|
+
cid: args.cid,
|
|
1266
|
+
page,
|
|
1267
|
+
gl: args.gl?.toLowerCase(),
|
|
1268
|
+
hl: args.hl?.toLowerCase()
|
|
1269
|
+
}));
|
|
1270
|
+
const places = listOf(data, "places");
|
|
1271
|
+
const replyLl = text(data?.ll, 60);
|
|
1272
|
+
const nextLl = ll ?? (replyLl && LL.test(replyLl) ? replyLl : void 0);
|
|
1273
|
+
return h.page({
|
|
1274
|
+
key: "places",
|
|
1275
|
+
items: places.map(trimPlace).filter(notEmpty).slice(skip),
|
|
1276
|
+
extra: compact({ query: args.q, page, ll: replyLl, creditsUsed: num(data?.credits) }),
|
|
1277
|
+
resumeAt: (index) => h.makeCursor({ p: page, o: skip + index, ...ll ? { l: ll } : {} }),
|
|
1278
|
+
...!lookup && nextLl && places.length >= 10 && page < MAX_PAGE ? { nextPage: h.makeCursor({ p: page + 1, o: 0, l: nextLl }) } : {}
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
};
|
|
1282
|
+
var placeReviews = {
|
|
1283
|
+
name: "place_reviews",
|
|
1284
|
+
kind: "read",
|
|
1285
|
+
title: "Read the Google reviews of a place via Serper",
|
|
1286
|
+
description: "The Google reviews of one place, found by the cid, fid or place_id that maps_search and places_search return: rating, date, text, likes, the reviewer's name and the owner's reply, newest or most relevant first, plus the topics Google groups them by (pass a topic id as topic_id to read only those). Each call uses one Serper credit. Pass nextCursor back as cursor for more.",
|
|
1287
|
+
inputSchema: {
|
|
1288
|
+
type: "object",
|
|
1289
|
+
properties: {
|
|
1290
|
+
cid: { type: "string", pattern: "^[0-9]{1,25}$", description: "The place's Google cid." },
|
|
1291
|
+
fid: { type: "string", minLength: 1, maxLength: 100, description: `The place's Google feature id, e.g. "0x89c25a197c06b7cb:0x40a06c78f79e5de6".` },
|
|
1292
|
+
place_id: { type: "string", minLength: 1, maxLength: 200, description: "The place's Google place ID." },
|
|
1293
|
+
sort_by: {
|
|
1294
|
+
type: "string",
|
|
1295
|
+
enum: ["mostRelevant", "newest", "highestRating", "lowestRating"],
|
|
1296
|
+
description: "The order: mostRelevant (Google's default), newest, highestRating or lowestRating."
|
|
1297
|
+
},
|
|
1298
|
+
topic_id: { type: "string", minLength: 1, maxLength: 200, description: "Only the reviews of one topic, from the topics of an earlier result." },
|
|
1299
|
+
gl: OPTIONS.gl,
|
|
1300
|
+
hl: OPTIONS.hl,
|
|
1301
|
+
cursor: CURSOR
|
|
1302
|
+
},
|
|
1303
|
+
additionalProperties: false
|
|
1304
|
+
},
|
|
1305
|
+
async run(args, h) {
|
|
1306
|
+
if (!args.cid && !args.fid && !args.place_id) {
|
|
1307
|
+
throw new ToolFailure("Give the place's cid, fid or place_id (maps_search and places_search return them). Nothing was sent to Serper.");
|
|
1308
|
+
}
|
|
1309
|
+
const state = h.cursor(args.cursor);
|
|
1310
|
+
const token = typeof state?.["n"] === "string" ? state["n"] : void 0;
|
|
1311
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1312
|
+
const data = await search(h, "/reviews", compact({
|
|
1313
|
+
cid: args.cid,
|
|
1314
|
+
fid: args.fid,
|
|
1315
|
+
placeId: args.place_id,
|
|
1316
|
+
sortBy: args.sort_by,
|
|
1317
|
+
topicId: args.topic_id,
|
|
1318
|
+
nextPageToken: token,
|
|
1319
|
+
gl: args.gl?.toLowerCase(),
|
|
1320
|
+
hl: args.hl?.toLowerCase()
|
|
1321
|
+
}));
|
|
1322
|
+
const topics = !token && skip === 0 ? listOf(data, "topics").slice(0, 20).map(trimTopic).filter(notEmpty) : [];
|
|
1323
|
+
const next = typeof data?.nextPageToken === "string" && data.nextPageToken ? data.nextPageToken : void 0;
|
|
1324
|
+
return h.page({
|
|
1325
|
+
key: "reviews",
|
|
1326
|
+
items: listOf(data, "reviews").map(trimReview).filter(notEmpty).slice(skip),
|
|
1327
|
+
extra: compact({ topics: topics.length ? topics : void 0, creditsUsed: num(data?.credits) }),
|
|
1328
|
+
resumeAt: (index) => h.makeCursor({ ...token ? { n: token } : {}, o: skip + index }),
|
|
1329
|
+
...next ? { nextPage: h.makeCursor({ n: next, o: 0 }) } : {}
|
|
1330
|
+
});
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
var autocomplete = {
|
|
1334
|
+
name: "autocomplete",
|
|
1335
|
+
kind: "read",
|
|
1336
|
+
title: "Get Google autocomplete suggestions via Serper",
|
|
1337
|
+
description: "The searches Google suggests as someone types a query, in Google's order: what people look for around a topic, for keyword and content research. Each call uses one Serper credit.",
|
|
1338
|
+
inputSchema: {
|
|
1339
|
+
type: "object",
|
|
1340
|
+
properties: { q: { ...QUERY, description: 'The start of a query, e.g. "best running shoes for".' }, gl: OPTIONS.gl, hl: OPTIONS.hl, location: OPTIONS.location },
|
|
1341
|
+
required: ["q"],
|
|
1342
|
+
additionalProperties: false
|
|
1343
|
+
},
|
|
1344
|
+
async run(args, h) {
|
|
1345
|
+
const data = await search(h, "/autocomplete", compact({ q: args.q, gl: args.gl?.toLowerCase(), hl: args.hl?.toLowerCase(), location: args.location }));
|
|
1346
|
+
const suggestions = listOf(data, "suggestions").map((item) => text(item["value"], 300)).filter((item) => item !== void 0);
|
|
1347
|
+
return compact({ query: args.q, suggestions, creditsUsed: num(data?.credits) });
|
|
1348
|
+
}
|
|
1349
|
+
};
|
|
1350
|
+
var lensSearch = {
|
|
1351
|
+
name: "lens_search",
|
|
1352
|
+
kind: "read",
|
|
1353
|
+
title: "Find an image on the web (Google Lens via Serper)",
|
|
1354
|
+
description: "Searches the web for an image by its public URL, as Google Lens does: pages and products that show it or look like it, with title, source, link, price and stock when Google has them. Serper downloads the image itself. Each call uses three Serper credits. Pass nextCursor back as cursor when the result was cut.",
|
|
1355
|
+
inputSchema: {
|
|
1356
|
+
type: "object",
|
|
1357
|
+
properties: {
|
|
1358
|
+
url: { type: "string", format: "uri", pattern: "^https?://", maxLength: 2e3, description: "The public http(s) URL of the image." },
|
|
1359
|
+
gl: OPTIONS.gl,
|
|
1360
|
+
hl: OPTIONS.hl,
|
|
1361
|
+
cursor: CURSOR
|
|
1362
|
+
},
|
|
1363
|
+
required: ["url"],
|
|
1364
|
+
additionalProperties: false
|
|
1365
|
+
},
|
|
1366
|
+
async run(args, h) {
|
|
1367
|
+
const { skip } = position(h, args);
|
|
1368
|
+
const data = await search(h, "/lens", compact({ url: args.url, gl: args.gl?.toLowerCase(), hl: args.hl?.toLowerCase() }));
|
|
1369
|
+
const matches = listOf(data, "organic").length ? listOf(data, "organic") : listOf(data, "visualMatches");
|
|
1370
|
+
return h.page({
|
|
1371
|
+
key: "matches",
|
|
1372
|
+
items: matches.map(trimLensMatch).filter(notEmpty).slice(skip),
|
|
1373
|
+
extra: compact({ creditsUsed: num(data?.credits) }),
|
|
1374
|
+
resumeAt: (index) => h.makeCursor({ o: skip + index })
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
};
|
|
1378
|
+
var findLocations = {
|
|
1379
|
+
name: "find_locations",
|
|
1380
|
+
kind: "read",
|
|
1381
|
+
title: "Find Serper location names",
|
|
1382
|
+
description: 'Looks up the place names the location option of the searches takes, e.g. "austin" gives "Austin,TX,Texas,United States": the canonical name to pass as location, with the country code and the kind of place (country, state, city, region). Free: it uses no Serper credits.',
|
|
1383
|
+
inputSchema: {
|
|
1384
|
+
type: "object",
|
|
1385
|
+
properties: {
|
|
1386
|
+
q: { type: "string", minLength: 1, maxLength: 100, description: 'A place name or its start, e.g. "austin" or "berlin".' },
|
|
1387
|
+
limit: { type: "integer", minimum: 1, maximum: 100, default: 10, description: "How many places to return, 1 to 100 (default 10)." }
|
|
1388
|
+
},
|
|
1389
|
+
required: ["q"],
|
|
1390
|
+
additionalProperties: false
|
|
1391
|
+
},
|
|
1392
|
+
async run(args, h) {
|
|
1393
|
+
const { data } = await h.api({ origin: LOCATIONS_ORIGIN, path: "/locations", query: { q: args.q, limit: args.limit }, auth: false });
|
|
1394
|
+
const locations = (Array.isArray(data) ? data : []).map((item) => trimLocation(typeof item === "object" && item !== null ? item : {})).filter(notEmpty);
|
|
1395
|
+
return { query: args.q, locations };
|
|
1396
|
+
}
|
|
1397
|
+
};
|
|
704
1398
|
var connector = defineConnector({
|
|
705
1399
|
vendor: "serper",
|
|
706
1400
|
label: "Serper",
|
|
707
|
-
origins: [
|
|
708
|
-
credentials: ["
|
|
709
|
-
credentialLabels: {
|
|
710
|
-
authHeaders: (credentials) => ({ "x-api-key": credentials["
|
|
1401
|
+
origins: [SEARCH_ORIGIN, LOCATIONS_ORIGIN],
|
|
1402
|
+
credentials: ["apikey"],
|
|
1403
|
+
credentialLabels: { apikey: "Serper API key" },
|
|
1404
|
+
authHeaders: (credentials) => ({ "x-api-key": credentials["apikey"] }),
|
|
711
1405
|
tools: [
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
title: "Search the
|
|
716
|
-
description: "Searches Google through Serper
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
1406
|
+
webSearch,
|
|
1407
|
+
listSearch({
|
|
1408
|
+
name: "news_search",
|
|
1409
|
+
title: "Search the news (Google News via Serper)",
|
|
1410
|
+
description: "Searches Google News through Serper: articles with title, link, snippet, source, date and image link, newest stories first when you set tbs. Each call uses one Serper credit. Pass nextCursor back as cursor for the next page.",
|
|
1411
|
+
path: "/news",
|
|
1412
|
+
listKey: "news",
|
|
1413
|
+
resultKey: "news",
|
|
1414
|
+
trim: trimNews,
|
|
1415
|
+
options: ["num", "gl", "hl", "location", "tbs", "autocorrect"],
|
|
1416
|
+
pageSize: 10
|
|
1417
|
+
}),
|
|
1418
|
+
listSearch({
|
|
1419
|
+
name: "image_search",
|
|
1420
|
+
title: "Search images (Google Images via Serper)",
|
|
1421
|
+
description: "Searches Google Images through Serper: each image with its URL, size, thumbnail, title and the page it is on, up to 100 a page. Each call uses one Serper credit, two when num is over 10. Pass nextCursor back as cursor for the next page.",
|
|
1422
|
+
path: "/images",
|
|
1423
|
+
listKey: "images",
|
|
1424
|
+
resultKey: "images",
|
|
1425
|
+
trim: trimImage,
|
|
1426
|
+
options: ["num", "gl", "hl", "location", "tbs", "autocorrect"],
|
|
1427
|
+
num: { type: "integer", minimum: 1, maximum: 100, default: 10, description: "Results per page, 1 to 100 (default 10). Serper counts more than 10 as two searches." },
|
|
1428
|
+
pageSize: 10
|
|
1429
|
+
}),
|
|
1430
|
+
listSearch({
|
|
1431
|
+
name: "video_search",
|
|
1432
|
+
title: "Search videos (Google Videos via Serper)",
|
|
1433
|
+
description: "Searches Google Videos through Serper: each video with title, link, snippet, duration, source, channel, date and thumbnail. Each call uses one Serper credit. Pass nextCursor back as cursor for the next page.",
|
|
1434
|
+
path: "/videos",
|
|
1435
|
+
listKey: "videos",
|
|
1436
|
+
resultKey: "videos",
|
|
1437
|
+
trim: trimVideo,
|
|
1438
|
+
options: ["num", "gl", "hl", "location", "tbs", "autocorrect"],
|
|
1439
|
+
pageSize: 10
|
|
1440
|
+
}),
|
|
1441
|
+
listSearch({
|
|
1442
|
+
name: "places_search",
|
|
1443
|
+
title: "Search local places (Google Places via Serper)",
|
|
1444
|
+
description: `Searches Google's local results through Serper, such as "coffee shops in Austin": each place with address, coordinates, rating and review count, category, phone, website and the cid that place_reviews takes. Each call uses one Serper credit. Pass nextCursor back as cursor for the next page.`,
|
|
1445
|
+
path: "/places",
|
|
1446
|
+
listKey: "places",
|
|
1447
|
+
resultKey: "places",
|
|
1448
|
+
trim: trimPlace,
|
|
1449
|
+
options: ["gl", "hl", "location"],
|
|
1450
|
+
pageSize: 10
|
|
1451
|
+
}),
|
|
1452
|
+
mapsSearch,
|
|
1453
|
+
placeReviews,
|
|
1454
|
+
listSearch({
|
|
1455
|
+
name: "shopping_search",
|
|
1456
|
+
title: "Search products (Google Shopping via Serper)",
|
|
1457
|
+
description: "Searches Google Shopping through Serper: products with price, shop, delivery, rating and review count, offers and link, up to 40 a page. Each call uses two Serper credits. Pass nextCursor back as cursor for the next page.",
|
|
1458
|
+
path: "/shopping",
|
|
1459
|
+
listKey: "shopping",
|
|
1460
|
+
resultKey: "products",
|
|
1461
|
+
trim: trimShopping,
|
|
1462
|
+
options: ["num", "gl", "hl", "location", "autocorrect"],
|
|
1463
|
+
num: { type: "integer", minimum: 1, maximum: 40, default: 40, description: "Results per page, 1 to 40 (default 40): a Google Shopping page holds up to 40." },
|
|
1464
|
+
pageSize: 40
|
|
1465
|
+
}),
|
|
1466
|
+
listSearch({
|
|
1467
|
+
name: "scholar_search",
|
|
1468
|
+
title: "Search papers (Google Scholar via Serper)",
|
|
1469
|
+
description: "Searches Google Scholar through Serper: papers with title, link, publication, snippet, year, citation count and PDF link. Each call uses one Serper credit. Pass nextCursor back as cursor for the next page.",
|
|
1470
|
+
path: "/scholar",
|
|
1471
|
+
listKey: "organic",
|
|
1472
|
+
resultKey: "papers",
|
|
1473
|
+
trim: trimScholar,
|
|
1474
|
+
options: ["gl", "hl", "location", "autocorrect"],
|
|
1475
|
+
pageSize: 10
|
|
1476
|
+
}),
|
|
1477
|
+
listSearch({
|
|
1478
|
+
name: "patent_search",
|
|
1479
|
+
title: "Search patents (Google Patents via Serper)",
|
|
1480
|
+
description: "Searches Google Patents through Serper: patents with title, snippet, publication number, priority, filing, grant and publication dates, inventor, assignee and PDF link. Each call uses one Serper credit. Pass nextCursor back as cursor for the next page.",
|
|
1481
|
+
path: "/patents",
|
|
1482
|
+
listKey: "organic",
|
|
1483
|
+
resultKey: "patents",
|
|
1484
|
+
trim: trimPatent,
|
|
1485
|
+
options: ["num"],
|
|
1486
|
+
pageSize: 10
|
|
1487
|
+
}),
|
|
1488
|
+
autocomplete,
|
|
1489
|
+
lensSearch,
|
|
1490
|
+
findLocations
|
|
769
1491
|
]
|
|
770
1492
|
});
|
|
771
1493
|
module.exports = connector;
|