@busca-agentes/core 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Busca para Agentes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,458 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ACCEPT_QUERY: () => ACCEPT_QUERY,
24
+ ALLOW_METHODS: () => ALLOW_METHODS,
25
+ DEFAULT_CHUNK_OVERLAP_RATIO: () => DEFAULT_CHUNK_OVERLAP_RATIO,
26
+ DEFAULT_CHUNK_TOKENS: () => DEFAULT_CHUNK_TOKENS,
27
+ DEFAULT_DOCUMENTATION: () => DEFAULT_DOCUMENTATION,
28
+ DEFAULT_EMBEDDING_DIMENSION: () => DEFAULT_EMBEDDING_DIMENSION,
29
+ DEFAULT_INSTRUCTIONS: () => DEFAULT_INSTRUCTIONS,
30
+ DEFAULT_MATCH_THRESHOLD: () => DEFAULT_MATCH_THRESHOLD,
31
+ DEFAULT_MAX_RESULTS: () => DEFAULT_MAX_RESULTS,
32
+ FREE_QUERIES_PER_MONTH: () => FREE_QUERIES_PER_MONTH,
33
+ MARKDOWN_CONTENT_TYPE: () => MARKDOWN_CONTENT_TYPE,
34
+ MISSING_QUERY_BODY: () => MISSING_QUERY_BODY,
35
+ PLAIN_CONTENT_TYPE: () => PLAIN_CONTENT_TYPE,
36
+ PREPAID_USD_PER_1000: () => PREPAID_USD_PER_1000,
37
+ RRF_K: () => RRF_K,
38
+ SEARCH_PATH: () => SEARCH_PATH,
39
+ agentDiscovery: () => agentDiscovery,
40
+ agentMetaTags: () => agentMetaTags,
41
+ agentYamlFrontMatter: () => agentYamlFrontMatter,
42
+ createMemoryQuotaStore: () => createMemoryQuotaStore,
43
+ decideQuota: () => decideQuota,
44
+ emptyHead: () => emptyHead,
45
+ formatSearchMarkdown: () => formatSearchMarkdown,
46
+ handleSearchRequest: () => handleSearchRequest,
47
+ markdownResponse: () => markdownResponse,
48
+ methodNotAllowed: () => methodNotAllowed,
49
+ monthKey: () => monthKey,
50
+ normalizeScores: () => normalizeScores,
51
+ parseSearchMarkdown: () => parseSearchMarkdown,
52
+ parseSearchQuery: () => parseSearchQuery,
53
+ plainResponse: () => plainResponse,
54
+ prepaidQueriesForUsd: () => prepaidQueriesForUsd,
55
+ quotaExceededResponse: () => quotaExceededResponse,
56
+ reciprocalRankFusion: () => reciprocalRankFusion,
57
+ searchResponseHeaders: () => searchResponseHeaders,
58
+ usdForPrepaidQueries: () => usdForPrepaidQueries
59
+ });
60
+ module.exports = __toCommonJS(index_exports);
61
+
62
+ // src/types.ts
63
+ var SEARCH_PATH = "/.well-known/search";
64
+ var DEFAULT_INSTRUCTIONS = "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown.";
65
+ var DEFAULT_DOCUMENTATION = "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/";
66
+ var FREE_QUERIES_PER_MONTH = 1e3;
67
+ var PREPAID_USD_PER_1000 = 0.75;
68
+ var DEFAULT_MAX_RESULTS = 10;
69
+ var DEFAULT_MATCH_THRESHOLD = 0.4;
70
+ var DEFAULT_CHUNK_TOKENS = 1024;
71
+ var DEFAULT_CHUNK_OVERLAP_RATIO = 0.1;
72
+ var RRF_K = 60;
73
+ var DEFAULT_EMBEDDING_DIMENSION = 1536;
74
+ var ALLOW_METHODS = "GET, HEAD, QUERY";
75
+ var ACCEPT_QUERY = "text/plain, application/json";
76
+ var MARKDOWN_CONTENT_TYPE = "text/markdown; charset=utf-8";
77
+ var PLAIN_CONTENT_TYPE = "text/plain; charset=utf-8";
78
+ var MISSING_QUERY_BODY = "Missing query parameter: ?q=";
79
+
80
+ // src/markdown.ts
81
+ function formatSearchMarkdown(query, hits) {
82
+ const header = `# Search results for: ${JSON.stringify(query)}`;
83
+ if (hits.length === 0) {
84
+ return `${header}
85
+ `;
86
+ }
87
+ const blocks = hits.map((hit) => {
88
+ const score = Number.isFinite(hit.score) ? hit.score : 0;
89
+ const heading = `## ${hit.source} (score: ${score.toFixed(3)})`;
90
+ const body = hit.content.trim();
91
+ return `${heading}
92
+
93
+ ${body}`;
94
+ });
95
+ return `${header}
96
+
97
+ ${blocks.join("\n\n---\n\n")}
98
+ `;
99
+ }
100
+ function normalizeScores(hits) {
101
+ if (hits.length === 0) return hits;
102
+ const max = Math.max(...hits.map((h) => h.score));
103
+ if (max <= 0) {
104
+ return hits.map((h, i) => ({
105
+ ...h,
106
+ score: i === 0 ? 1 : 0
107
+ }));
108
+ }
109
+ return hits.map((h) => ({ ...h, score: h.score / max }));
110
+ }
111
+ function parseSearchMarkdown(markdown) {
112
+ const queryMatch = markdown.match(/^# Search results for: (.*)$/m);
113
+ if (!queryMatch) {
114
+ throw new Error("Not a Search for Agents markdown document");
115
+ }
116
+ let query = queryMatch[1].trim();
117
+ try {
118
+ query = JSON.parse(query);
119
+ } catch {
120
+ if (query.startsWith('"') && query.endsWith('"') || query.startsWith("'") && query.endsWith("'")) {
121
+ query = query.slice(1, -1);
122
+ }
123
+ }
124
+ const rest = markdown.slice(queryMatch.index + queryMatch[0].length).trim();
125
+ if (!rest) return { query, hits: [] };
126
+ const chunks = rest.split(/\n---\n/);
127
+ const hits = chunks.map((chunk) => chunk.trim()).filter(Boolean).map((chunk) => {
128
+ const heading = chunk.match(
129
+ /^## (.+) \(score: ([0-9]+(?:\.[0-9]+)?)\)$/m
130
+ );
131
+ if (!heading) {
132
+ throw new Error(`Invalid result heading in: ${chunk.slice(0, 80)}`);
133
+ }
134
+ const content = chunk.slice(heading[0].length).trim();
135
+ return {
136
+ source: heading[1],
137
+ score: Number(heading[2]),
138
+ content
139
+ };
140
+ });
141
+ return { query, hits };
142
+ }
143
+
144
+ // src/query.ts
145
+ function isJsonContentType(value) {
146
+ if (!value) return false;
147
+ return value.toLowerCase().includes("application/json");
148
+ }
149
+ function isPlainText(value) {
150
+ if (!value) return true;
151
+ const v = value.toLowerCase();
152
+ return v.includes("text/plain") || v.includes("text/markdown") || v.includes("application/x-www-form-urlencoded");
153
+ }
154
+ async function parseSearchQuery(request) {
155
+ const method = request.method.toUpperCase();
156
+ const url = new URL(request.url);
157
+ const headerQ = request.headers.get("x-agent-search-q");
158
+ if (method === "GET" || method === "HEAD") {
159
+ const q = (headerQ ?? url.searchParams.get("q") ?? "").trim();
160
+ if (!q) {
161
+ return {
162
+ ok: false,
163
+ status: 400,
164
+ body: MISSING_QUERY_BODY,
165
+ contentType: "text/plain; charset=utf-8"
166
+ };
167
+ }
168
+ return { ok: true, q, method: method === "HEAD" ? "HEAD" : "GET" };
169
+ }
170
+ if (method === "QUERY") {
171
+ const contentType = request.headers.get("content-type");
172
+ let q = "";
173
+ try {
174
+ if (isJsonContentType(contentType)) {
175
+ const json = await request.json();
176
+ q = typeof json?.q === "string" ? json.q : "";
177
+ } else if (isPlainText(contentType)) {
178
+ const raw = await request.text();
179
+ if (contentType && contentType.toLowerCase().includes("application/x-www-form-urlencoded")) {
180
+ const params = new URLSearchParams(raw);
181
+ q = (params.get("q") ?? raw).trim();
182
+ } else {
183
+ q = raw.trim();
184
+ }
185
+ } else {
186
+ return {
187
+ ok: false,
188
+ status: 415,
189
+ body: "Unsupported QUERY content type. Use text/plain or application/json.",
190
+ contentType: "text/plain; charset=utf-8"
191
+ };
192
+ }
193
+ } catch {
194
+ return {
195
+ ok: false,
196
+ status: 400,
197
+ body: MISSING_QUERY_BODY,
198
+ contentType: "text/plain; charset=utf-8"
199
+ };
200
+ }
201
+ q = q.trim();
202
+ if (!q) {
203
+ return {
204
+ ok: false,
205
+ status: 400,
206
+ body: MISSING_QUERY_BODY,
207
+ contentType: "text/plain; charset=utf-8"
208
+ };
209
+ }
210
+ return { ok: true, q, method: "QUERY" };
211
+ }
212
+ return {
213
+ ok: false,
214
+ status: 405,
215
+ body: "Method Not Allowed",
216
+ contentType: "text/plain; charset=utf-8"
217
+ };
218
+ }
219
+
220
+ // src/headers.ts
221
+ function searchResponseHeaders(extra) {
222
+ const headers = new Headers({
223
+ Allow: ALLOW_METHODS,
224
+ "Accept-Query": ACCEPT_QUERY,
225
+ "X-Content-Type-Options": "nosniff",
226
+ ...extra
227
+ });
228
+ return headers;
229
+ }
230
+ function markdownResponse(body, status = 200) {
231
+ return new Response(body, {
232
+ status,
233
+ headers: searchResponseHeaders({
234
+ "Content-Type": MARKDOWN_CONTENT_TYPE
235
+ })
236
+ });
237
+ }
238
+ function plainResponse(body, status) {
239
+ return new Response(body, {
240
+ status,
241
+ headers: searchResponseHeaders({
242
+ "Content-Type": PLAIN_CONTENT_TYPE
243
+ })
244
+ });
245
+ }
246
+ function emptyHead(status, markdown) {
247
+ return new Response(null, {
248
+ status,
249
+ headers: searchResponseHeaders({
250
+ "Content-Type": markdown ? MARKDOWN_CONTENT_TYPE : PLAIN_CONTENT_TYPE
251
+ })
252
+ });
253
+ }
254
+ function methodNotAllowed() {
255
+ return plainResponse("Method Not Allowed", 405);
256
+ }
257
+ function quotaExceededResponse() {
258
+ return plainResponse(
259
+ "Query quota exceeded. This site has used its included 1000 queries this month and has no prepaid credit.",
260
+ 429
261
+ );
262
+ }
263
+
264
+ // src/quota.ts
265
+ function monthKey(date = /* @__PURE__ */ new Date()) {
266
+ const year = date.getUTCFullYear();
267
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
268
+ return `${year}-${month}`;
269
+ }
270
+ function decideQuota(input) {
271
+ const freeLimit = input.freeLimit ?? FREE_QUERIES_PER_MONTH;
272
+ if (input.usedFree < freeLimit) {
273
+ return { ok: true, bucket: "free" };
274
+ }
275
+ if (input.credits > 0) {
276
+ return { ok: true, bucket: "credit" };
277
+ }
278
+ return {
279
+ ok: false,
280
+ reason: "exhausted",
281
+ usedFree: input.usedFree,
282
+ credits: input.credits,
283
+ freeLimit
284
+ };
285
+ }
286
+ function prepaidQueriesForUsd(usd) {
287
+ return Math.round(usd / 0.75 * 1e3);
288
+ }
289
+ function usdForPrepaidQueries(queries) {
290
+ return queries / 1e3 * 0.75;
291
+ }
292
+ function createMemoryQuotaStore(options) {
293
+ const freeLimit = options?.freeLimit ?? FREE_QUERIES_PER_MONTH;
294
+ const used = /* @__PURE__ */ new Map();
295
+ const credits = new Map(
296
+ Object.entries(options?.creditsBySite ?? {})
297
+ );
298
+ const currentMonth = () => monthKey();
299
+ return {
300
+ async consume(siteId) {
301
+ const key = `${siteId}:${currentMonth()}`;
302
+ const usedFree = used.get(key) ?? 0;
303
+ const remainingCredits = credits.get(siteId) ?? 0;
304
+ const decision = decideQuota({
305
+ usedFree,
306
+ credits: remainingCredits,
307
+ freeLimit
308
+ });
309
+ if (!decision.ok) return decision;
310
+ if (decision.bucket === "free") {
311
+ used.set(key, usedFree + 1);
312
+ } else {
313
+ credits.set(siteId, remainingCredits - 1);
314
+ }
315
+ return decision;
316
+ },
317
+ snapshot(siteId) {
318
+ return {
319
+ usedFree: used.get(`${siteId}:${currentMonth()}`) ?? 0,
320
+ credits: credits.get(siteId) ?? 0,
321
+ month: currentMonth()
322
+ };
323
+ }
324
+ };
325
+ }
326
+
327
+ // src/rrf.ts
328
+ function reciprocalRankFusion(rankedLists, k = RRF_K) {
329
+ const scores = /* @__PURE__ */ new Map();
330
+ for (const list of rankedLists) {
331
+ list.forEach((hit, index) => {
332
+ const key = hit.source;
333
+ const add = 1 / (k + index + 1);
334
+ const current = scores.get(key);
335
+ if (current) {
336
+ current.score += add;
337
+ if (hit.content.length > current.hit.content.length) {
338
+ current.hit = hit;
339
+ }
340
+ } else {
341
+ scores.set(key, { hit, score: add });
342
+ }
343
+ });
344
+ }
345
+ const fused = [...scores.values()].sort((a, b) => b.score - a.score).map(({ hit, score }) => ({ ...hit, score }));
346
+ return normalizeScores(fused);
347
+ }
348
+
349
+ // src/handler.ts
350
+ async function handleSearchRequest(request, options) {
351
+ const method = request.method.toUpperCase();
352
+ if (method === "OPTIONS") {
353
+ return new Response(null, {
354
+ status: 204,
355
+ headers: searchResponseHeaders()
356
+ });
357
+ }
358
+ if (!["GET", "HEAD", "QUERY"].includes(method)) {
359
+ return methodNotAllowed();
360
+ }
361
+ const parsed = await parseSearchQuery(request);
362
+ if (!parsed.ok) {
363
+ if (method === "HEAD") {
364
+ return emptyHead(parsed.status, false);
365
+ }
366
+ return plainResponse(parsed.body, parsed.status);
367
+ }
368
+ if (options.quota && options.siteId) {
369
+ const quota = await options.quota.consume(options.siteId);
370
+ if (!quota.ok) {
371
+ if (method === "HEAD") return emptyHead(429, false);
372
+ return quotaExceededResponse();
373
+ }
374
+ }
375
+ const hits = await options.backend.search(parsed.q, {
376
+ limit: options.maxResults ?? DEFAULT_MAX_RESULTS,
377
+ threshold: options.matchThreshold ?? DEFAULT_MATCH_THRESHOLD
378
+ });
379
+ const body = formatSearchMarkdown(parsed.q, hits);
380
+ if (method === "HEAD") {
381
+ return emptyHead(200, true);
382
+ }
383
+ return markdownResponse(body, 200);
384
+ }
385
+
386
+ // src/discovery.ts
387
+ function agentDiscovery(options) {
388
+ const origin = options.origin.replace(/\/$/, "");
389
+ return {
390
+ instructions: options.instructions ?? DEFAULT_INSTRUCTIONS,
391
+ endpoint: `${origin}${SEARCH_PATH}?q={query}`,
392
+ method: "GET",
393
+ documentation: options.documentation ?? DEFAULT_DOCUMENTATION
394
+ };
395
+ }
396
+ function agentMetaTags(discovery) {
397
+ return [
398
+ `<meta name="agent:instructions" content="${escapeAttr(discovery.instructions)}" />`,
399
+ `<meta name="agent:endpoint" content="${escapeAttr(discovery.endpoint)}" />`,
400
+ `<meta name="agent:method" content="${escapeAttr(discovery.method)}" />`,
401
+ `<meta name="agent:documentation" content="${escapeAttr(discovery.documentation)}" />`
402
+ ].join("\n");
403
+ }
404
+ function agentYamlFrontMatter(discovery) {
405
+ return [
406
+ "---",
407
+ "agent:",
408
+ ` instructions: ${JSON.stringify(discovery.instructions)}`,
409
+ ` endpoint: ${JSON.stringify(discovery.endpoint)}`,
410
+ ` method: ${JSON.stringify(discovery.method)}`,
411
+ ` documentation: ${JSON.stringify(discovery.documentation)}`,
412
+ "---",
413
+ ""
414
+ ].join("\n");
415
+ }
416
+ function escapeAttr(value) {
417
+ return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
418
+ }
419
+ // Annotate the CommonJS export names for ESM import in node:
420
+ 0 && (module.exports = {
421
+ ACCEPT_QUERY,
422
+ ALLOW_METHODS,
423
+ DEFAULT_CHUNK_OVERLAP_RATIO,
424
+ DEFAULT_CHUNK_TOKENS,
425
+ DEFAULT_DOCUMENTATION,
426
+ DEFAULT_EMBEDDING_DIMENSION,
427
+ DEFAULT_INSTRUCTIONS,
428
+ DEFAULT_MATCH_THRESHOLD,
429
+ DEFAULT_MAX_RESULTS,
430
+ FREE_QUERIES_PER_MONTH,
431
+ MARKDOWN_CONTENT_TYPE,
432
+ MISSING_QUERY_BODY,
433
+ PLAIN_CONTENT_TYPE,
434
+ PREPAID_USD_PER_1000,
435
+ RRF_K,
436
+ SEARCH_PATH,
437
+ agentDiscovery,
438
+ agentMetaTags,
439
+ agentYamlFrontMatter,
440
+ createMemoryQuotaStore,
441
+ decideQuota,
442
+ emptyHead,
443
+ formatSearchMarkdown,
444
+ handleSearchRequest,
445
+ markdownResponse,
446
+ methodNotAllowed,
447
+ monthKey,
448
+ normalizeScores,
449
+ parseSearchMarkdown,
450
+ parseSearchQuery,
451
+ plainResponse,
452
+ prepaidQueriesForUsd,
453
+ quotaExceededResponse,
454
+ reciprocalRankFusion,
455
+ searchResponseHeaders,
456
+ usdForPrepaidQueries
457
+ });
458
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/markdown.ts","../src/query.ts","../src/headers.ts","../src/quota.ts","../src/rrf.ts","../src/handler.ts","../src/discovery.ts"],"sourcesContent":["export {\n SEARCH_PATH,\n DEFAULT_INSTRUCTIONS,\n DEFAULT_DOCUMENTATION,\n FREE_QUERIES_PER_MONTH,\n PREPAID_USD_PER_1000,\n DEFAULT_MAX_RESULTS,\n DEFAULT_MATCH_THRESHOLD,\n DEFAULT_CHUNK_TOKENS,\n DEFAULT_CHUNK_OVERLAP_RATIO,\n RRF_K,\n DEFAULT_EMBEDDING_DIMENSION,\n ALLOW_METHODS,\n ACCEPT_QUERY,\n MARKDOWN_CONTENT_TYPE,\n PLAIN_CONTENT_TYPE,\n MISSING_QUERY_BODY,\n} from \"./types.js\";\nexport type {\n SearchHit,\n SearchBackend,\n QuotaBucket,\n QuotaDecision,\n QuotaExhausted,\n QuotaResult,\n QuotaStore,\n AgentDiscovery,\n SearchHandlerOptions,\n} from \"./types.js\";\n\nexport {\n formatSearchMarkdown,\n normalizeScores,\n parseSearchMarkdown,\n} from \"./markdown.js\";\nexport { parseSearchQuery } from \"./query.js\";\nexport {\n searchResponseHeaders,\n markdownResponse,\n plainResponse,\n emptyHead,\n methodNotAllowed,\n quotaExceededResponse,\n} from \"./headers.js\";\nexport {\n monthKey,\n decideQuota,\n prepaidQueriesForUsd,\n usdForPrepaidQueries,\n createMemoryQuotaStore,\n} from \"./quota.js\";\nexport { reciprocalRankFusion } from \"./rrf.js\";\nexport { handleSearchRequest } from \"./handler.js\";\nexport {\n agentDiscovery,\n agentMetaTags,\n agentYamlFrontMatter,\n} from \"./discovery.js\";\n","export const SEARCH_PATH = \"/.well-known/search\";\n\nexport const DEFAULT_INSTRUCTIONS =\n \"Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown.\";\n\nexport const DEFAULT_DOCUMENTATION =\n \"https://developers.cloudflare.com/ai-search/how-to/search-for-agents/\";\n\nexport const FREE_QUERIES_PER_MONTH = 1000;\nexport const PREPAID_USD_PER_1000 = 0.75;\nexport const DEFAULT_MAX_RESULTS = 10;\nexport const DEFAULT_MATCH_THRESHOLD = 0.4;\nexport const DEFAULT_CHUNK_TOKENS = 1024;\nexport const DEFAULT_CHUNK_OVERLAP_RATIO = 0.1;\nexport const RRF_K = 60;\nexport const DEFAULT_EMBEDDING_DIMENSION = 1536;\n\nexport const ALLOW_METHODS = \"GET, HEAD, QUERY\";\nexport const ACCEPT_QUERY = \"text/plain, application/json\";\nexport const MARKDOWN_CONTENT_TYPE = \"text/markdown; charset=utf-8\";\nexport const PLAIN_CONTENT_TYPE = \"text/plain; charset=utf-8\";\n\nexport const MISSING_QUERY_BODY = \"Missing query parameter: ?q=\";\n\nexport interface SearchHit {\n source: string;\n url: string;\n title: string;\n content: string;\n score: number;\n}\n\nexport interface SearchBackend {\n search(\n query: string,\n options: { limit: number; threshold: number },\n ): Promise<SearchHit[]>;\n}\n\nexport type QuotaBucket = \"free\" | \"credit\";\n\nexport interface QuotaDecision {\n ok: true;\n bucket: QuotaBucket;\n}\n\nexport interface QuotaExhausted {\n ok: false;\n reason: \"exhausted\";\n usedFree: number;\n credits: number;\n freeLimit: number;\n}\n\nexport type QuotaResult = QuotaDecision | QuotaExhausted;\n\nexport interface QuotaStore {\n consume(siteId: string): Promise<QuotaResult>;\n}\n\nexport interface AgentDiscovery {\n instructions: string;\n endpoint: string;\n method: \"GET\";\n documentation: string;\n}\n\nexport interface SearchHandlerOptions {\n backend: SearchBackend;\n quota?: QuotaStore;\n siteId?: string;\n maxResults?: number;\n matchThreshold?: number;\n origin?: string;\n}\n","import type { SearchHit } from \"./types.js\";\n\n/**\n * Render Search for Agents results.\n *\n * Observed Cloudflare format (live `developers.cloudflare.com/.well-known/search`):\n *\n * # Search results for: \"{query}\"\n *\n * ## {source} (score: {0.000})\n *\n * {chunk markdown}\n *\n * ---\n *\n * ## {source} (score: {0.000})\n * ...\n *\n * Scores are three decimal places. The first hit is normalized to 1.000.\n * Hits are separated by a horizontal rule. There is no trailing `---` after\n * the last hit.\n */\nexport function formatSearchMarkdown(query: string, hits: SearchHit[]): string {\n const header = `# Search results for: ${JSON.stringify(query)}`;\n if (hits.length === 0) {\n return `${header}\\n`;\n }\n\n const blocks = hits.map((hit) => {\n const score = Number.isFinite(hit.score) ? hit.score : 0;\n const heading = `## ${hit.source} (score: ${score.toFixed(3)})`;\n const body = hit.content.trim();\n return `${heading}\\n\\n${body}`;\n });\n\n return `${header}\\n\\n${blocks.join(\"\\n\\n---\\n\\n\")}\\n`;\n}\n\nexport function normalizeScores(hits: SearchHit[]): SearchHit[] {\n if (hits.length === 0) return hits;\n const max = Math.max(...hits.map((h) => h.score));\n if (max <= 0) {\n return hits.map((h, i) => ({\n ...h,\n score: i === 0 ? 1 : 0,\n }));\n }\n return hits.map((h) => ({ ...h, score: h.score / max }));\n}\n\nexport function parseSearchMarkdown(markdown: string): {\n query: string;\n hits: Array<{ source: string; score: number; content: string }>;\n} {\n const queryMatch = markdown.match(/^# Search results for: (.*)$/m);\n if (!queryMatch) {\n throw new Error(\"Not a Search for Agents markdown document\");\n }\n let query = queryMatch[1].trim();\n try {\n query = JSON.parse(query) as string;\n } catch {\n if (\n (query.startsWith('\"') && query.endsWith('\"')) ||\n (query.startsWith(\"'\") && query.endsWith(\"'\"))\n ) {\n query = query.slice(1, -1);\n }\n }\n\n const rest = markdown.slice(queryMatch.index! + queryMatch[0].length).trim();\n if (!rest) return { query, hits: [] };\n\n const chunks = rest.split(/\\n---\\n/);\n const hits = chunks\n .map((chunk) => chunk.trim())\n .filter(Boolean)\n .map((chunk) => {\n const heading = chunk.match(\n /^## (.+) \\(score: ([0-9]+(?:\\.[0-9]+)?)\\)$/m,\n );\n if (!heading) {\n throw new Error(`Invalid result heading in: ${chunk.slice(0, 80)}`);\n }\n const content = chunk.slice(heading[0].length).trim();\n return {\n source: heading[1],\n score: Number(heading[2]),\n content,\n };\n });\n\n return { query, hits };\n}\n","import { MISSING_QUERY_BODY } from \"./types.js\";\n\nexport type ParsedQuery =\n | { ok: true; q: string; method: \"GET\" | \"QUERY\" | \"HEAD\" }\n | { ok: false; status: number; body: string; contentType: string };\n\nfunction isJsonContentType(value: string | null): boolean {\n if (!value) return false;\n return value.toLowerCase().includes(\"application/json\");\n}\n\nfunction isPlainText(value: string | null): boolean {\n if (!value) return true;\n const v = value.toLowerCase();\n return (\n v.includes(\"text/plain\") ||\n v.includes(\"text/markdown\") ||\n v.includes(\"application/x-www-form-urlencoded\")\n );\n}\n\n/**\n * Extract the search text from a GET, HEAD, or QUERY request.\n *\n * Spec (Cloudflare docs + live endpoint):\n * - GET/HEAD: `?q=`\n * - QUERY + `text/plain`: raw UTF-8 body\n * - QUERY + `application/json`: `{ \"q\": \"...\" }`\n *\n * Decision (curl-friendly, not in the written spec): QUERY without a\n * Content-Type, and `application/x-www-form-urlencoded` bodies, are treated\n * as plain text. `curl -X QUERY --data '...'` sends urlencoded by default.\n * Empty or missing `q` returns HTTP 400 with body `Missing query parameter: ?q=`.\n */\nexport async function parseSearchQuery(request: Request): Promise<ParsedQuery> {\n const method = request.method.toUpperCase();\n const url = new URL(request.url);\n const headerQ = request.headers.get(\"x-agent-search-q\");\n\n if (method === \"GET\" || method === \"HEAD\") {\n const q = (headerQ ?? url.searchParams.get(\"q\") ?? \"\").trim();\n if (!q) {\n return {\n ok: false,\n status: 400,\n body: MISSING_QUERY_BODY,\n contentType: \"text/plain; charset=utf-8\",\n };\n }\n return { ok: true, q, method: method === \"HEAD\" ? \"HEAD\" : \"GET\" };\n }\n\n if (method === \"QUERY\") {\n const contentType = request.headers.get(\"content-type\");\n let q = \"\";\n try {\n if (isJsonContentType(contentType)) {\n const json = (await request.json()) as { q?: unknown };\n q = typeof json?.q === \"string\" ? json.q : \"\";\n } else if (isPlainText(contentType)) {\n const raw = await request.text();\n if (\n contentType &&\n contentType.toLowerCase().includes(\"application/x-www-form-urlencoded\")\n ) {\n const params = new URLSearchParams(raw);\n q = (params.get(\"q\") ?? raw).trim();\n } else {\n q = raw.trim();\n }\n } else {\n return {\n ok: false,\n status: 415,\n body: \"Unsupported QUERY content type. Use text/plain or application/json.\",\n contentType: \"text/plain; charset=utf-8\",\n };\n }\n } catch {\n return {\n ok: false,\n status: 400,\n body: MISSING_QUERY_BODY,\n contentType: \"text/plain; charset=utf-8\",\n };\n }\n q = q.trim();\n if (!q) {\n return {\n ok: false,\n status: 400,\n body: MISSING_QUERY_BODY,\n contentType: \"text/plain; charset=utf-8\",\n };\n }\n return { ok: true, q, method: \"QUERY\" };\n }\n\n return {\n ok: false,\n status: 405,\n body: \"Method Not Allowed\",\n contentType: \"text/plain; charset=utf-8\",\n };\n}\n","import {\n ACCEPT_QUERY,\n ALLOW_METHODS,\n MARKDOWN_CONTENT_TYPE,\n PLAIN_CONTENT_TYPE,\n} from \"./types.js\";\n\nexport function searchResponseHeaders(\n extra?: Record<string, string>,\n): Headers {\n const headers = new Headers({\n Allow: ALLOW_METHODS,\n \"Accept-Query\": ACCEPT_QUERY,\n \"X-Content-Type-Options\": \"nosniff\",\n ...extra,\n });\n return headers;\n}\n\nexport function markdownResponse(body: string, status = 200): Response {\n return new Response(body, {\n status,\n headers: searchResponseHeaders({\n \"Content-Type\": MARKDOWN_CONTENT_TYPE,\n }),\n });\n}\n\nexport function plainResponse(body: string, status: number): Response {\n return new Response(body, {\n status,\n headers: searchResponseHeaders({\n \"Content-Type\": PLAIN_CONTENT_TYPE,\n }),\n });\n}\n\nexport function emptyHead(status: number, markdown: boolean): Response {\n return new Response(null, {\n status,\n headers: searchResponseHeaders({\n \"Content-Type\": markdown ? MARKDOWN_CONTENT_TYPE : PLAIN_CONTENT_TYPE,\n }),\n });\n}\n\nexport function methodNotAllowed(): Response {\n return plainResponse(\"Method Not Allowed\", 405);\n}\n\nexport function quotaExceededResponse(): Response {\n return plainResponse(\n \"Query quota exceeded. This site has used its included 1000 queries this month and has no prepaid credit.\",\n 429,\n );\n}\n","import {\n FREE_QUERIES_PER_MONTH,\n type QuotaResult,\n type QuotaStore,\n} from \"./types.js\";\n\nexport function monthKey(date: Date = new Date()): string {\n const year = date.getUTCFullYear();\n const month = String(date.getUTCMonth() + 1).padStart(2, \"0\");\n return `${year}-${month}`;\n}\n\nexport function decideQuota(input: {\n usedFree: number;\n credits: number;\n freeLimit?: number;\n}): QuotaResult {\n const freeLimit = input.freeLimit ?? FREE_QUERIES_PER_MONTH;\n if (input.usedFree < freeLimit) {\n return { ok: true, bucket: \"free\" };\n }\n if (input.credits > 0) {\n return { ok: true, bucket: \"credit\" };\n }\n return {\n ok: false,\n reason: \"exhausted\",\n usedFree: input.usedFree,\n credits: input.credits,\n freeLimit,\n };\n}\n\nexport function prepaidQueriesForUsd(usd: number): number {\n return Math.round((usd / 0.75) * 1000);\n}\n\nexport function usdForPrepaidQueries(queries: number): number {\n return (queries / 1000) * 0.75;\n}\n\n/**\n * In-memory quota store for tests and local single-process demos.\n * Not safe across serverless instances — production uses Postgres.\n */\nexport function createMemoryQuotaStore(options?: {\n freeLimit?: number;\n creditsBySite?: Record<string, number>;\n}): QuotaStore & {\n snapshot(siteId: string): { usedFree: number; credits: number; month: string };\n} {\n const freeLimit = options?.freeLimit ?? FREE_QUERIES_PER_MONTH;\n const used = new Map<string, number>();\n const credits = new Map<string, number>(\n Object.entries(options?.creditsBySite ?? {}),\n );\n const currentMonth = () => monthKey();\n\n return {\n async consume(siteId: string): Promise<QuotaResult> {\n const key = `${siteId}:${currentMonth()}`;\n const usedFree = used.get(key) ?? 0;\n const remainingCredits = credits.get(siteId) ?? 0;\n const decision = decideQuota({\n usedFree,\n credits: remainingCredits,\n freeLimit,\n });\n if (!decision.ok) return decision;\n if (decision.bucket === \"free\") {\n used.set(key, usedFree + 1);\n } else {\n credits.set(siteId, remainingCredits - 1);\n }\n return decision;\n },\n snapshot(siteId: string) {\n return {\n usedFree: used.get(`${siteId}:${currentMonth()}`) ?? 0,\n credits: credits.get(siteId) ?? 0,\n month: currentMonth(),\n };\n },\n };\n}\n","import { RRF_K, type SearchHit } from \"./types.js\";\nimport { normalizeScores } from \"./markdown.js\";\n\nexport function reciprocalRankFusion(\n rankedLists: SearchHit[][],\n k: number = RRF_K,\n): SearchHit[] {\n const scores = new Map<string, { hit: SearchHit; score: number }>();\n\n for (const list of rankedLists) {\n list.forEach((hit, index) => {\n const key = hit.source;\n const add = 1 / (k + index + 1);\n const current = scores.get(key);\n if (current) {\n current.score += add;\n if (hit.content.length > current.hit.content.length) {\n current.hit = hit;\n }\n } else {\n scores.set(key, { hit, score: add });\n }\n });\n }\n\n const fused = [...scores.values()]\n .sort((a, b) => b.score - a.score)\n .map(({ hit, score }) => ({ ...hit, score }));\n\n return normalizeScores(fused);\n}\n","import { parseSearchQuery } from \"./query.js\";\nimport { formatSearchMarkdown } from \"./markdown.js\";\nimport {\n emptyHead,\n markdownResponse,\n methodNotAllowed,\n plainResponse,\n quotaExceededResponse,\n searchResponseHeaders,\n} from \"./headers.js\";\nimport {\n DEFAULT_MATCH_THRESHOLD,\n DEFAULT_MAX_RESULTS,\n type SearchHandlerOptions,\n} from \"./types.js\";\n\nexport async function handleSearchRequest(\n request: Request,\n options: SearchHandlerOptions,\n): Promise<Response> {\n const method = request.method.toUpperCase();\n\n if (method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: searchResponseHeaders(),\n });\n }\n\n if (![\"GET\", \"HEAD\", \"QUERY\"].includes(method)) {\n return methodNotAllowed();\n }\n\n const parsed = await parseSearchQuery(request);\n if (!parsed.ok) {\n if (method === \"HEAD\") {\n return emptyHead(parsed.status, false);\n }\n return plainResponse(parsed.body, parsed.status);\n }\n\n if (options.quota && options.siteId) {\n const quota = await options.quota.consume(options.siteId);\n if (!quota.ok) {\n if (method === \"HEAD\") return emptyHead(429, false);\n return quotaExceededResponse();\n }\n }\n\n const hits = await options.backend.search(parsed.q, {\n limit: options.maxResults ?? DEFAULT_MAX_RESULTS,\n threshold: options.matchThreshold ?? DEFAULT_MATCH_THRESHOLD,\n });\n\n const body = formatSearchMarkdown(parsed.q, hits);\n if (method === \"HEAD\") {\n return emptyHead(200, true);\n }\n return markdownResponse(body, 200);\n}\n","import {\n DEFAULT_DOCUMENTATION,\n DEFAULT_INSTRUCTIONS,\n SEARCH_PATH,\n type AgentDiscovery,\n} from \"./types.js\";\n\nexport function agentDiscovery(options: {\n origin: string;\n documentation?: string;\n instructions?: string;\n}): AgentDiscovery {\n const origin = options.origin.replace(/\\/$/, \"\");\n return {\n instructions: options.instructions ?? DEFAULT_INSTRUCTIONS,\n endpoint: `${origin}${SEARCH_PATH}?q={query}`,\n method: \"GET\",\n documentation: options.documentation ?? DEFAULT_DOCUMENTATION,\n };\n}\n\nexport function agentMetaTags(discovery: AgentDiscovery): string {\n return [\n `<meta name=\"agent:instructions\" content=\"${escapeAttr(discovery.instructions)}\" />`,\n `<meta name=\"agent:endpoint\" content=\"${escapeAttr(discovery.endpoint)}\" />`,\n `<meta name=\"agent:method\" content=\"${escapeAttr(discovery.method)}\" />`,\n `<meta name=\"agent:documentation\" content=\"${escapeAttr(discovery.documentation)}\" />`,\n ].join(\"\\n\");\n}\n\nexport function agentYamlFrontMatter(discovery: AgentDiscovery): string {\n return [\n \"---\",\n \"agent:\",\n ` instructions: ${JSON.stringify(discovery.instructions)}`,\n ` endpoint: ${JSON.stringify(discovery.endpoint)}`,\n ` method: ${JSON.stringify(discovery.method)}`,\n ` documentation: ${JSON.stringify(discovery.documentation)}`,\n \"---\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction escapeAttr(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,cAAc;AAEpB,IAAM,uBACX;AAEK,IAAM,wBACX;AAEK,IAAM,yBAAyB;AAC/B,IAAM,uBAAuB;AAC7B,IAAM,sB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,IACzD,eAAe,KAAK,UAAU,UAAU,QAAQ,CAAC;AAAA,IACjD,aAAa,KAAK,UAAU,UAAU,MAAM,CAAC;AAAA,IAC7C,oBAAoB,KAAK,UAAU,UAAU,aAAa,CAAC;AAAA,IAC3D;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,SAAS,WAAW,OAAuB;AACzC,SAAO,MACJ,WAAW,KAAK,OAAO,EACvB,WAAW,KAAK,QAAQ,EACxB,WAAW,KAAK,MAAM,EACtB,WAAW,KAAK,MAAM;AAC3B;","names":[]}
@@ -0,0 +1,159 @@
1
+ declare const SEARCH_PATH = "/.well-known/search";
2
+ declare const DEFAULT_INSTRUCTIONS = "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown.";
3
+ declare const DEFAULT_DOCUMENTATION = "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/";
4
+ declare const FREE_QUERIES_PER_MONTH = 1000;
5
+ declare const PREPAID_USD_PER_1000 = 0.75;
6
+ declare const DEFAULT_MAX_RESULTS = 10;
7
+ declare const DEFAULT_MATCH_THRESHOLD = 0.4;
8
+ declare const DEFAULT_CHUNK_TOKENS = 1024;
9
+ declare const DEFAULT_CHUNK_OVERLAP_RATIO = 0.1;
10
+ declare const RRF_K = 60;
11
+ declare const DEFAULT_EMBEDDING_DIMENSION = 1536;
12
+ declare const ALLOW_METHODS = "GET, HEAD, QUERY";
13
+ declare const ACCEPT_QUERY = "text/plain, application/json";
14
+ declare const MARKDOWN_CONTENT_TYPE = "text/markdown; charset=utf-8";
15
+ declare const PLAIN_CONTENT_TYPE = "text/plain; charset=utf-8";
16
+ declare const MISSING_QUERY_BODY = "Missing query parameter: ?q=";
17
+ interface SearchHit {
18
+ source: string;
19
+ url: string;
20
+ title: string;
21
+ content: string;
22
+ score: number;
23
+ }
24
+ interface SearchBackend {
25
+ search(query: string, options: {
26
+ limit: number;
27
+ threshold: number;
28
+ }): Promise<SearchHit[]>;
29
+ }
30
+ type QuotaBucket = "free" | "credit";
31
+ interface QuotaDecision {
32
+ ok: true;
33
+ bucket: QuotaBucket;
34
+ }
35
+ interface QuotaExhausted {
36
+ ok: false;
37
+ reason: "exhausted";
38
+ usedFree: number;
39
+ credits: number;
40
+ freeLimit: number;
41
+ }
42
+ type QuotaResult = QuotaDecision | QuotaExhausted;
43
+ interface QuotaStore {
44
+ consume(siteId: string): Promise<QuotaResult>;
45
+ }
46
+ interface AgentDiscovery {
47
+ instructions: string;
48
+ endpoint: string;
49
+ method: "GET";
50
+ documentation: string;
51
+ }
52
+ interface SearchHandlerOptions {
53
+ backend: SearchBackend;
54
+ quota?: QuotaStore;
55
+ siteId?: string;
56
+ maxResults?: number;
57
+ matchThreshold?: number;
58
+ origin?: string;
59
+ }
60
+
61
+ /**
62
+ * Render Search for Agents results.
63
+ *
64
+ * Observed Cloudflare format (live `developers.cloudflare.com/.well-known/search`):
65
+ *
66
+ * # Search results for: "{query}"
67
+ *
68
+ * ## {source} (score: {0.000})
69
+ *
70
+ * {chunk markdown}
71
+ *
72
+ * ---
73
+ *
74
+ * ## {source} (score: {0.000})
75
+ * ...
76
+ *
77
+ * Scores are three decimal places. The first hit is normalized to 1.000.
78
+ * Hits are separated by a horizontal rule. There is no trailing `---` after
79
+ * the last hit.
80
+ */
81
+ declare function formatSearchMarkdown(query: string, hits: SearchHit[]): string;
82
+ declare function normalizeScores(hits: SearchHit[]): SearchHit[];
83
+ declare function parseSearchMarkdown(markdown: string): {
84
+ query: string;
85
+ hits: Array<{
86
+ source: string;
87
+ score: number;
88
+ content: string;
89
+ }>;
90
+ };
91
+
92
+ type ParsedQuery = {
93
+ ok: true;
94
+ q: string;
95
+ method: "GET" | "QUERY" | "HEAD";
96
+ } | {
97
+ ok: false;
98
+ status: number;
99
+ body: string;
100
+ contentType: string;
101
+ };
102
+ /**
103
+ * Extract the search text from a GET, HEAD, or QUERY request.
104
+ *
105
+ * Spec (Cloudflare docs + live endpoint):
106
+ * - GET/HEAD: `?q=`
107
+ * - QUERY + `text/plain`: raw UTF-8 body
108
+ * - QUERY + `application/json`: `{ "q": "..." }`
109
+ *
110
+ * Decision (curl-friendly, not in the written spec): QUERY without a
111
+ * Content-Type, and `application/x-www-form-urlencoded` bodies, are treated
112
+ * as plain text. `curl -X QUERY --data '...'` sends urlencoded by default.
113
+ * Empty or missing `q` returns HTTP 400 with body `Missing query parameter: ?q=`.
114
+ */
115
+ declare function parseSearchQuery(request: Request): Promise<ParsedQuery>;
116
+
117
+ declare function searchResponseHeaders(extra?: Record<string, string>): Headers;
118
+ declare function markdownResponse(body: string, status?: number): Response;
119
+ declare function plainResponse(body: string, status: number): Response;
120
+ declare function emptyHead(status: number, markdown: boolean): Response;
121
+ declare function methodNotAllowed(): Response;
122
+ declare function quotaExceededResponse(): Response;
123
+
124
+ declare function monthKey(date?: Date): string;
125
+ declare function decideQuota(input: {
126
+ usedFree: number;
127
+ credits: number;
128
+ freeLimit?: number;
129
+ }): QuotaResult;
130
+ declare function prepaidQueriesForUsd(usd: number): number;
131
+ declare function usdForPrepaidQueries(queries: number): number;
132
+ /**
133
+ * In-memory quota store for tests and local single-process demos.
134
+ * Not safe across serverless instances — production uses Postgres.
135
+ */
136
+ declare function createMemoryQuotaStore(options?: {
137
+ freeLimit?: number;
138
+ creditsBySite?: Record<string, number>;
139
+ }): QuotaStore & {
140
+ snapshot(siteId: string): {
141
+ usedFree: number;
142
+ credits: number;
143
+ month: string;
144
+ };
145
+ };
146
+
147
+ declare function reciprocalRankFusion(rankedLists: SearchHit[][], k?: number): SearchHit[];
148
+
149
+ declare function handleSearchRequest(request: Request, options: SearchHandlerOptions): Promise<Response>;
150
+
151
+ declare function agentDiscovery(options: {
152
+ origin: string;
153
+ documentation?: string;
154
+ instructions?: string;
155
+ }): AgentDiscovery;
156
+ declare function agentMetaTags(discovery: AgentDiscovery): string;
157
+ declare function agentYamlFrontMatter(discovery: AgentDiscovery): string;
158
+
159
+ export { ACCEPT_QUERY, ALLOW_METHODS, type AgentDiscovery, DEFAULT_CHUNK_OVERLAP_RATIO, DEFAULT_CHUNK_TOKENS, DEFAULT_DOCUMENTATION, DEFAULT_EMBEDDING_DIMENSION, DEFAULT_INSTRUCTIONS, DEFAULT_MATCH_THRESHOLD, DEFAULT_MAX_RESULTS, FREE_QUERIES_PER_MONTH, MARKDOWN_CONTENT_TYPE, MISSING_QUERY_BODY, PLAIN_CONTENT_TYPE, PREPAID_USD_PER_1000, type QuotaBucket, type QuotaDecision, type QuotaExhausted, type QuotaResult, type QuotaStore, RRF_K, SEARCH_PATH, type SearchBackend, type SearchHandlerOptions, type SearchHit, agentDiscovery, agentMetaTags, agentYamlFrontMatter, createMemoryQuotaStore, decideQuota, emptyHead, formatSearchMarkdown, handleSearchRequest, markdownResponse, methodNotAllowed, monthKey, normalizeScores, parseSearchMarkdown, parseSearchQuery, plainResponse, prepaidQueriesForUsd, quotaExceededResponse, reciprocalRankFusion, searchResponseHeaders, usdForPrepaidQueries };
@@ -0,0 +1,159 @@
1
+ declare const SEARCH_PATH = "/.well-known/search";
2
+ declare const DEFAULT_INSTRUCTIONS = "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown.";
3
+ declare const DEFAULT_DOCUMENTATION = "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/";
4
+ declare const FREE_QUERIES_PER_MONTH = 1000;
5
+ declare const PREPAID_USD_PER_1000 = 0.75;
6
+ declare const DEFAULT_MAX_RESULTS = 10;
7
+ declare const DEFAULT_MATCH_THRESHOLD = 0.4;
8
+ declare const DEFAULT_CHUNK_TOKENS = 1024;
9
+ declare const DEFAULT_CHUNK_OVERLAP_RATIO = 0.1;
10
+ declare const RRF_K = 60;
11
+ declare const DEFAULT_EMBEDDING_DIMENSION = 1536;
12
+ declare const ALLOW_METHODS = "GET, HEAD, QUERY";
13
+ declare const ACCEPT_QUERY = "text/plain, application/json";
14
+ declare const MARKDOWN_CONTENT_TYPE = "text/markdown; charset=utf-8";
15
+ declare const PLAIN_CONTENT_TYPE = "text/plain; charset=utf-8";
16
+ declare const MISSING_QUERY_BODY = "Missing query parameter: ?q=";
17
+ interface SearchHit {
18
+ source: string;
19
+ url: string;
20
+ title: string;
21
+ content: string;
22
+ score: number;
23
+ }
24
+ interface SearchBackend {
25
+ search(query: string, options: {
26
+ limit: number;
27
+ threshold: number;
28
+ }): Promise<SearchHit[]>;
29
+ }
30
+ type QuotaBucket = "free" | "credit";
31
+ interface QuotaDecision {
32
+ ok: true;
33
+ bucket: QuotaBucket;
34
+ }
35
+ interface QuotaExhausted {
36
+ ok: false;
37
+ reason: "exhausted";
38
+ usedFree: number;
39
+ credits: number;
40
+ freeLimit: number;
41
+ }
42
+ type QuotaResult = QuotaDecision | QuotaExhausted;
43
+ interface QuotaStore {
44
+ consume(siteId: string): Promise<QuotaResult>;
45
+ }
46
+ interface AgentDiscovery {
47
+ instructions: string;
48
+ endpoint: string;
49
+ method: "GET";
50
+ documentation: string;
51
+ }
52
+ interface SearchHandlerOptions {
53
+ backend: SearchBackend;
54
+ quota?: QuotaStore;
55
+ siteId?: string;
56
+ maxResults?: number;
57
+ matchThreshold?: number;
58
+ origin?: string;
59
+ }
60
+
61
+ /**
62
+ * Render Search for Agents results.
63
+ *
64
+ * Observed Cloudflare format (live `developers.cloudflare.com/.well-known/search`):
65
+ *
66
+ * # Search results for: "{query}"
67
+ *
68
+ * ## {source} (score: {0.000})
69
+ *
70
+ * {chunk markdown}
71
+ *
72
+ * ---
73
+ *
74
+ * ## {source} (score: {0.000})
75
+ * ...
76
+ *
77
+ * Scores are three decimal places. The first hit is normalized to 1.000.
78
+ * Hits are separated by a horizontal rule. There is no trailing `---` after
79
+ * the last hit.
80
+ */
81
+ declare function formatSearchMarkdown(query: string, hits: SearchHit[]): string;
82
+ declare function normalizeScores(hits: SearchHit[]): SearchHit[];
83
+ declare function parseSearchMarkdown(markdown: string): {
84
+ query: string;
85
+ hits: Array<{
86
+ source: string;
87
+ score: number;
88
+ content: string;
89
+ }>;
90
+ };
91
+
92
+ type ParsedQuery = {
93
+ ok: true;
94
+ q: string;
95
+ method: "GET" | "QUERY" | "HEAD";
96
+ } | {
97
+ ok: false;
98
+ status: number;
99
+ body: string;
100
+ contentType: string;
101
+ };
102
+ /**
103
+ * Extract the search text from a GET, HEAD, or QUERY request.
104
+ *
105
+ * Spec (Cloudflare docs + live endpoint):
106
+ * - GET/HEAD: `?q=`
107
+ * - QUERY + `text/plain`: raw UTF-8 body
108
+ * - QUERY + `application/json`: `{ "q": "..." }`
109
+ *
110
+ * Decision (curl-friendly, not in the written spec): QUERY without a
111
+ * Content-Type, and `application/x-www-form-urlencoded` bodies, are treated
112
+ * as plain text. `curl -X QUERY --data '...'` sends urlencoded by default.
113
+ * Empty or missing `q` returns HTTP 400 with body `Missing query parameter: ?q=`.
114
+ */
115
+ declare function parseSearchQuery(request: Request): Promise<ParsedQuery>;
116
+
117
+ declare function searchResponseHeaders(extra?: Record<string, string>): Headers;
118
+ declare function markdownResponse(body: string, status?: number): Response;
119
+ declare function plainResponse(body: string, status: number): Response;
120
+ declare function emptyHead(status: number, markdown: boolean): Response;
121
+ declare function methodNotAllowed(): Response;
122
+ declare function quotaExceededResponse(): Response;
123
+
124
+ declare function monthKey(date?: Date): string;
125
+ declare function decideQuota(input: {
126
+ usedFree: number;
127
+ credits: number;
128
+ freeLimit?: number;
129
+ }): QuotaResult;
130
+ declare function prepaidQueriesForUsd(usd: number): number;
131
+ declare function usdForPrepaidQueries(queries: number): number;
132
+ /**
133
+ * In-memory quota store for tests and local single-process demos.
134
+ * Not safe across serverless instances — production uses Postgres.
135
+ */
136
+ declare function createMemoryQuotaStore(options?: {
137
+ freeLimit?: number;
138
+ creditsBySite?: Record<string, number>;
139
+ }): QuotaStore & {
140
+ snapshot(siteId: string): {
141
+ usedFree: number;
142
+ credits: number;
143
+ month: string;
144
+ };
145
+ };
146
+
147
+ declare function reciprocalRankFusion(rankedLists: SearchHit[][], k?: number): SearchHit[];
148
+
149
+ declare function handleSearchRequest(request: Request, options: SearchHandlerOptions): Promise<Response>;
150
+
151
+ declare function agentDiscovery(options: {
152
+ origin: string;
153
+ documentation?: string;
154
+ instructions?: string;
155
+ }): AgentDiscovery;
156
+ declare function agentMetaTags(discovery: AgentDiscovery): string;
157
+ declare function agentYamlFrontMatter(discovery: AgentDiscovery): string;
158
+
159
+ export { ACCEPT_QUERY, ALLOW_METHODS, type AgentDiscovery, DEFAULT_CHUNK_OVERLAP_RATIO, DEFAULT_CHUNK_TOKENS, DEFAULT_DOCUMENTATION, DEFAULT_EMBEDDING_DIMENSION, DEFAULT_INSTRUCTIONS, DEFAULT_MATCH_THRESHOLD, DEFAULT_MAX_RESULTS, FREE_QUERIES_PER_MONTH, MARKDOWN_CONTENT_TYPE, MISSING_QUERY_BODY, PLAIN_CONTENT_TYPE, PREPAID_USD_PER_1000, type QuotaBucket, type QuotaDecision, type QuotaExhausted, type QuotaResult, type QuotaStore, RRF_K, SEARCH_PATH, type SearchBackend, type SearchHandlerOptions, type SearchHit, agentDiscovery, agentMetaTags, agentYamlFrontMatter, createMemoryQuotaStore, decideQuota, emptyHead, formatSearchMarkdown, handleSearchRequest, markdownResponse, methodNotAllowed, monthKey, normalizeScores, parseSearchMarkdown, parseSearchQuery, plainResponse, prepaidQueriesForUsd, quotaExceededResponse, reciprocalRankFusion, searchResponseHeaders, usdForPrepaidQueries };
package/dist/index.js ADDED
@@ -0,0 +1,396 @@
1
+ // src/types.ts
2
+ var SEARCH_PATH = "/.well-known/search";
3
+ var DEFAULT_INSTRUCTIONS = "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown.";
4
+ var DEFAULT_DOCUMENTATION = "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/";
5
+ var FREE_QUERIES_PER_MONTH = 1e3;
6
+ var PREPAID_USD_PER_1000 = 0.75;
7
+ var DEFAULT_MAX_RESULTS = 10;
8
+ var DEFAULT_MATCH_THRESHOLD = 0.4;
9
+ var DEFAULT_CHUNK_TOKENS = 1024;
10
+ var DEFAULT_CHUNK_OVERLAP_RATIO = 0.1;
11
+ var RRF_K = 60;
12
+ var DEFAULT_EMBEDDING_DIMENSION = 1536;
13
+ var ALLOW_METHODS = "GET, HEAD, QUERY";
14
+ var ACCEPT_QUERY = "text/plain, application/json";
15
+ var MARKDOWN_CONTENT_TYPE = "text/markdown; charset=utf-8";
16
+ var PLAIN_CONTENT_TYPE = "text/plain; charset=utf-8";
17
+ var MISSING_QUERY_BODY = "Missing query parameter: ?q=";
18
+
19
+ // src/markdown.ts
20
+ function formatSearchMarkdown(query, hits) {
21
+ const header = `# Search results for: ${JSON.stringify(query)}`;
22
+ if (hits.length === 0) {
23
+ return `${header}
24
+ `;
25
+ }
26
+ const blocks = hits.map((hit) => {
27
+ const score = Number.isFinite(hit.score) ? hit.score : 0;
28
+ const heading = `## ${hit.source} (score: ${score.toFixed(3)})`;
29
+ const body = hit.content.trim();
30
+ return `${heading}
31
+
32
+ ${body}`;
33
+ });
34
+ return `${header}
35
+
36
+ ${blocks.join("\n\n---\n\n")}
37
+ `;
38
+ }
39
+ function normalizeScores(hits) {
40
+ if (hits.length === 0) return hits;
41
+ const max = Math.max(...hits.map((h) => h.score));
42
+ if (max <= 0) {
43
+ return hits.map((h, i) => ({
44
+ ...h,
45
+ score: i === 0 ? 1 : 0
46
+ }));
47
+ }
48
+ return hits.map((h) => ({ ...h, score: h.score / max }));
49
+ }
50
+ function parseSearchMarkdown(markdown) {
51
+ const queryMatch = markdown.match(/^# Search results for: (.*)$/m);
52
+ if (!queryMatch) {
53
+ throw new Error("Not a Search for Agents markdown document");
54
+ }
55
+ let query = queryMatch[1].trim();
56
+ try {
57
+ query = JSON.parse(query);
58
+ } catch {
59
+ if (query.startsWith('"') && query.endsWith('"') || query.startsWith("'") && query.endsWith("'")) {
60
+ query = query.slice(1, -1);
61
+ }
62
+ }
63
+ const rest = markdown.slice(queryMatch.index + queryMatch[0].length).trim();
64
+ if (!rest) return { query, hits: [] };
65
+ const chunks = rest.split(/\n---\n/);
66
+ const hits = chunks.map((chunk) => chunk.trim()).filter(Boolean).map((chunk) => {
67
+ const heading = chunk.match(
68
+ /^## (.+) \(score: ([0-9]+(?:\.[0-9]+)?)\)$/m
69
+ );
70
+ if (!heading) {
71
+ throw new Error(`Invalid result heading in: ${chunk.slice(0, 80)}`);
72
+ }
73
+ const content = chunk.slice(heading[0].length).trim();
74
+ return {
75
+ source: heading[1],
76
+ score: Number(heading[2]),
77
+ content
78
+ };
79
+ });
80
+ return { query, hits };
81
+ }
82
+
83
+ // src/query.ts
84
+ function isJsonContentType(value) {
85
+ if (!value) return false;
86
+ return value.toLowerCase().includes("application/json");
87
+ }
88
+ function isPlainText(value) {
89
+ if (!value) return true;
90
+ const v = value.toLowerCase();
91
+ return v.includes("text/plain") || v.includes("text/markdown") || v.includes("application/x-www-form-urlencoded");
92
+ }
93
+ async function parseSearchQuery(request) {
94
+ const method = request.method.toUpperCase();
95
+ const url = new URL(request.url);
96
+ const headerQ = request.headers.get("x-agent-search-q");
97
+ if (method === "GET" || method === "HEAD") {
98
+ const q = (headerQ ?? url.searchParams.get("q") ?? "").trim();
99
+ if (!q) {
100
+ return {
101
+ ok: false,
102
+ status: 400,
103
+ body: MISSING_QUERY_BODY,
104
+ contentType: "text/plain; charset=utf-8"
105
+ };
106
+ }
107
+ return { ok: true, q, method: method === "HEAD" ? "HEAD" : "GET" };
108
+ }
109
+ if (method === "QUERY") {
110
+ const contentType = request.headers.get("content-type");
111
+ let q = "";
112
+ try {
113
+ if (isJsonContentType(contentType)) {
114
+ const json = await request.json();
115
+ q = typeof json?.q === "string" ? json.q : "";
116
+ } else if (isPlainText(contentType)) {
117
+ const raw = await request.text();
118
+ if (contentType && contentType.toLowerCase().includes("application/x-www-form-urlencoded")) {
119
+ const params = new URLSearchParams(raw);
120
+ q = (params.get("q") ?? raw).trim();
121
+ } else {
122
+ q = raw.trim();
123
+ }
124
+ } else {
125
+ return {
126
+ ok: false,
127
+ status: 415,
128
+ body: "Unsupported QUERY content type. Use text/plain or application/json.",
129
+ contentType: "text/plain; charset=utf-8"
130
+ };
131
+ }
132
+ } catch {
133
+ return {
134
+ ok: false,
135
+ status: 400,
136
+ body: MISSING_QUERY_BODY,
137
+ contentType: "text/plain; charset=utf-8"
138
+ };
139
+ }
140
+ q = q.trim();
141
+ if (!q) {
142
+ return {
143
+ ok: false,
144
+ status: 400,
145
+ body: MISSING_QUERY_BODY,
146
+ contentType: "text/plain; charset=utf-8"
147
+ };
148
+ }
149
+ return { ok: true, q, method: "QUERY" };
150
+ }
151
+ return {
152
+ ok: false,
153
+ status: 405,
154
+ body: "Method Not Allowed",
155
+ contentType: "text/plain; charset=utf-8"
156
+ };
157
+ }
158
+
159
+ // src/headers.ts
160
+ function searchResponseHeaders(extra) {
161
+ const headers = new Headers({
162
+ Allow: ALLOW_METHODS,
163
+ "Accept-Query": ACCEPT_QUERY,
164
+ "X-Content-Type-Options": "nosniff",
165
+ ...extra
166
+ });
167
+ return headers;
168
+ }
169
+ function markdownResponse(body, status = 200) {
170
+ return new Response(body, {
171
+ status,
172
+ headers: searchResponseHeaders({
173
+ "Content-Type": MARKDOWN_CONTENT_TYPE
174
+ })
175
+ });
176
+ }
177
+ function plainResponse(body, status) {
178
+ return new Response(body, {
179
+ status,
180
+ headers: searchResponseHeaders({
181
+ "Content-Type": PLAIN_CONTENT_TYPE
182
+ })
183
+ });
184
+ }
185
+ function emptyHead(status, markdown) {
186
+ return new Response(null, {
187
+ status,
188
+ headers: searchResponseHeaders({
189
+ "Content-Type": markdown ? MARKDOWN_CONTENT_TYPE : PLAIN_CONTENT_TYPE
190
+ })
191
+ });
192
+ }
193
+ function methodNotAllowed() {
194
+ return plainResponse("Method Not Allowed", 405);
195
+ }
196
+ function quotaExceededResponse() {
197
+ return plainResponse(
198
+ "Query quota exceeded. This site has used its included 1000 queries this month and has no prepaid credit.",
199
+ 429
200
+ );
201
+ }
202
+
203
+ // src/quota.ts
204
+ function monthKey(date = /* @__PURE__ */ new Date()) {
205
+ const year = date.getUTCFullYear();
206
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
207
+ return `${year}-${month}`;
208
+ }
209
+ function decideQuota(input) {
210
+ const freeLimit = input.freeLimit ?? FREE_QUERIES_PER_MONTH;
211
+ if (input.usedFree < freeLimit) {
212
+ return { ok: true, bucket: "free" };
213
+ }
214
+ if (input.credits > 0) {
215
+ return { ok: true, bucket: "credit" };
216
+ }
217
+ return {
218
+ ok: false,
219
+ reason: "exhausted",
220
+ usedFree: input.usedFree,
221
+ credits: input.credits,
222
+ freeLimit
223
+ };
224
+ }
225
+ function prepaidQueriesForUsd(usd) {
226
+ return Math.round(usd / 0.75 * 1e3);
227
+ }
228
+ function usdForPrepaidQueries(queries) {
229
+ return queries / 1e3 * 0.75;
230
+ }
231
+ function createMemoryQuotaStore(options) {
232
+ const freeLimit = options?.freeLimit ?? FREE_QUERIES_PER_MONTH;
233
+ const used = /* @__PURE__ */ new Map();
234
+ const credits = new Map(
235
+ Object.entries(options?.creditsBySite ?? {})
236
+ );
237
+ const currentMonth = () => monthKey();
238
+ return {
239
+ async consume(siteId) {
240
+ const key = `${siteId}:${currentMonth()}`;
241
+ const usedFree = used.get(key) ?? 0;
242
+ const remainingCredits = credits.get(siteId) ?? 0;
243
+ const decision = decideQuota({
244
+ usedFree,
245
+ credits: remainingCredits,
246
+ freeLimit
247
+ });
248
+ if (!decision.ok) return decision;
249
+ if (decision.bucket === "free") {
250
+ used.set(key, usedFree + 1);
251
+ } else {
252
+ credits.set(siteId, remainingCredits - 1);
253
+ }
254
+ return decision;
255
+ },
256
+ snapshot(siteId) {
257
+ return {
258
+ usedFree: used.get(`${siteId}:${currentMonth()}`) ?? 0,
259
+ credits: credits.get(siteId) ?? 0,
260
+ month: currentMonth()
261
+ };
262
+ }
263
+ };
264
+ }
265
+
266
+ // src/rrf.ts
267
+ function reciprocalRankFusion(rankedLists, k = RRF_K) {
268
+ const scores = /* @__PURE__ */ new Map();
269
+ for (const list of rankedLists) {
270
+ list.forEach((hit, index) => {
271
+ const key = hit.source;
272
+ const add = 1 / (k + index + 1);
273
+ const current = scores.get(key);
274
+ if (current) {
275
+ current.score += add;
276
+ if (hit.content.length > current.hit.content.length) {
277
+ current.hit = hit;
278
+ }
279
+ } else {
280
+ scores.set(key, { hit, score: add });
281
+ }
282
+ });
283
+ }
284
+ const fused = [...scores.values()].sort((a, b) => b.score - a.score).map(({ hit, score }) => ({ ...hit, score }));
285
+ return normalizeScores(fused);
286
+ }
287
+
288
+ // src/handler.ts
289
+ async function handleSearchRequest(request, options) {
290
+ const method = request.method.toUpperCase();
291
+ if (method === "OPTIONS") {
292
+ return new Response(null, {
293
+ status: 204,
294
+ headers: searchResponseHeaders()
295
+ });
296
+ }
297
+ if (!["GET", "HEAD", "QUERY"].includes(method)) {
298
+ return methodNotAllowed();
299
+ }
300
+ const parsed = await parseSearchQuery(request);
301
+ if (!parsed.ok) {
302
+ if (method === "HEAD") {
303
+ return emptyHead(parsed.status, false);
304
+ }
305
+ return plainResponse(parsed.body, parsed.status);
306
+ }
307
+ if (options.quota && options.siteId) {
308
+ const quota = await options.quota.consume(options.siteId);
309
+ if (!quota.ok) {
310
+ if (method === "HEAD") return emptyHead(429, false);
311
+ return quotaExceededResponse();
312
+ }
313
+ }
314
+ const hits = await options.backend.search(parsed.q, {
315
+ limit: options.maxResults ?? DEFAULT_MAX_RESULTS,
316
+ threshold: options.matchThreshold ?? DEFAULT_MATCH_THRESHOLD
317
+ });
318
+ const body = formatSearchMarkdown(parsed.q, hits);
319
+ if (method === "HEAD") {
320
+ return emptyHead(200, true);
321
+ }
322
+ return markdownResponse(body, 200);
323
+ }
324
+
325
+ // src/discovery.ts
326
+ function agentDiscovery(options) {
327
+ const origin = options.origin.replace(/\/$/, "");
328
+ return {
329
+ instructions: options.instructions ?? DEFAULT_INSTRUCTIONS,
330
+ endpoint: `${origin}${SEARCH_PATH}?q={query}`,
331
+ method: "GET",
332
+ documentation: options.documentation ?? DEFAULT_DOCUMENTATION
333
+ };
334
+ }
335
+ function agentMetaTags(discovery) {
336
+ return [
337
+ `<meta name="agent:instructions" content="${escapeAttr(discovery.instructions)}" />`,
338
+ `<meta name="agent:endpoint" content="${escapeAttr(discovery.endpoint)}" />`,
339
+ `<meta name="agent:method" content="${escapeAttr(discovery.method)}" />`,
340
+ `<meta name="agent:documentation" content="${escapeAttr(discovery.documentation)}" />`
341
+ ].join("\n");
342
+ }
343
+ function agentYamlFrontMatter(discovery) {
344
+ return [
345
+ "---",
346
+ "agent:",
347
+ ` instructions: ${JSON.stringify(discovery.instructions)}`,
348
+ ` endpoint: ${JSON.stringify(discovery.endpoint)}`,
349
+ ` method: ${JSON.stringify(discovery.method)}`,
350
+ ` documentation: ${JSON.stringify(discovery.documentation)}`,
351
+ "---",
352
+ ""
353
+ ].join("\n");
354
+ }
355
+ function escapeAttr(value) {
356
+ return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
357
+ }
358
+ export {
359
+ ACCEPT_QUERY,
360
+ ALLOW_METHODS,
361
+ DEFAULT_CHUNK_OVERLAP_RATIO,
362
+ DEFAULT_CHUNK_TOKENS,
363
+ DEFAULT_DOCUMENTATION,
364
+ DEFAULT_EMBEDDING_DIMENSION,
365
+ DEFAULT_INSTRUCTIONS,
366
+ DEFAULT_MATCH_THRESHOLD,
367
+ DEFAULT_MAX_RESULTS,
368
+ FREE_QUERIES_PER_MONTH,
369
+ MARKDOWN_CONTENT_TYPE,
370
+ MISSING_QUERY_BODY,
371
+ PLAIN_CONTENT_TYPE,
372
+ PREPAID_USD_PER_1000,
373
+ RRF_K,
374
+ SEARCH_PATH,
375
+ agentDiscovery,
376
+ agentMetaTags,
377
+ agentYamlFrontMatter,
378
+ createMemoryQuotaStore,
379
+ decideQuota,
380
+ emptyHead,
381
+ formatSearchMarkdown,
382
+ handleSearchRequest,
383
+ markdownResponse,
384
+ methodNotAllowed,
385
+ monthKey,
386
+ normalizeScores,
387
+ parseSearchMarkdown,
388
+ parseSearchQuery,
389
+ plainResponse,
390
+ prepaidQueriesForUsd,
391
+ quotaExceededResponse,
392
+ reciprocalRankFusion,
393
+ searchResponseHeaders,
394
+ usdForPrepaidQueries
395
+ };
396
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/markdown.ts","../src/query.ts","../src/headers.ts","../src/quota.ts","../src/rrf.ts","../src/handler.ts","../src/discovery.ts"],"sourcesContent":["export const SEARCH_PATH = \"/.well-known/search\";\n\nexport const DEFAULT_INSTRUCTIONS =\n \"Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown.\";\n\nexport const DEFAULT_DOCUMENTATION =\n \"https://developers.cloudflare.com/ai-search/how-to/search-for-agents/\";\n\nexport const FREE_QUERIES_PER_MONTH = 1000;\nexport const PREPAID_USD_PER_1000 = 0.75;\nexport const DEFAULT_MAX_RESULTS = 10;\nexport const DEFAULT_MATCH_THRESHOLD = 0.4;\nexport const DEFAULT_CHUNK_TOKENS = 1024;\nexport const DEFAULT_CHUNK_OVERLAP_RATIO = 0.1;\nexport const RRF_K = 60;\nexport const DEFAULT_EMBEDDING_DIMENSION = 1536;\n\nexport const ALLOW_METHODS = \"GET, HEAD, QUERY\";\nexport const ACCEPT_QUERY = \"text/plain, application/json\";\nexport const MARKDOWN_CONTENT_TYPE = \"text/markdown; charset=utf-8\";\nexport const PLAIN_CONTENT_TYPE = \"text/plain; charset=utf-8\";\n\nexport const MISSING_QUERY_BODY = \"Missing query parameter: ?q=\";\n\nexport interface SearchHit {\n source: string;\n url: string;\n title: string;\n content: string;\n score: number;\n}\n\nexport interface SearchBackend {\n search(\n query: string,\n options: { limit: number; threshold: number },\n ): Promise<SearchHit[]>;\n}\n\nexport type QuotaBucket = \"free\" | \"credit\";\n\nexport interface QuotaDecision {\n ok: true;\n bucket: QuotaBucket;\n}\n\nexport interface QuotaExhausted {\n ok: false;\n reason: \"exhausted\";\n usedFree: number;\n credits: number;\n freeLimit: number;\n}\n\nexport type QuotaResult = QuotaDecision | QuotaExhausted;\n\nexport interface QuotaStore {\n consume(siteId: string): Promise<QuotaResult>;\n}\n\nexport interface AgentDiscovery {\n instructions: string;\n endpoint: string;\n method: \"GET\";\n documentation: string;\n}\n\nexport interface SearchHandlerOptions {\n backend: SearchBackend;\n quota?: QuotaStore;\n siteId?: string;\n maxResults?: number;\n matchThreshold?: number;\n origin?: string;\n}\n","import type { SearchHit } from \"./types.js\";\n\n/**\n * Render Search for Agents results.\n *\n * Observed Cloudflare format (live `developers.cloudflare.com/.well-known/search`):\n *\n * # Search results for: \"{query}\"\n *\n * ## {source} (score: {0.000})\n *\n * {chunk markdown}\n *\n * ---\n *\n * ## {source} (score: {0.000})\n * ...\n *\n * Scores are three decimal places. The first hit is normalized to 1.000.\n * Hits are separated by a horizontal rule. There is no trailing `---` after\n * the last hit.\n */\nexport function formatSearchMarkdown(query: string, hits: SearchHit[]): string {\n const header = `# Search results for: ${JSON.stringify(query)}`;\n if (hits.length === 0) {\n return `${header}\\n`;\n }\n\n const blocks = hits.map((hit) => {\n const score = Number.isFinite(hit.score) ? hit.score : 0;\n const heading = `## ${hit.source} (score: ${score.toFixed(3)})`;\n const body = hit.content.trim();\n return `${heading}\\n\\n${body}`;\n });\n\n return `${header}\\n\\n${blocks.join(\"\\n\\n---\\n\\n\")}\\n`;\n}\n\nexport function normalizeScores(hits: SearchHit[]): SearchHit[] {\n if (hits.length === 0) return hits;\n const max = Math.max(...hits.map((h) => h.score));\n if (max <= 0) {\n return hits.map((h, i) => ({\n ...h,\n score: i === 0 ? 1 : 0,\n }));\n }\n return hits.map((h) => ({ ...h, score: h.score / max }));\n}\n\nexport function parseSearchMarkdown(markdown: string): {\n query: string;\n hits: Array<{ source: string; score: number; content: string }>;\n} {\n const queryMatch = markdown.match(/^# Search results for: (.*)$/m);\n if (!queryMatch) {\n throw new Error(\"Not a Search for Agents markdown document\");\n }\n let query = queryMatch[1].trim();\n try {\n query = JSON.parse(query) as string;\n } catch {\n if (\n (query.startsWith('\"') && query.endsWith('\"')) ||\n (query.startsWith(\"'\") && query.endsWith(\"'\"))\n ) {\n query = query.slice(1, -1);\n }\n }\n\n const rest = markdown.slice(queryMatch.index! + queryMatch[0].length).trim();\n if (!rest) return { query, hits: [] };\n\n const chunks = rest.split(/\\n---\\n/);\n const hits = chunks\n .map((chunk) => chunk.trim())\n .filter(Boolean)\n .map((chunk) => {\n const heading = chunk.match(\n /^## (.+) \\(score: ([0-9]+(?:\\.[0-9]+)?)\\)$/m,\n );\n if (!heading) {\n throw new Error(`Invalid result heading in: ${chunk.slice(0, 80)}`);\n }\n const content = chunk.slice(heading[0].length).trim();\n return {\n source: heading[1],\n score: Number(heading[2]),\n content,\n };\n });\n\n return { query, hits };\n}\n","import { MISSING_QUERY_BODY } from \"./types.js\";\n\nexport type ParsedQuery =\n | { ok: true; q: string; method: \"GET\" | \"QUERY\" | \"HEAD\" }\n | { ok: false; status: number; body: string; contentType: string };\n\nfunction isJsonContentType(value: string | null): boolean {\n if (!value) return false;\n return value.toLowerCase().includes(\"application/json\");\n}\n\nfunction isPlainText(value: string | null): boolean {\n if (!value) return true;\n const v = value.toLowerCase();\n return (\n v.includes(\"text/plain\") ||\n v.includes(\"text/markdown\") ||\n v.includes(\"application/x-www-form-urlencoded\")\n );\n}\n\n/**\n * Extract the search text from a GET, HEAD, or QUERY request.\n *\n * Spec (Cloudflare docs + live endpoint):\n * - GET/HEAD: `?q=`\n * - QUERY + `text/plain`: raw UTF-8 body\n * - QUERY + `application/json`: `{ \"q\": \"...\" }`\n *\n * Decision (curl-friendly, not in the written spec): QUERY without a\n * Content-Type, and `application/x-www-form-urlencoded` bodies, are treated\n * as plain text. `curl -X QUERY --data '...'` sends urlencoded by default.\n * Empty or missing `q` returns HTTP 400 with body `Missing query parameter: ?q=`.\n */\nexport async function parseSearchQuery(request: Request): Promise<ParsedQuery> {\n const method = request.method.toUpperCase();\n const url = new URL(request.url);\n const headerQ = request.headers.get(\"x-agent-search-q\");\n\n if (method === \"GET\" || method === \"HEAD\") {\n const q = (headerQ ?? url.searchParams.get(\"q\") ?? \"\").trim();\n if (!q) {\n return {\n ok: false,\n status: 400,\n body: MISSING_QUERY_BODY,\n contentType: \"text/plain; charset=utf-8\",\n };\n }\n return { ok: true, q, method: method === \"HEAD\" ? \"HEAD\" : \"GET\" };\n }\n\n if (method === \"QUERY\") {\n const contentType = request.headers.get(\"content-type\");\n let q = \"\";\n try {\n if (isJsonContentType(contentType)) {\n const json = (await request.json()) as { q?: unknown };\n q = typeof json?.q === \"string\" ? json.q : \"\";\n } else if (isPlainText(contentType)) {\n const raw = await request.text();\n if (\n contentType &&\n contentType.toLowerCase().includes(\"application/x-www-form-urlencoded\")\n ) {\n const params = new URLSearchParams(raw);\n q = (params.get(\"q\") ?? raw).trim();\n } else {\n q = raw.trim();\n }\n } else {\n return {\n ok: false,\n status: 415,\n body: \"Unsupported QUERY content type. Use text/plain or application/json.\",\n contentType: \"text/plain; charset=utf-8\",\n };\n }\n } catch {\n return {\n ok: false,\n status: 400,\n body: MISSING_QUERY_BODY,\n contentType: \"text/plain; charset=utf-8\",\n };\n }\n q = q.trim();\n if (!q) {\n return {\n ok: false,\n status: 400,\n body: MISSING_QUERY_BODY,\n contentType: \"text/plain; charset=utf-8\",\n };\n }\n return { ok: true, q, method: \"QUERY\" };\n }\n\n return {\n ok: false,\n status: 405,\n body: \"Method Not Allowed\",\n contentType: \"text/plain; charset=utf-8\",\n };\n}\n","import {\n ACCEPT_QUERY,\n ALLOW_METHODS,\n MARKDOWN_CONTENT_TYPE,\n PLAIN_CONTENT_TYPE,\n} from \"./types.js\";\n\nexport function searchResponseHeaders(\n extra?: Record<string, string>,\n): Headers {\n const headers = new Headers({\n Allow: ALLOW_METHODS,\n \"Accept-Query\": ACCEPT_QUERY,\n \"X-Content-Type-Options\": \"nosniff\",\n ...extra,\n });\n return headers;\n}\n\nexport function markdownResponse(body: string, status = 200): Response {\n return new Response(body, {\n status,\n headers: searchResponseHeaders({\n \"Content-Type\": MARKDOWN_CONTENT_TYPE,\n }),\n });\n}\n\nexport function plainResponse(body: string, status: number): Response {\n return new Response(body, {\n status,\n headers: searchResponseHeaders({\n \"Content-Type\": PLAIN_CONTENT_TYPE,\n }),\n });\n}\n\nexport function emptyHead(status: number, markdown: boolean): Response {\n return new Response(null, {\n status,\n headers: searchResponseHeaders({\n \"Content-Type\": markdown ? MARKDOWN_CONTENT_TYPE : PLAIN_CONTENT_TYPE,\n }),\n });\n}\n\nexport function methodNotAllowed(): Response {\n return plainResponse(\"Method Not Allowed\", 405);\n}\n\nexport function quotaExceededResponse(): Response {\n return plainResponse(\n \"Query quota exceeded. This site has used its included 1000 queries this month and has no prepaid credit.\",\n 429,\n );\n}\n","import {\n FREE_QUERIES_PER_MONTH,\n type QuotaResult,\n type QuotaStore,\n} from \"./types.js\";\n\nexport function monthKey(date: Date = new Date()): string {\n const year = date.getUTCFullYear();\n const month = String(date.getUTCMonth() + 1).padStart(2, \"0\");\n return `${year}-${month}`;\n}\n\nexport function decideQuota(input: {\n usedFree: number;\n credits: number;\n freeLimit?: number;\n}): QuotaResult {\n const freeLimit = input.freeLimit ?? FREE_QUERIES_PER_MONTH;\n if (input.usedFree < freeLimit) {\n return { ok: true, bucket: \"free\" };\n }\n if (input.credits > 0) {\n return { ok: true, bucket: \"credit\" };\n }\n return {\n ok: false,\n reason: \"exhausted\",\n usedFree: input.usedFree,\n credits: input.credits,\n freeLimit,\n };\n}\n\nexport function prepaidQueriesForUsd(usd: number): number {\n return Math.round((usd / 0.75) * 1000);\n}\n\nexport function usdForPrepaidQueries(queries: number): number {\n return (queries / 1000) * 0.75;\n}\n\n/**\n * In-memory quota store for tests and local single-process demos.\n * Not safe across serverless instances — production uses Postgres.\n */\nexport function createMemoryQuotaStore(options?: {\n freeLimit?: number;\n creditsBySite?: Record<string, number>;\n}): QuotaStore & {\n snapshot(siteId: string): { usedFree: number; credits: number; month: string };\n} {\n const freeLimit = options?.freeLimit ?? FREE_QUERIES_PER_MONTH;\n const used = new Map<string, number>();\n const credits = new Map<string, number>(\n Object.entries(options?.creditsBySite ?? {}),\n );\n const currentMonth = () => monthKey();\n\n return {\n async consume(siteId: string): Promise<QuotaResult> {\n const key = `${siteId}:${currentMonth()}`;\n const usedFree = used.get(key) ?? 0;\n const remainingCredits = credits.get(siteId) ?? 0;\n const decision = decideQuota({\n usedFree,\n credits: remainingCredits,\n freeLimit,\n });\n if (!decision.ok) return decision;\n if (decision.bucket === \"free\") {\n used.set(key, usedFree + 1);\n } else {\n credits.set(siteId, remainingCredits - 1);\n }\n return decision;\n },\n snapshot(siteId: string) {\n return {\n usedFree: used.get(`${siteId}:${currentMonth()}`) ?? 0,\n credits: credits.get(siteId) ?? 0,\n month: currentMonth(),\n };\n },\n };\n}\n","import { RRF_K, type SearchHit } from \"./types.js\";\nimport { normalizeScores } from \"./markdown.js\";\n\nexport function reciprocalRankFusion(\n rankedLists: SearchHit[][],\n k: number = RRF_K,\n): SearchHit[] {\n const scores = new Map<string, { hit: SearchHit; score: number }>();\n\n for (const list of rankedLists) {\n list.forEach((hit, index) => {\n const key = hit.source;\n const add = 1 / (k + index + 1);\n const current = scores.get(key);\n if (current) {\n current.score += add;\n if (hit.content.length > current.hit.content.length) {\n current.hit = hit;\n }\n } else {\n scores.set(key, { hit, score: add });\n }\n });\n }\n\n const fused = [...scores.values()]\n .sort((a, b) => b.score - a.score)\n .map(({ hit, score }) => ({ ...hit, score }));\n\n return normalizeScores(fused);\n}\n","import { parseSearchQuery } from \"./query.js\";\nimport { formatSearchMarkdown } from \"./markdown.js\";\nimport {\n emptyHead,\n markdownResponse,\n methodNotAllowed,\n plainResponse,\n quotaExceededResponse,\n searchResponseHeaders,\n} from \"./headers.js\";\nimport {\n DEFAULT_MATCH_THRESHOLD,\n DEFAULT_MAX_RESULTS,\n type SearchHandlerOptions,\n} from \"./types.js\";\n\nexport async function handleSearchRequest(\n request: Request,\n options: SearchHandlerOptions,\n): Promise<Response> {\n const method = request.method.toUpperCase();\n\n if (method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: searchResponseHeaders(),\n });\n }\n\n if (![\"GET\", \"HEAD\", \"QUERY\"].includes(method)) {\n return methodNotAllowed();\n }\n\n const parsed = await parseSearchQuery(request);\n if (!parsed.ok) {\n if (method === \"HEAD\") {\n return emptyHead(parsed.status, false);\n }\n return plainResponse(parsed.body, parsed.status);\n }\n\n if (options.quota && options.siteId) {\n const quota = await options.quota.consume(options.siteId);\n if (!quota.ok) {\n if (method === \"HEAD\") return emptyHead(429, false);\n return quotaExceededResponse();\n }\n }\n\n const hits = await options.backend.search(parsed.q, {\n limit: options.maxResults ?? DEFAULT_MAX_RESULTS,\n threshold: options.matchThreshold ?? DEFAULT_MATCH_THRESHOLD,\n });\n\n const body = formatSearchMarkdown(parsed.q, hits);\n if (method === \"HEAD\") {\n return emptyHead(200, true);\n }\n return markdownResponse(body, 200);\n}\n","import {\n DEFAULT_DOCUMENTATION,\n DEFAULT_INSTRUCTIONS,\n SEARCH_PATH,\n type AgentDiscovery,\n} from \"./types.js\";\n\nexport function agentDiscovery(options: {\n origin: string;\n documentation?: string;\n instructions?: string;\n}): AgentDiscovery {\n const origin = options.origin.replace(/\\/$/, \"\");\n return {\n instructions: options.instructions ?? DEFAULT_INSTRUCTIONS,\n endpoint: `${origin}${SEARCH_PATH}?q={query}`,\n method: \"GET\",\n documentation: options.documentation ?? DEFAULT_DOCUMENTATION,\n };\n}\n\nexport function agentMetaTags(discovery: AgentDiscovery): string {\n return [\n `<meta name=\"agent:instructions\" content=\"${escapeAttr(discovery.instructions)}\" />`,\n `<meta name=\"agent:endpoint\" content=\"${escapeAttr(discovery.endpoint)}\" />`,\n `<meta name=\"agent:method\" content=\"${escapeAttr(discovery.method)}\" />`,\n `<meta name=\"agent:documentation\" content=\"${escapeAttr(discovery.documentation)}\" />`,\n ].join(\"\\n\");\n}\n\nexport function agentYamlFrontMatter(discovery: AgentDiscovery): string {\n return [\n \"---\",\n \"agent:\",\n ` instructions: ${JSON.stringify(discovery.instructions)}`,\n ` endpoint: ${JSON.stringify(discovery.endpoint)}`,\n ` method: ${JSON.stringify(discovery.method)}`,\n ` documentation: ${JSON.stringify(discovery.documentation)}`,\n \"---\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction escapeAttr(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\");\n}\n"],"mappings":";AAAO,IAAM,cAAc;AAEpB,IAAM,uBACX;AAEK,IAAM,wBACX;AAEK,IAAM,yBAAyB;AAC/B,IAAM,uBAAuB;AAC7B,IAAM,sBAAsB;AAC5B,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAC7B,IAAM,8BAA8B;AACpC,IAAM,QAAQ;AACd,IAAM,8BAA8B;AAEpC,IAAM,gBAAgB;AACtB,IAAM,eAAe;AACrB,IAAM,wBAAwB;AAC9B,IAAM,qBAAqB;AAE3B,IAAM,qBAAqB;;;ACA3B,SAAS,qBAAqB,OAAe,MAA2B;AAC7E,QAAM,SAAS,yBAAyB,KAAK,UAAU,KAAK,CAAC;AAC7D,MAAI,KAAK,WAAW,GAAG;AACrB,WAAO,GAAG,MAAM;AAAA;AAAA,EAClB;AAEA,QAAM,SAAS,KAAK,IAAI,CAAC,QAAQ;AAC/B,UAAM,QAAQ,OAAO,SAAS,IAAI,KAAK,IAAI,IAAI,QAAQ;AACvD,UAAM,UAAU,MAAM,IAAI,MAAM,YAAY,MAAM,QAAQ,CAAC,CAAC;AAC5D,UAAM,OAAO,IAAI,QAAQ,KAAK;AAC9B,WAAO,GAAG,OAAO;AAAA;AAAA,EAAO,IAAI;AAAA,EAC9B,CAAC;AAED,SAAO,GAAG,MAAM;AAAA;AAAA,EAAO,OAAO,KAAK,aAAa,CAAC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AAAA,IACL,cAAc,QAAQ,gBAAgB;AAAA,IACtC,UAAU,GAAG,MAAM,GAAG,WAAW;AAAA,IACjC,QAAQ;AAAA,IACR,eAAe,QAAQ,iBAAiB;AAAA,EAC1C;AACF;AAEO,SAAS,cAAc,WAAmC;AAC/D,SAAO;AAAA,IACL,4CAA4C,WAAW,UAAU,YAAY,CAAC;AAAA,IAC9E,wCAAwC,WAAW,UAAU,QAAQ,CAAC;AAAA,IACtE,sCAAsC,WAAW,UAAU,MAAM,CAAC;AAAA,IAClE,6CAA6C,WAAW,UAAU,aAAa,CAAC;AAAA,EAClF,EAAE,KAAK,IAAI;AACb;AAEO,SAAS,qBAAqB,WAAmC;AACtE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,mBAAmB,KAAK,UAAU,UAAU,YAAY,CAAC;AAAA,IACzD,eAAe,KAAK,UAAU,UAAU,QAAQ,CAAC;AAAA,IACjD,aAAa,KAAK,UAAU,UAAU,MAAM,CAAC;AAAA,IAC7C,oBAAoB,KAAK,UAAU,UAAU,aAAa,CAAC;AAAA,IAC3D;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,SAAS,WAAW,OAAuB;AACzC,SAAO,MACJ,WAAW,KAAK,OAAO,EACvB,WAAW,KAAK,QAAQ,EACxB,WAAW,KAAK,MAAM,EACtB,WAAW,KAAK,MAAM;AAC3B;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@busca-agentes/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Search for Agents spec: Markdown results, GET/QUERY parsing, quota math",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "license": "MIT",
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/ilankriger-gmail/busca-agentes.git",
29
+ "directory": "packages/core"
30
+ },
31
+ "homepage": "https://busca-agentes.com",
32
+ "bugs": {
33
+ "url": "https://github.com/ilankriger-gmail/busca-agentes/issues"
34
+ },
35
+ "scripts": {
36
+ "build": "tsup",
37
+ "typecheck": "tsc --noEmit"
38
+ }
6
39
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.