@wiro-ai/wiro-agent-connectors 0.1.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.
@@ -0,0 +1,771 @@
1
+ /* serper connector module (MIT License). Built from src/vendors/serper; 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/text.ts
21
+ var encoder = new TextEncoder();
22
+ var decoder = new TextDecoder();
23
+ function utf8Bytes(text2) {
24
+ return encoder.encode(text2);
25
+ }
26
+ function utf8Length(text2) {
27
+ return encoder.encode(text2).length;
28
+ }
29
+ function utf8Decode(bytes) {
30
+ return decoder.decode(bytes);
31
+ }
32
+ function base64UrlEncode(bytes) {
33
+ let binary = "";
34
+ for (let i = 0; i < bytes.length; i += 32768) {
35
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
36
+ }
37
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
38
+ }
39
+ function base64UrlDecode(text2) {
40
+ if (!/^[A-Za-z0-9_-]*$/.test(text2)) throw new Error("not base64url");
41
+ const padded = text2.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text2.length + 3) % 4);
42
+ const binary = atob(padded);
43
+ const bytes = new Uint8Array(binary.length);
44
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
45
+ return bytes;
46
+ }
47
+ function truncate(text2, max) {
48
+ if (text2.length <= max) return text2;
49
+ const points = Array.from(text2);
50
+ if (points.length <= max) return text2;
51
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
52
+ }
53
+ function cleanVendorText(text2, max = 300) {
54
+ if (typeof text2 !== "string") return void 0;
55
+ if (/^\s*</.test(text2)) return void 0;
56
+ const line = text2.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
57
+ return line ? truncate(line, max) : void 0;
58
+ }
59
+ function formatNumber(value) {
60
+ return value.toLocaleString("en-US");
61
+ }
62
+
63
+ // src/core/http.ts
64
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
65
+ var USER_AGENT = "agent-connectors";
66
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
67
+ function errorCode(error) {
68
+ const code = error?.code;
69
+ return typeof code === "string" ? code : void 0;
70
+ }
71
+ function describe(error) {
72
+ const name2 = error?.name;
73
+ const code = errorCode(error);
74
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
75
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
76
+ if (code === "TOO_LARGE") return "the reply was too large";
77
+ return cleanVendorText(error?.message, 200) ?? "a network error";
78
+ }
79
+ function retryAfterSeconds(headers, now = Date.now()) {
80
+ const retryAfter = headers.get("retry-after");
81
+ if (retryAfter) {
82
+ const seconds = Number(retryAfter);
83
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
84
+ const date = Date.parse(retryAfter);
85
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
86
+ }
87
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
88
+ if (reset) {
89
+ const value = Number(reset);
90
+ if (Number.isFinite(value) && value >= 0) {
91
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
92
+ }
93
+ }
94
+ return void 0;
95
+ }
96
+ function vendorCode(data) {
97
+ if (typeof data !== "object" || data === null) return void 0;
98
+ for (const key of ["error", "code"]) {
99
+ const value = data[key];
100
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
101
+ }
102
+ return void 0;
103
+ }
104
+ function vendorMessage(data) {
105
+ if (typeof data === "string") return cleanVendorText(data);
106
+ if (typeof data !== "object" || data === null) return void 0;
107
+ const record = data;
108
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
109
+ const value = record[key];
110
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
111
+ const nested = value?.message;
112
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
113
+ }
114
+ if (Array.isArray(record["errors"])) {
115
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
116
+ if (messages.length) return cleanVendorText(messages.join("; "));
117
+ }
118
+ return void 0;
119
+ }
120
+ var TooLarge = class extends Error {
121
+ constructor(limit) {
122
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
123
+ this.limit = limit;
124
+ }
125
+ limit;
126
+ };
127
+ async function readCapped(response, maxBytes) {
128
+ const declared = Number(response.headers.get("content-length"));
129
+ if (Number.isFinite(declared) && declared > maxBytes) {
130
+ await response.body?.cancel().catch(() => {
131
+ });
132
+ throw new TooLarge(maxBytes);
133
+ }
134
+ if (!response.body) return new Uint8Array(0);
135
+ const reader = response.body.getReader();
136
+ const chunks = [];
137
+ let total = 0;
138
+ for (; ; ) {
139
+ const { done, value } = await reader.read();
140
+ if (done) break;
141
+ total += value.byteLength;
142
+ if (total > maxBytes) {
143
+ await reader.cancel().catch(() => {
144
+ });
145
+ throw new TooLarge(maxBytes);
146
+ }
147
+ chunks.push(value);
148
+ }
149
+ const bytes = new Uint8Array(total);
150
+ let offset = 0;
151
+ for (const chunk of chunks) {
152
+ bytes.set(chunk, offset);
153
+ offset += chunk.byteLength;
154
+ }
155
+ return bytes;
156
+ }
157
+ function parseBody(bytes, contentType) {
158
+ if (bytes.length === 0) return null;
159
+ const text2 = utf8Decode(bytes);
160
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text2)) {
161
+ try {
162
+ return JSON.parse(text2);
163
+ } catch {
164
+ }
165
+ }
166
+ return text2;
167
+ }
168
+ function createHttp(env) {
169
+ const { label, ctx } = env;
170
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
171
+ function failureFor(status, headers, data, request) {
172
+ const message = vendorMessage(data);
173
+ const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
174
+ const retryAfter = retryAfterSeconds(headers);
175
+ const code = vendorCode(data);
176
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
177
+ const custom = request.errors?.[status];
178
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
179
+ if (status >= 500) {
180
+ if (request.write) {
181
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
182
+ }
183
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
184
+ }
185
+ if (status === 429) {
186
+ return new ToolFailure(
187
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
188
+ { status, ...extra }
189
+ );
190
+ }
191
+ if (status === 401) {
192
+ return new ToolFailure(
193
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. Check that the ${env.credentialLabel} is correct and still active.${nothingChanged}`),
194
+ { status, ...extra }
195
+ );
196
+ }
197
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
198
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
199
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
200
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
201
+ }
202
+ async function api(request) {
203
+ const method = request.method ?? "GET";
204
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
205
+ throw new Error(`read-only tool sent ${method}`);
206
+ }
207
+ const origin = request.origin ?? env.origins[0];
208
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
209
+ const url = new URL(request.path, origin);
210
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
211
+ for (const [key, value] of Object.entries(request.query ?? {})) {
212
+ if (value !== void 0 && value !== null) url.searchParams.set(key, String(value));
213
+ }
214
+ const headers = {
215
+ accept: "application/json",
216
+ "user-agent": USER_AGENT,
217
+ ...request.auth === false ? {} : env.authHeaders(),
218
+ ...request.headers
219
+ };
220
+ let body;
221
+ if (request.json !== void 0) {
222
+ body = JSON.stringify(request.json);
223
+ headers["content-type"] = "application/json";
224
+ } else if (request.body) {
225
+ body = request.body;
226
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
227
+ }
228
+ const started = Date.now();
229
+ if (request.write) env.onWriteSent();
230
+ let response;
231
+ try {
232
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
233
+ } catch (error) {
234
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
235
+ if (errorCode(error) === "URL_REFUSED") {
236
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
237
+ }
238
+ if (request.write) {
239
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
240
+ }
241
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
242
+ }
243
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
244
+ let bytes;
245
+ try {
246
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
247
+ } catch (error) {
248
+ if (request.write && (response.ok || response.status >= 500)) {
249
+ 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.`);
250
+ }
251
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
252
+ }
253
+ const data = parseBody(bytes, response.headers.get("content-type"));
254
+ if (response.ok) return { status: response.status, headers: response.headers, data };
255
+ throw failureFor(response.status, response.headers, data, request);
256
+ }
257
+ async function media(rawUrl, options) {
258
+ const { what } = options;
259
+ let url;
260
+ try {
261
+ url = new URL(rawUrl);
262
+ } catch {
263
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
264
+ }
265
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
266
+ const started = Date.now();
267
+ let response;
268
+ try {
269
+ response = await ctx.fetch(url.toString(), {
270
+ method: "GET",
271
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
272
+ ...ctx.signal ? { signal: ctx.signal } : {}
273
+ });
274
+ } catch (error) {
275
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
276
+ if (errorCode(error) === "URL_REFUSED") {
277
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
278
+ }
279
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
280
+ }
281
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
282
+ if (!response.ok) {
283
+ await response.body?.cancel().catch(() => {
284
+ });
285
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
286
+ }
287
+ try {
288
+ const bytes = await readCapped(response, options.maxBytes);
289
+ return { bytes, contentType: response.headers.get("content-type") };
290
+ } catch (error) {
291
+ if (error instanceof TooLarge) {
292
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
293
+ }
294
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
295
+ }
296
+ }
297
+ return { api, media };
298
+ }
299
+
300
+ // src/core/output.ts
301
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
302
+ function jsonSize(value) {
303
+ return utf8Length(JSON.stringify(value) ?? "");
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;
352
+ try {
353
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
354
+ if (typeof state === "object" && state !== null && state.t === tool) {
355
+ return state;
356
+ }
357
+ } catch {
358
+ }
359
+ throw new ToolFailure(
360
+ "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."
361
+ );
362
+ }
363
+
364
+ // src/core/schema.ts
365
+ var patterns = /* @__PURE__ */ new Map();
366
+ function patternOf(source) {
367
+ let compiled = patterns.get(source);
368
+ if (!compiled) {
369
+ compiled = new RegExp(source, "u");
370
+ patterns.set(source, compiled);
371
+ }
372
+ return compiled;
373
+ }
374
+ function isPlainObject(value) {
375
+ return typeof value === "object" && value !== null && !Array.isArray(value);
376
+ }
377
+ function isHttpUrl(value) {
378
+ try {
379
+ const url = new URL(value);
380
+ return url.protocol === "https:" || url.protocol === "http:";
381
+ } catch {
382
+ return false;
383
+ }
384
+ }
385
+ function name(path) {
386
+ return `\`${path}\``;
387
+ }
388
+ function child(path, key) {
389
+ return path ? `${path}.${key}` : key;
390
+ }
391
+ function checkValue(schema, value, path, issues) {
392
+ switch (schema.type) {
393
+ case "object":
394
+ checkObject(schema, value, path, issues);
395
+ return;
396
+ case "array": {
397
+ if (!Array.isArray(value)) {
398
+ issues.push(`${name(path)} must be an array`);
399
+ return;
400
+ }
401
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
402
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
403
+ }
404
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
405
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
406
+ }
407
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
408
+ issues.push(`${name(path)} must not repeat an item`);
409
+ }
410
+ if (schema.items) {
411
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
412
+ }
413
+ break;
414
+ }
415
+ case "string": {
416
+ if (typeof value !== "string") {
417
+ issues.push(`${name(path)} must be a string`);
418
+ return;
419
+ }
420
+ const length = Array.from(value).length;
421
+ if (schema.minLength !== void 0 && length < schema.minLength) {
422
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
423
+ }
424
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
425
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
426
+ }
427
+ if (schema.format === "uri" && !isHttpUrl(value)) {
428
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
429
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
430
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
431
+ }
432
+ break;
433
+ }
434
+ case "integer":
435
+ case "number": {
436
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
437
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
438
+ return;
439
+ }
440
+ if (schema.minimum !== void 0 && value < schema.minimum) {
441
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
442
+ }
443
+ if (schema.maximum !== void 0 && value > schema.maximum) {
444
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
445
+ }
446
+ break;
447
+ }
448
+ case "boolean":
449
+ if (typeof value !== "boolean") {
450
+ issues.push(`${name(path)} must be true or false`);
451
+ return;
452
+ }
453
+ break;
454
+ default:
455
+ break;
456
+ }
457
+ if (schema.enum && !schema.enum.includes(value)) {
458
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
459
+ }
460
+ }
461
+ function checkObject(schema, value, path, issues) {
462
+ if (!isPlainObject(value)) {
463
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
464
+ return;
465
+ }
466
+ const properties = schema.properties ?? {};
467
+ for (const key of schema.required ?? []) {
468
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
469
+ }
470
+ const unknown = [];
471
+ for (const [key, item] of Object.entries(value)) {
472
+ const property = properties[key];
473
+ if (!property) {
474
+ if (schema.additionalProperties === false) unknown.push(key);
475
+ continue;
476
+ }
477
+ if (item === void 0 || item === null) continue;
478
+ checkValue(property, item, child(path, key), issues);
479
+ }
480
+ if (unknown.length) {
481
+ const known = Object.keys(properties);
482
+ 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(", ")})` : ""));
483
+ }
484
+ }
485
+ function copyDefault(value) {
486
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
487
+ }
488
+ function validateArguments(schema, args) {
489
+ const input = args === void 0 || args === null ? {} : args;
490
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
491
+ const value = { ...input };
492
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
493
+ const issues = [];
494
+ checkObject(schema, value, "", issues);
495
+ if (issues.length) return { ok: false, issues };
496
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
497
+ if (value[key] === null) delete value[key];
498
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
499
+ }
500
+ return { ok: true, value };
501
+ }
502
+
503
+ // src/core/connector.ts
504
+ var ANNOTATIONS = {
505
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
506
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
507
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
508
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true }
509
+ };
510
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
511
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
512
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
513
+ function deepFreeze(value) {
514
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
515
+ Object.freeze(value);
516
+ for (const item of Object.values(value)) deepFreeze(item);
517
+ }
518
+ return value;
519
+ }
520
+ function assertDefinition(def) {
521
+ const problem = (message) => {
522
+ throw new Error(`connector "${def.vendor}": ${message}`);
523
+ };
524
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
525
+ if (!def.label?.trim()) problem("label is required");
526
+ if (!def.origins.length) problem("at least one origin is required");
527
+ for (const origin of def.origins) {
528
+ let url;
529
+ try {
530
+ url = new URL(origin);
531
+ } catch {
532
+ }
533
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
534
+ }
535
+ for (const name2 of def.credentials) {
536
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
537
+ }
538
+ const names = /* @__PURE__ */ new Set();
539
+ for (const tool of def.tools) {
540
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
541
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
542
+ names.add(tool.name);
543
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
544
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
545
+ if (!(tool.kind in ANNOTATIONS)) problem(`tool ${tool.name} has an unknown kind`);
546
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
547
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
548
+ }
549
+ }
550
+ for (const tool of def.tools) {
551
+ if (tool.kind === "read") continue;
552
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
553
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
554
+ }
555
+ }
556
+ function result(payload, isError) {
557
+ return { content: [{ type: "text", text: JSON.stringify(payload) }], ...isError ? { isError: true } : {} };
558
+ }
559
+ function failure(message, details = {}) {
560
+ return result({ error: message, ...details }, true);
561
+ }
562
+ function trimmed(values) {
563
+ const out = {};
564
+ if (typeof values !== "object" || values === null) return out;
565
+ for (const [key, value] of Object.entries(values)) {
566
+ if (value === void 0 || value === null) continue;
567
+ const text2 = String(value).trim();
568
+ if (text2) out[key] = text2;
569
+ }
570
+ return out;
571
+ }
572
+ function defineConnector(def) {
573
+ assertDefinition(def);
574
+ const { label } = def;
575
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
576
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
577
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
578
+ const descriptors = def.tools.map((tool) => ({
579
+ name: tool.name,
580
+ title: tool.title,
581
+ description: tool.description,
582
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
583
+ annotations: { ...ANNOTATIONS[tool.kind] }
584
+ }));
585
+ async function call(toolName, args, ctx) {
586
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
587
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
588
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
589
+ const log = (text2) => {
590
+ try {
591
+ ctx.log?.(text2);
592
+ } catch {
593
+ }
594
+ };
595
+ let credentials = trimmed(ctx.credentials);
596
+ if (def.normalizeCredentials) credentials = def.normalizeCredentials(credentials);
597
+ const missing = def.credentials.filter((name2) => !credentials[name2]);
598
+ if (missing.length) {
599
+ return failure(`${label} is not connected: the ${missing.map(credentialLabel).join(" and ")} ${missing.length > 1 ? "are" : "is"} missing.`);
600
+ }
601
+ const parsed = validateArguments(tool.inputSchema, args);
602
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
603
+ const frozenCredentials = Object.freeze({ ...credentials });
604
+ let writeSent = false;
605
+ const http = createHttp({
606
+ vendor: def.vendor,
607
+ label,
608
+ tool: tool.name,
609
+ readOnly: tool.kind === "read",
610
+ origins: def.origins,
611
+ credentialLabel: def.credentials.map(credentialLabel).join(" and "),
612
+ ctx,
613
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
614
+ log,
615
+ onWriteSent: () => {
616
+ writeSent = true;
617
+ }
618
+ });
619
+ const helpers = {
620
+ tool: tool.name,
621
+ credentials: frozenCredentials,
622
+ ctx,
623
+ api: http.api,
624
+ media: http.media,
625
+ page: (input) => fitPage(input),
626
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
627
+ makeCursor: (state) => encodeCursor(tool.name, state),
628
+ log
629
+ };
630
+ try {
631
+ const data = await tool.run(parsed.value, helpers);
632
+ const fitted = shrinkToFit(data ?? {});
633
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
634
+ const payload = fitted.value;
635
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false);
636
+ } catch (error) {
637
+ if (error instanceof OutcomeUnknown) {
638
+ return result({
639
+ outcome: "unknown",
640
+ check: tool.check,
641
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
642
+ }, true);
643
+ }
644
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
645
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
646
+ if (writeSent) {
647
+ return result({
648
+ outcome: "unknown",
649
+ check: tool.check,
650
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
651
+ }, true);
652
+ }
653
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
654
+ }
655
+ }
656
+ return deepFreeze({
657
+ vendor: def.vendor,
658
+ origins: [...def.origins],
659
+ credentials: [...def.credentials],
660
+ tools: descriptors,
661
+ call
662
+ });
663
+ }
664
+
665
+ // src/vendors/serper/index.ts
666
+ var MAX_PAGE = 10;
667
+ function text(value, max) {
668
+ return typeof value === "string" && value.trim() ? truncate(value.trim(), max) : void 0;
669
+ }
670
+ function compact(value) {
671
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
672
+ }
673
+ function trimOrganic(item) {
674
+ return compact({
675
+ position: typeof item.position === "number" ? item.position : void 0,
676
+ title: text(item.title, 300),
677
+ link: text(item.link, 2e3),
678
+ snippet: text(item.snippet, 600),
679
+ date: text(item.date, 40)
680
+ });
681
+ }
682
+ function trimAnswerBox(box) {
683
+ if (!box || typeof box !== "object") return void 0;
684
+ const trimmedBox = compact({
685
+ title: text(box.title, 300),
686
+ answer: text(box.answer, 600),
687
+ snippet: text(box.snippet, 1e3),
688
+ link: text(box.link, 2e3)
689
+ });
690
+ return Object.keys(trimmedBox).length ? trimmedBox : void 0;
691
+ }
692
+ function trimKnowledgeGraph(graph) {
693
+ if (!graph || typeof graph !== "object") return void 0;
694
+ const attributes = graph.attributes && typeof graph.attributes === "object" ? Object.fromEntries(Object.entries(graph.attributes).slice(0, 12).map(([key, value]) => [truncate(key, 80), text(value, 200) ?? ""])) : void 0;
695
+ const trimmedGraph = compact({
696
+ title: text(graph.title, 300),
697
+ type: text(graph.type, 120),
698
+ description: text(graph.description, 1e3),
699
+ website: text(graph.website, 2e3),
700
+ attributes
701
+ });
702
+ return Object.keys(trimmedGraph).length ? trimmedGraph : void 0;
703
+ }
704
+ var connector = defineConnector({
705
+ vendor: "serper",
706
+ label: "Serper",
707
+ origins: ["https://google.serper.dev"],
708
+ credentials: ["api_key"],
709
+ credentialLabels: { api_key: "Serper API key" },
710
+ authHeaders: (credentials) => ({ "x-api-key": credentials["api_key"] }),
711
+ tools: [
712
+ {
713
+ name: "web_search",
714
+ kind: "read",
715
+ title: "Search the web (Google results via Serper)",
716
+ 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. Read the pages themselves with a fetch tool. Each call uses one Serper search credit, two when num is over 10. Pass nextCursor back as cursor for the next page.",
717
+ inputSchema: {
718
+ type: "object",
719
+ properties: {
720
+ q: { type: "string", minLength: 1, maxLength: 2048, description: "The search query, as you would type it into Google." },
721
+ num: { type: "integer", minimum: 1, maximum: 20, default: 10, description: "Results per page, 1 to 20 (default 10)." },
722
+ gl: { type: "string", pattern: "^[a-z]{2}$", description: 'Two-letter country code to search from, e.g. "us" or "de".' },
723
+ hl: { type: "string", pattern: "^[a-z]{2,3}(-[a-z]{2,4})?$", description: 'Interface language code, e.g. "en" or "pt-br".' },
724
+ tbs: {
725
+ type: "string",
726
+ enum: ["qdr:h", "qdr:d", "qdr:w", "qdr:m", "qdr:y"],
727
+ description: "Only results from the past hour (qdr:h), day (qdr:d), week (qdr:w), month (qdr:m) or year (qdr:y)."
728
+ },
729
+ autocorrect: { type: "boolean", description: "Let Google correct the spelling of the query (default true)." },
730
+ cursor: { type: "string", description: "nextCursor from the previous result, for the next page." }
731
+ },
732
+ required: ["q"],
733
+ additionalProperties: false
734
+ },
735
+ async run(args, h) {
736
+ const state = h.cursor(args.cursor);
737
+ const page = typeof state?.["p"] === "number" ? state["p"] : 1;
738
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
739
+ const { data } = await h.api({
740
+ method: "POST",
741
+ path: "/search",
742
+ json: compact({ q: args.q, num: args.num, page, gl: args.gl, hl: args.hl, tbs: args.tbs, autocorrect: args.autocorrect }),
743
+ // A search changes nothing: POST is only how Serper takes the query.
744
+ safe: true,
745
+ errors: {
746
+ 400: "Serper could not run this search: check the query and the options.",
747
+ 403: "Serper refused the API key: it may be wrong, disabled, or out of credits."
748
+ }
749
+ });
750
+ const organic = Array.isArray(data?.organic) ? data.organic : [];
751
+ const results = organic.map(trimOrganic).slice(skip);
752
+ const firstPage = page === 1 && skip === 0;
753
+ return h.page({
754
+ key: "results",
755
+ items: results,
756
+ extra: compact({
757
+ query: args.q,
758
+ page,
759
+ answerBox: firstPage ? trimAnswerBox(data?.answerBox) : void 0,
760
+ knowledgeGraph: firstPage ? trimKnowledgeGraph(data?.knowledgeGraph) : void 0,
761
+ peopleAlsoAsk: firstPage && Array.isArray(data?.peopleAlsoAsk) ? 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,
762
+ relatedSearches: firstPage && Array.isArray(data?.relatedSearches) ? data.relatedSearches.slice(0, 8).map((item) => text(item?.query, 200)).filter(Boolean) : void 0
763
+ }),
764
+ resumeAt: (index) => h.makeCursor({ p: page, o: skip + index }),
765
+ ...organic.length >= args.num && page < MAX_PAGE ? { nextPage: h.makeCursor({ p: page + 1, o: 0 }) } : {}
766
+ });
767
+ }
768
+ }
769
+ ]
770
+ });
771
+ module.exports = connector;