@parcha/agentrun-web 0.0.0-bootstrap.0 → 0.1.0-beta.57
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 +202 -0
- package/NOTICE +4 -0
- package/README.md +71 -0
- package/dist/fees.d.ts +36 -0
- package/dist/fees.js +41 -0
- package/dist/fetch.d.ts +59 -0
- package/dist/fetch.js +183 -0
- package/dist/guard.d.ts +46 -0
- package/dist/guard.js +3 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +16 -0
- package/dist/page.d.ts +117 -0
- package/dist/page.js +143 -0
- package/dist/providers/direct.d.ts +9 -0
- package/dist/providers/direct.js +53 -0
- package/dist/providers/exa-keyless.d.ts +35 -0
- package/dist/providers/exa-keyless.js +109 -0
- package/dist/providers/firecrawl-keyless.d.ts +40 -0
- package/dist/providers/firecrawl-keyless.js +132 -0
- package/dist/providers/mcp.d.ts +39 -0
- package/dist/providers/mcp.js +107 -0
- package/dist/providers/parallel.d.ts +20 -0
- package/dist/providers/parallel.js +102 -0
- package/dist/search.d.ts +110 -0
- package/dist/search.js +153 -0
- package/dist/text-urls.d.ts +38 -0
- package/dist/text-urls.js +166 -0
- package/dist/web.d.ts +77 -0
- package/dist/web.js +111 -0
- package/package.json +60 -3
package/dist/search.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// web_search's one answer shape (Search), its bounds, and searchInTurn: a call asks its backends in order, each behind
|
|
2
|
+
// a breaker of its own. A quota answer turns a backend off for the breaker's life; a rate limit holds it for the wait it
|
|
3
|
+
// named (60 s when none, 15 min at most). A backend that fails or is held passes the call to the next.
|
|
4
|
+
export const QUERY_MAX = 200;
|
|
5
|
+
export const RESULTS_MAX = 25;
|
|
6
|
+
export const RESULTS_DEFAULT = 10;
|
|
7
|
+
/** The most of a result's text its snippet keeps; Parallel is asked for as much of each result's excerpts. */
|
|
8
|
+
export const SNIPPET_MAX = 3_000;
|
|
9
|
+
/** The most of the provider's own short answer (`text`) a search keeps (serve's hosted-search.ts). */
|
|
10
|
+
export const ANSWER_MAX = 4_000;
|
|
11
|
+
/** The most characters a search's answer takes, its citing line included: about RESULTS_MAX results with whole snippets,
|
|
12
|
+
* under the host's result bound (HOST_RESULT_MAX_CHARS), which the host-bounds test holds it to. */
|
|
13
|
+
export const SEARCH_MAX_CHARS = 100_000;
|
|
14
|
+
/** What every later web_search call of a run answers once its provider said the run is out of quota (a Limit of kind
|
|
15
|
+
* quota): the provider is not asked again in that run. */
|
|
16
|
+
export const SEARCH_UNAVAILABLE = "search is unavailable for the rest of this run; answer from what you have";
|
|
17
|
+
/** What a call answers while a rate limit's wait holds, `seconds` of it left. */
|
|
18
|
+
export const searchBusy = (seconds) => `search is busy; try again in ${seconds} s, or answer from what you have`;
|
|
19
|
+
/** The wait a rate limit holds a run's search for when no Retry-After reaches here. */
|
|
20
|
+
const DEFAULT_WAIT_MS = 60_000;
|
|
21
|
+
/** The longest wait a Retry-After holds a run's search for: 15 minutes. A provider naming hours, or a date far off (a
|
|
22
|
+
* clock that is wrong), would stop a long run's search as a quota answer does; past 15 minutes the next call asks. */
|
|
23
|
+
const MAX_WAIT_MS = 15 * 60_000;
|
|
24
|
+
/** The wait a Retry-After names, in ms from `nowMs` (negative for a date already passed): delta-seconds or an HTTP date,
|
|
25
|
+
* or a number of seconds; undefined when it names neither. The one reading of a Retry-After here. */
|
|
26
|
+
export function retryAfterMs(retryAfter, nowMs) {
|
|
27
|
+
const said = typeof retryAfter === "string" ? retryAfter.trim() : retryAfter;
|
|
28
|
+
const ms = typeof said === "number" ? said * 1_000 : said && /^\d+$/.test(said) ? Number(said) * 1_000 : said ? Date.parse(said) - nowMs : Number.NaN;
|
|
29
|
+
return Number.isFinite(ms) ? ms : undefined;
|
|
30
|
+
}
|
|
31
|
+
/** The wait a breaker holds for `retryAfter` (retryAfterMs): none named, 60 s; a date already passed, none; never more
|
|
32
|
+
* than 15 minutes (MAX_WAIT_MS). */
|
|
33
|
+
export function waitOf(retryAfter, nowMs) {
|
|
34
|
+
const ms = retryAfterMs(retryAfter, nowMs);
|
|
35
|
+
return ms === undefined ? DEFAULT_WAIT_MS : Math.min(Math.max(ms, 0), MAX_WAIT_MS);
|
|
36
|
+
}
|
|
37
|
+
/** `ms` of a wait as searchBusy's seconds: rounded up, at least 1. */
|
|
38
|
+
const busyFor = (ms) => ({ error: searchBusy(Math.max(1, Math.ceil(ms / 1_000))) });
|
|
39
|
+
export function searchBreaker(now = Date.now) {
|
|
40
|
+
let off = false;
|
|
41
|
+
let until = 0;
|
|
42
|
+
// A marked rate limit (keyless Exa's) has opened a wait in this run, with no search succeeding since.
|
|
43
|
+
let marked = false;
|
|
44
|
+
return {
|
|
45
|
+
held() {
|
|
46
|
+
if (off)
|
|
47
|
+
return { error: SEARCH_UNAVAILABLE };
|
|
48
|
+
const left = until - now();
|
|
49
|
+
return left > 0 ? busyFor(left) : undefined;
|
|
50
|
+
},
|
|
51
|
+
off: () => off,
|
|
52
|
+
left: () => Math.max(0, until - now()),
|
|
53
|
+
read({ answer, limit }) {
|
|
54
|
+
if (!("error" in answer))
|
|
55
|
+
marked = false;
|
|
56
|
+
if (limit?.kind === "quota")
|
|
57
|
+
off = true;
|
|
58
|
+
else if (limit) {
|
|
59
|
+
const at = now();
|
|
60
|
+
// The call that turns search off answers so itself, never its limit's "try again" words.
|
|
61
|
+
if (limit.repeatIsQuota && marked && at >= until) {
|
|
62
|
+
off = true;
|
|
63
|
+
return { error: SEARCH_UNAVAILABLE };
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
if (limit.repeatIsQuota)
|
|
67
|
+
marked = true;
|
|
68
|
+
until = Math.max(until, at + waitOf(limit.retryAfter, at));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return answer;
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** The line that ends a search's answer to the model, as Claude Code's WebSearch ends its own. */
|
|
76
|
+
export const CITE = "Cite the URL of each result you rely on.";
|
|
77
|
+
/** `answer` within SEARCH_MAX_CHARS, as searchText writes it: whole when it fits, else without its least relevant results
|
|
78
|
+
* (the last), as many as it takes, `omitted` counting them. */
|
|
79
|
+
export function fitSearch(answer) {
|
|
80
|
+
if ("error" in answer)
|
|
81
|
+
return answer;
|
|
82
|
+
const room = SEARCH_MAX_CHARS - CITE.length - 1;
|
|
83
|
+
let fitted = answer;
|
|
84
|
+
for (let kept = answer.results.length; JSON.stringify(fitted).length > room && kept > 0;) {
|
|
85
|
+
kept -= 1;
|
|
86
|
+
fitted = { ...answer, results: answer.results.slice(0, kept), omitted: answer.results.length - kept };
|
|
87
|
+
}
|
|
88
|
+
return fitted;
|
|
89
|
+
}
|
|
90
|
+
/** A search as the model reads it: its JSON (fitSearch), then the line asking it to cite the URLs it relies on; an
|
|
91
|
+
* error's JSON alone. */
|
|
92
|
+
export function searchText(answer) {
|
|
93
|
+
const fitted = fitSearch(answer);
|
|
94
|
+
return "error" in fitted ? JSON.stringify(fitted) : `${JSON.stringify(fitted)}\n${CITE}`;
|
|
95
|
+
}
|
|
96
|
+
/** A result's text as its snippet: links reduced to their text, whitespace collapsed, cut at SNIPPET_MAX on a word. */
|
|
97
|
+
export function snippetOf(raw) {
|
|
98
|
+
const text = raw.replace(/!?\[([^\]]*)\]\([^)\s]*\)/g, "$1").replace(/\s+/g, " ").trim();
|
|
99
|
+
if (text.length <= SNIPPET_MAX)
|
|
100
|
+
return text;
|
|
101
|
+
const cut = text.slice(0, SNIPPET_MAX - 1);
|
|
102
|
+
const space = cut.lastIndexOf(" ");
|
|
103
|
+
return `${(space > SNIPPET_MAX / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
|
|
104
|
+
}
|
|
105
|
+
/** `{query, n?}` as every provider takes it: the query trimmed and cut at QUERY_MAX, n 1 to RESULTS_MAX. */
|
|
106
|
+
export const searchArgs = (args) => ({
|
|
107
|
+
query: typeof args.query === "string" ? args.query.trim().slice(0, QUERY_MAX) : "",
|
|
108
|
+
n: Math.max(1, Math.min(RESULTS_MAX, Math.floor(Number(args.n) || RESULTS_DEFAULT))),
|
|
109
|
+
});
|
|
110
|
+
/** The most one call of web_search spends across its keyless backends together: Firecrawl's failing or timing out
|
|
111
|
+
* leaves Exa what is left of it, never a fresh bound. Firecrawl's own bound inside it (FIRECRAWL_MS, 30 s) leaves Exa
|
|
112
|
+
* at least the rest. */
|
|
113
|
+
export const KEYLESS_SEARCH_MS = 60_000;
|
|
114
|
+
/** A call's search through `backends` in turn, each behind its breaker, all under one deadline (`boundMs` or `signal`):
|
|
115
|
+
* the first with results answers; none starts on a spent deadline. None left: SEARCH_UNAVAILABLE where every backend is
|
|
116
|
+
* off (a lone backend's own answer where it was asked), else the last failure, else searchBusy for the shortest wait. */
|
|
117
|
+
export async function searchInTurn(backends, breakerOf, signal, boundMs = KEYLESS_SEARCH_MS, tries) {
|
|
118
|
+
const deadline = AbortSignal.any([AbortSignal.timeout(boundMs), ...(signal ? [signal] : [])]);
|
|
119
|
+
let last;
|
|
120
|
+
for (const backend of backends) {
|
|
121
|
+
const breaker = breakerOf(backend.name);
|
|
122
|
+
if (breaker.held()) {
|
|
123
|
+
tries?.push({ provider: backend.name, outcome: "held", ms: 0 });
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (last && deadline.aborted)
|
|
127
|
+
break;
|
|
128
|
+
const started = tries ? performance.now() : 0;
|
|
129
|
+
const searched = await backend.ask(deadline);
|
|
130
|
+
const answer = breaker.read(searched);
|
|
131
|
+
tries?.push({ provider: backend.name, outcome: "error" in answer ? "error" : "ok", ...("error" in answer ? { error: answer.error } : {}), ...(searched.limit ? { limit: searched.limit } : {}), ms: Math.round(performance.now() - started) });
|
|
132
|
+
if (!("error" in answer))
|
|
133
|
+
return answer;
|
|
134
|
+
last = answer;
|
|
135
|
+
}
|
|
136
|
+
const breakers = backends.map((backend) => breakerOf(backend.name));
|
|
137
|
+
if (breakers.every((breaker) => breaker.off()))
|
|
138
|
+
return backends.length === 1 && last ? last : { error: SEARCH_UNAVAILABLE };
|
|
139
|
+
// A backend that turned off in this call while another only waits: the run's search is not off, so it waits.
|
|
140
|
+
if (last && !("error" in last && last.error === SEARCH_UNAVAILABLE))
|
|
141
|
+
return last;
|
|
142
|
+
return busyFor(Math.min(...breakers.filter((breaker) => !breaker.off()).map((breaker) => breaker.left())));
|
|
143
|
+
}
|
|
144
|
+
/** Breakers by backend name, made at first use: one run's (serve's webSearchTool), or one call's (its searchFor). */
|
|
145
|
+
export const breakers = (now = Date.now) => {
|
|
146
|
+
const made = new Map();
|
|
147
|
+
return (name) => {
|
|
148
|
+
let breaker = made.get(name);
|
|
149
|
+
if (!breaker)
|
|
150
|
+
made.set(name, (breaker = searchBreaker(now)));
|
|
151
|
+
return breaker;
|
|
152
|
+
};
|
|
153
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** A URL written in text, as a link is read (a page's links, an answer's cited links): it also ends at "|", so a Slack
|
|
2
|
+
* mrkdwn link `<https://a/b|text>` is `https://a/b`. */
|
|
3
|
+
export declare const TEXT_URL: RegExp;
|
|
4
|
+
/** A URL written in text, as the timeline scrubs one (scrubUrls): it runs on through a "|", so a query value holding one
|
|
5
|
+
* (`?ids=1|2`) is elided whole, never shown past the "|". The scrub's only difference from TEXT_URL. */
|
|
6
|
+
export declare const SCRUBBED_URL: RegExp;
|
|
7
|
+
/** What a URL found in text may end with that is not its own: a sentence's punctuation, a closing quote, an emphasis's
|
|
8
|
+
* "*", a closing bracket the URL did not open (trimmed). */
|
|
9
|
+
export declare const TRAILING = ".,;:!?*)]}'";
|
|
10
|
+
/** A URL found in text less its tail (TRAILING): a closing bracket stays where the URL opened as many as it closes (a wiki
|
|
11
|
+
* title's `Foo_(bar)`). One count of the brackets, then one walk back, so a long run of them is linear. */
|
|
12
|
+
export declare function trimmed(raw: string): string;
|
|
13
|
+
/** Where a markdown link's target (`text` from `from`, the character after its "](") ends: at the ")" that closes the link,
|
|
14
|
+
* so parentheses it holds in pairs (a wiki title's) stay, else at whitespace or `to`. `text[end] === ")"` says it closed. */
|
|
15
|
+
export declare function targetEnd(text: string, from?: number, to?: number): number;
|
|
16
|
+
/** A string that is one URL whole (a JSON field holding a link means all of it, its last character too), trimmed of the
|
|
17
|
+
* whitespace around it; else undefined. */
|
|
18
|
+
export declare function wholeUrl(text: string): string | undefined;
|
|
19
|
+
/** A link as `text` writes it, and whether that is all of it (`exact`): a markdown link's target that its ")" closed is;
|
|
20
|
+
* a URL written out, or a target with no ")", may end in a tail that is not its own (TRAILING). */
|
|
21
|
+
export type WrittenLink = {
|
|
22
|
+
raw: string;
|
|
23
|
+
exact: boolean;
|
|
24
|
+
};
|
|
25
|
+
/** Every link `text` holds, in order, as written (WrittenLink): a markdown link's target (`[text](url)`, targetEnd), and a
|
|
26
|
+
* URL written out (TEXT_URL). A URL written out that runs into a "](" is a link written as its own text
|
|
27
|
+
* (`[https://a](https://a)`): what follows each "](" in it is a target. A target ends where targetEnd says, never where
|
|
28
|
+
* TEXT_URL stopped, so one holding a "|" (`](https://a/?m=1|2)`) is whole. Each link is looked for from where the last
|
|
29
|
+
* one ended, a target read past the URL running into it scanned once more at most: linear, however many unclosed "](" a
|
|
30
|
+
* hostile page holds. A page's links (hrefsIn) and an answer's cited links (link-check.ts) both read it. */
|
|
31
|
+
export declare function linksWritten(text: string): Generator<WrittenLink>;
|
|
32
|
+
/** Every link `text` holds, in order (linksWritten): a target its ")" closed as it is, any other less its tail (trimmed). */
|
|
33
|
+
export declare function hrefsIn(text: string): Generator<string>;
|
|
34
|
+
/** The absolute http(s) URLs a text holds, each once and without its fragment, in order: for JSON, those of its string
|
|
35
|
+
* values (jsonHrefs); for any other text (markdown, plain text, XML), its markdown link targets and the URLs it writes
|
|
36
|
+
* out (hrefsIn), read with its entities undone (readable). A fetched page's links (linksWithin keeps those within the
|
|
37
|
+
* caps and counts the rest), and the urls the link check takes from a call that is not a web call. */
|
|
38
|
+
export declare function linksOf(text: string): Generator<string>;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// The one reading of an http(s) URL written in text, shared by a fetched page's links and serve's timeline scrub and link
|
|
2
|
+
// check. It imports nothing (the console compiles it from source), and every reading is linear in its text.
|
|
3
|
+
/** What ends a URL written in text, for every reader: whitespace, a quote, an angle bracket, a backtick or a backslash. */
|
|
4
|
+
const URL_ENDS = "\\s\"`<>\\\\";
|
|
5
|
+
/** A URL written in text, as a link is read (a page's links, an answer's cited links): it also ends at "|", so a Slack
|
|
6
|
+
* mrkdwn link `<https://a/b|text>` is `https://a/b`. */
|
|
7
|
+
export const TEXT_URL = new RegExp(`https?://[^${URL_ENDS}|]+`, "gi");
|
|
8
|
+
/** A URL written in text, as the timeline scrubs one (scrubUrls): it runs on through a "|", so a query value holding one
|
|
9
|
+
* (`?ids=1|2`) is elided whole, never shown past the "|". The scrub's only difference from TEXT_URL. */
|
|
10
|
+
export const SCRUBBED_URL = new RegExp(`https?://[^${URL_ENDS}]+`, "gi");
|
|
11
|
+
/** What a URL found in text may end with that is not its own: a sentence's punctuation, a closing quote, an emphasis's
|
|
12
|
+
* "*", a closing bracket the URL did not open (trimmed). */
|
|
13
|
+
export const TRAILING = ".,;:!?*)]}'";
|
|
14
|
+
const OPENER = { ")": "(", "]": "[", "}": "{" };
|
|
15
|
+
/** A URL found in text less its tail (TRAILING): a closing bracket stays where the URL opened as many as it closes (a wiki
|
|
16
|
+
* title's `Foo_(bar)`). One count of the brackets, then one walk back, so a long run of them is linear. */
|
|
17
|
+
export function trimmed(raw) {
|
|
18
|
+
const count = { "(": 0, ")": 0, "[": 0, "]": 0, "{": 0, "}": 0 };
|
|
19
|
+
for (const char of raw)
|
|
20
|
+
if (char in count)
|
|
21
|
+
count[char] += 1;
|
|
22
|
+
let end = raw.length;
|
|
23
|
+
for (; end > 0 && TRAILING.includes(raw[end - 1]); end--) {
|
|
24
|
+
const char = raw[end - 1];
|
|
25
|
+
const opener = OPENER[char];
|
|
26
|
+
if (opener && count[opener] >= count[char])
|
|
27
|
+
break;
|
|
28
|
+
if (opener)
|
|
29
|
+
count[char] -= 1;
|
|
30
|
+
}
|
|
31
|
+
return raw.slice(0, end);
|
|
32
|
+
}
|
|
33
|
+
/** Where a markdown link's target (`text` from `from`, the character after its "](") ends: at the ")" that closes the link,
|
|
34
|
+
* so parentheses it holds in pairs (a wiki title's) stay, else at whitespace or `to`. `text[end] === ")"` says it closed. */
|
|
35
|
+
export function targetEnd(text, from = 0, to = text.length) {
|
|
36
|
+
let end = from;
|
|
37
|
+
for (let depth = 0; end < to && !/\s/.test(text[end]); end++) {
|
|
38
|
+
if (text[end] === "(")
|
|
39
|
+
depth++;
|
|
40
|
+
else if (text[end] === ")" && depth-- === 0)
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
return end;
|
|
44
|
+
}
|
|
45
|
+
/** Where a markdown target in angle brackets (`text` from `from`, the character after its "<") ends: the index of its ">",
|
|
46
|
+
* or -1 where whitespace, another "<" or `to` comes first (no such target: read it as targetEnd does). */
|
|
47
|
+
function angledEnd(text, from, to) {
|
|
48
|
+
for (let end = from; end < to && !/[\s<]/.test(text[end]); end++)
|
|
49
|
+
if (text[end] === ">")
|
|
50
|
+
return end;
|
|
51
|
+
return -1;
|
|
52
|
+
}
|
|
53
|
+
/** A string that is one URL whole (a JSON field holding a link means all of it, its last character too), trimmed of the
|
|
54
|
+
* whitespace around it; else undefined. */
|
|
55
|
+
export function wholeUrl(text) {
|
|
56
|
+
const whole = text.trim();
|
|
57
|
+
return /^https?:\/\//i.test(whole) && !/\s/.test(whole) ? whole : undefined;
|
|
58
|
+
}
|
|
59
|
+
/** Where a link starts: a markdown link's target (after its "]("), or a URL written out (TEXT_URL). */
|
|
60
|
+
const LINK_AT = new RegExp(`\\]\\(|${TEXT_URL.source}`, "gi");
|
|
61
|
+
/** Every link `text` holds, in order, as written (WrittenLink): a markdown link's target (`[text](url)`, targetEnd), and a
|
|
62
|
+
* URL written out (TEXT_URL). A URL written out that runs into a "](" is a link written as its own text
|
|
63
|
+
* (`[https://a](https://a)`): what follows each "](" in it is a target. A target ends where targetEnd says, never where
|
|
64
|
+
* TEXT_URL stopped, so one holding a "|" (`](https://a/?m=1|2)`) is whole. Each link is looked for from where the last
|
|
65
|
+
* one ended, a target read past the URL running into it scanned once more at most: linear, however many unclosed "](" a
|
|
66
|
+
* hostile page holds. A page's links (hrefsIn) and an answer's cited links (link-check.ts) both read it. */
|
|
67
|
+
export function* linksWritten(text) {
|
|
68
|
+
const at = new RegExp(LINK_AT.source, "gi");
|
|
69
|
+
for (let found = at.exec(text); found; found = at.exec(text)) {
|
|
70
|
+
// A "](" alone is ["", ""]: one target, after it.
|
|
71
|
+
const pieces = found[0].split("](");
|
|
72
|
+
if (pieces[0])
|
|
73
|
+
yield { raw: pieces[0], exact: false };
|
|
74
|
+
let from = found.index + pieces[0].length + 2;
|
|
75
|
+
for (let i = 1; i < pieces.length; i++) {
|
|
76
|
+
// Each target but the last ends by the next "](" in the URL; the last may run on past where TEXT_URL stopped.
|
|
77
|
+
const to = i < pieces.length - 1 ? from + pieces[i].length : text.length;
|
|
78
|
+
// A target in angle brackets (CommonMark's `](<https://a/b>)`) is what they hold, its ">" its end.
|
|
79
|
+
const angled = text[from] === "<" ? angledEnd(text, from + 1, to) : -1;
|
|
80
|
+
const end = angled >= 0 ? angled : targetEnd(text, from, to);
|
|
81
|
+
yield angled >= 0 ? { raw: text.slice(from + 1, angled), exact: true } : { raw: text.slice(from, end), exact: text[end] === ")" };
|
|
82
|
+
at.lastIndex = Math.max(at.lastIndex, end);
|
|
83
|
+
from += pieces[i].length + 2;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** Every link `text` holds, in order (linksWritten): a target its ")" closed as it is, any other less its tail (trimmed). */
|
|
88
|
+
export function* hrefsIn(text) {
|
|
89
|
+
for (const { raw, exact } of linksWritten(text))
|
|
90
|
+
yield exact ? raw : trimmed(raw);
|
|
91
|
+
}
|
|
92
|
+
/** The entities XML names (`'` HTML's `'` too, a numeric reference), undone once in a text that is not JSON. */
|
|
93
|
+
const ENTITY = /&(?:(quot|amp|lt|gt|apos)|#(\d{1,7})|#x([0-9a-f]{1,6}));/gi;
|
|
94
|
+
const NAMED = { quot: '"', amp: "&", lt: "<", gt: ">", apos: "'" };
|
|
95
|
+
/** An XML attribute: its name, and its value in double quotes (kept as it is, so an "='" in its query is never taken for
|
|
96
|
+
* an attribute) or in single quotes (the fourth group). */
|
|
97
|
+
const ATTRIBUTE = /(\s)([^\s=<>"'/]+)(\s*=\s*)(?:"[^"]*"|'([^'<]*)')/g;
|
|
98
|
+
/** `text` read for its links, where it is not JSON: its entities undone once, so an escaped `<a href="…">`
|
|
99
|
+
* (an Atom feed's content) ends its URL at the quote, never running on to the next space, and an attribute's
|
|
100
|
+
* `href="https://a/?x=1&y=2"` is the URL `https://a/?x=1&y=2`. One pass, so `&lt;` is `<`. Where it is XML,
|
|
101
|
+
* first: a single-quoted attribute (`href='https://a/b'`) is requoted to end at its quote as a double-quoted one does (its
|
|
102
|
+
* value holds no "'" or "<" of its own), and a namespace's name (`xmlns="http://www.w3.org/2005/Atom"`), an identifier,
|
|
103
|
+
* never a link, is dropped. Attributes are read in order, each whole. */
|
|
104
|
+
function readable(text) {
|
|
105
|
+
const xml = /^\s*<[?!A-Za-z]/.test(text)
|
|
106
|
+
? text.replace(ATTRIBUTE, (attribute, space, name, equals, single) => {
|
|
107
|
+
if (/^xmlns(:|$)/i.test(name))
|
|
108
|
+
return space;
|
|
109
|
+
return single === undefined ? attribute : `${space}${name}${equals}"${single}"`;
|
|
110
|
+
})
|
|
111
|
+
: text;
|
|
112
|
+
return xml.replace(ENTITY, (entity, name, decimal, hex) => {
|
|
113
|
+
if (name)
|
|
114
|
+
return NAMED[name.toLowerCase()];
|
|
115
|
+
const code = Number.parseInt(decimal ?? hex, decimal ? 10 : 16);
|
|
116
|
+
return code <= 0x10ffff ? String.fromCodePoint(code) : entity;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
/** A JSON body's links as written, in the body's order: each string value's (hrefsIn), one that is a URL whole taken as
|
|
120
|
+
* it is (wholeUrl); undefined for a text that is not JSON. Read from the parsed body, so an escape (`\/`) never hides or
|
|
121
|
+
* cuts one. */
|
|
122
|
+
function jsonHrefs(text) {
|
|
123
|
+
// An object, an array or one string: the bodies that can hold a URL (a string body is one, or holds some).
|
|
124
|
+
if (!/^\s*[[{"]/.test(text))
|
|
125
|
+
return undefined;
|
|
126
|
+
let body;
|
|
127
|
+
try {
|
|
128
|
+
body = JSON.parse(text);
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
return (function* () {
|
|
134
|
+
// A stack, not recursion: a deeply nested body never overflows it.
|
|
135
|
+
const stack = [body];
|
|
136
|
+
while (stack.length) {
|
|
137
|
+
const next = stack.pop();
|
|
138
|
+
if (typeof next === "string") {
|
|
139
|
+
const whole = wholeUrl(next);
|
|
140
|
+
yield* whole === undefined ? hrefsIn(next) : [whole];
|
|
141
|
+
}
|
|
142
|
+
else if (typeof next === "object" && next !== null) {
|
|
143
|
+
const values = Object.values(next);
|
|
144
|
+
for (let i = values.length - 1; i >= 0; i--)
|
|
145
|
+
stack.push(values[i]);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
})();
|
|
149
|
+
}
|
|
150
|
+
/** The absolute http(s) URLs a text holds, each once and without its fragment, in order: for JSON, those of its string
|
|
151
|
+
* values (jsonHrefs); for any other text (markdown, plain text, XML), its markdown link targets and the URLs it writes
|
|
152
|
+
* out (hrefsIn), read with its entities undone (readable). A fetched page's links (linksWithin keeps those within the
|
|
153
|
+
* caps and counts the rest), and the urls the link check takes from a call that is not a web call. */
|
|
154
|
+
export function* linksOf(text) {
|
|
155
|
+
const seen = new Set();
|
|
156
|
+
for (const href of jsonHrefs(text) ?? hrefsIn(readable(text))) {
|
|
157
|
+
const link = /^https?:\/\//i.test(href) ? URL.parse(href) : null;
|
|
158
|
+
if (!link)
|
|
159
|
+
continue;
|
|
160
|
+
link.hash = "";
|
|
161
|
+
if (seen.has(link.href))
|
|
162
|
+
continue;
|
|
163
|
+
seen.add(link.href);
|
|
164
|
+
yield link.href;
|
|
165
|
+
}
|
|
166
|
+
}
|
package/dist/web.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type WebLog, type FetchProvider, type WebPage } from "./fetch.js";
|
|
2
|
+
import { type Fee, type Pay } from "./fees.js";
|
|
3
|
+
import type { Guard, GuardOptions } from "./guard.js";
|
|
4
|
+
import { type Page, type Part } from "./page.js";
|
|
5
|
+
import type { Words } from "./providers/mcp.js";
|
|
6
|
+
import { type Breaker, type Search, type SearchBounds, type Searched, type Try } from "./search.js";
|
|
7
|
+
export type ProviderId = "parallel" | "firecrawl-keyless" | "exa-keyless" | "native" | "direct";
|
|
8
|
+
export type SearchProvider = Exclude<ProviderId, "direct">;
|
|
9
|
+
/** The run's own model provider's hosted search. `signal` is the caller's; it keeps its own bounds. */
|
|
10
|
+
export type NativeSearch = (query: string, n: number, signal?: AbortSignal) => Promise<Searched>;
|
|
11
|
+
/** What an answer took and cost. `out` is the answer as the model reads it; `cache` is "hit" when a fetch came from the
|
|
12
|
+
* run's pages. */
|
|
13
|
+
export type Receipt = {
|
|
14
|
+
op: "search" | "fetch";
|
|
15
|
+
asked: string;
|
|
16
|
+
provider: ProviderId | null;
|
|
17
|
+
tries: Try[];
|
|
18
|
+
classifier: "off";
|
|
19
|
+
wall: {
|
|
20
|
+
verdict: "unjudged";
|
|
21
|
+
};
|
|
22
|
+
injection: "unjudged";
|
|
23
|
+
out: {
|
|
24
|
+
bytes: number;
|
|
25
|
+
chars: number;
|
|
26
|
+
};
|
|
27
|
+
cost: {
|
|
28
|
+
usd: number;
|
|
29
|
+
lines: Fee[];
|
|
30
|
+
};
|
|
31
|
+
cache?: "hit";
|
|
32
|
+
};
|
|
33
|
+
/** `order.fetch` names the providers ahead of the direct fetch ("direct" in it). No `keys.parallel`: Parallel answers
|
|
34
|
+
* that the run holds none. No `guard`: nothing is fetched directly and no URL goes to a provider. No `pay`: unmetered. */
|
|
35
|
+
export type WebConfig = {
|
|
36
|
+
order: {
|
|
37
|
+
search: readonly SearchProvider[];
|
|
38
|
+
fetch: readonly FetchProvider[];
|
|
39
|
+
};
|
|
40
|
+
keys?: {
|
|
41
|
+
parallel?: string;
|
|
42
|
+
};
|
|
43
|
+
native?: NativeSearch;
|
|
44
|
+
guard?: Guard;
|
|
45
|
+
pay?: Pay;
|
|
46
|
+
endpoints?: {
|
|
47
|
+
"firecrawl-keyless"?: string;
|
|
48
|
+
};
|
|
49
|
+
send?: Partial<Record<"parallel" | "firecrawl-keyless" | "exa-keyless", typeof fetch>>;
|
|
50
|
+
words?: Words;
|
|
51
|
+
now?: () => number;
|
|
52
|
+
bounds?: SearchBounds & {
|
|
53
|
+
checkMs?: number;
|
|
54
|
+
};
|
|
55
|
+
log?: WebLog;
|
|
56
|
+
};
|
|
57
|
+
/** `breakers`: the search breakers this call reads and trips (default the Web's own). `bounds`: this call's deadlines,
|
|
58
|
+
* each in place of the Web's (WebConfig.bounds) where given. */
|
|
59
|
+
export type SearchOptions = {
|
|
60
|
+
n?: number;
|
|
61
|
+
signal?: AbortSignal;
|
|
62
|
+
breakers?: (name: string) => Breaker;
|
|
63
|
+
bounds?: SearchBounds;
|
|
64
|
+
};
|
|
65
|
+
/** `lookup` and `fetchImpl`: the resolver and transport this call's guard dials through. */
|
|
66
|
+
export type FetchOptions = Part & GuardOptions;
|
|
67
|
+
export type Web = {
|
|
68
|
+
search(query: string, options?: SearchOptions): Promise<{
|
|
69
|
+
answer: Search;
|
|
70
|
+
receipt: Receipt;
|
|
71
|
+
}>;
|
|
72
|
+
fetch(url: unknown, options?: FetchOptions): Promise<{
|
|
73
|
+
answer: WebPage | Page;
|
|
74
|
+
receipt: Receipt;
|
|
75
|
+
}>;
|
|
76
|
+
};
|
|
77
|
+
export declare function createWeb(config: WebConfig): Web;
|
package/dist/web.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// One run's web search and fetch (createWeb). The providers asked are data (WebConfig.order); everything from outside
|
|
2
|
+
// comes in through the config. Every answer comes with a Receipt, which is never put in front of the model.
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
import { webFetch, webFetchText } from "./fetch.js";
|
|
5
|
+
import { unmetered } from "./fees.js";
|
|
6
|
+
import { askedUrl, partProblem } from "./page.js";
|
|
7
|
+
import { exaLimitOf, exaSearch } from "./providers/exa-keyless.js";
|
|
8
|
+
import { firecrawlFetch, firecrawlSearch } from "./providers/firecrawl-keyless.js";
|
|
9
|
+
import { parallelExtract, parallelSearched } from "./providers/parallel.js";
|
|
10
|
+
import { breakers, fitSearch, searchArgs, searchInTurn, searchText } from "./search.js";
|
|
11
|
+
/** The fees of the requests sent within one call. */
|
|
12
|
+
const feesOfCall = new AsyncLocalStorage();
|
|
13
|
+
const usd = (lines) => Math.round(lines.reduce((sum, fee) => sum + fee.usd, 0) * 1e6) / 1e6;
|
|
14
|
+
const outOf = (text) => ({ bytes: Buffer.byteLength(text), chars: text.length });
|
|
15
|
+
const judged = { classifier: "off", wall: { verdict: "unjudged" }, injection: "unjudged" };
|
|
16
|
+
/** A provider's failure: the error alone for the model, the limit it met for the breaker. */
|
|
17
|
+
const failedWith = (error, limit) => ({ answer: { error }, ...(limit ? { limit } : {}) });
|
|
18
|
+
export function createWeb(config) {
|
|
19
|
+
const now = config.now ?? Date.now;
|
|
20
|
+
const runBreakers = breakers(now);
|
|
21
|
+
const pages = new Map();
|
|
22
|
+
// A fee goes on the call's receipt once its request is sent, whatever the cap then books.
|
|
23
|
+
const pay = (fee, send) => (config.pay ?? unmetered)(fee, () => (feesOfCall.getStore()?.push(fee), send()));
|
|
24
|
+
const firecrawl = {};
|
|
25
|
+
const exa = {};
|
|
26
|
+
if (config.endpoints?.["firecrawl-keyless"])
|
|
27
|
+
firecrawl.endpoint = config.endpoints["firecrawl-keyless"];
|
|
28
|
+
if (config.send?.["firecrawl-keyless"])
|
|
29
|
+
firecrawl.send = config.send["firecrawl-keyless"];
|
|
30
|
+
if (config.send?.["exa-keyless"])
|
|
31
|
+
exa.send = config.send["exa-keyless"];
|
|
32
|
+
if (config.words)
|
|
33
|
+
firecrawl.words = exa.words = config.words;
|
|
34
|
+
let parallel;
|
|
35
|
+
const parallelOf = () => (parallel ??= config.keys?.parallel === undefined ? null : parallelExtract(config.keys.parallel, config.send?.parallel ?? fetch, pay));
|
|
36
|
+
let keyless;
|
|
37
|
+
const firecrawlOf = () => (keyless ??= firecrawlFetch(firecrawl, now));
|
|
38
|
+
const backendOf = (name, args, signal, firecrawlSearchMs) => {
|
|
39
|
+
const { query, n } = searchArgs(args);
|
|
40
|
+
if (name === "parallel")
|
|
41
|
+
return { name, ask: () => parallelSearched(args, parallelOf(), signal) };
|
|
42
|
+
if (name === "native")
|
|
43
|
+
return { name, ask: async () => (config.native ? config.native(query, n, signal) : { answer: { error: "web_search: no native search was given" } }) };
|
|
44
|
+
if (name === "firecrawl-keyless") {
|
|
45
|
+
return { name, ask: async (deadline) => {
|
|
46
|
+
const found = await firecrawlSearch(query, n, { ...firecrawl, signal: deadline, ...(firecrawlSearchMs === undefined ? {} : { timeoutMs: firecrawlSearchMs }) });
|
|
47
|
+
// Which limit Firecrawl met is the breaker's to read, never the model's.
|
|
48
|
+
return "error" in found ? failedWith(found.error, "limit" in found ? found.limit : undefined) : { answer: found };
|
|
49
|
+
} };
|
|
50
|
+
}
|
|
51
|
+
return { name, ask: async (deadline) => {
|
|
52
|
+
const found = await exaSearch(query, n, { ...exa, signal: deadline });
|
|
53
|
+
return "limit" in found ? failedWith(found.error, exaLimitOf(found)) : { answer: found };
|
|
54
|
+
} };
|
|
55
|
+
};
|
|
56
|
+
return {
|
|
57
|
+
async search(query, { n, signal, breakers: breakerOf = runBreakers, bounds } = {}) {
|
|
58
|
+
const lines = [];
|
|
59
|
+
const tries = [];
|
|
60
|
+
const args = { query, ...(n === undefined ? {} : { n }) };
|
|
61
|
+
const order = config.order.search;
|
|
62
|
+
const searchMs = bounds?.searchMs ?? config.bounds?.searchMs;
|
|
63
|
+
const firecrawlMs = bounds?.firecrawlMs ?? config.bounds?.firecrawlMs;
|
|
64
|
+
// Parallel's search answers an empty query itself; every other provider is asked only with one.
|
|
65
|
+
const found = !order.includes("parallel") && !searchArgs(args).query ? { error: "web_search needs a query" }
|
|
66
|
+
: !order.length ? { error: "web_search has no provider to ask" }
|
|
67
|
+
: await feesOfCall.run(lines, () => searchInTurn(order.map((name) => backendOf(name, args, signal, firecrawlMs)), breakerOf, signal, searchMs, tries));
|
|
68
|
+
const answer = fitSearch(found);
|
|
69
|
+
const receipt = { op: "search", asked: query, provider: "error" in answer ? null : answer.provider, tries, ...judged, out: outOf(searchText(answer)), cost: { usd: usd(lines), lines } };
|
|
70
|
+
return { answer, receipt };
|
|
71
|
+
},
|
|
72
|
+
// Only the call's part, resolver, transport and signal are read: the guard, its bound and the order stay the Web's.
|
|
73
|
+
async fetch(url, { offset, maxChars, lookup, fetchImpl, signal } = {}) {
|
|
74
|
+
const asked = typeof url === "string" ? url : "";
|
|
75
|
+
const lines = [];
|
|
76
|
+
const tries = [];
|
|
77
|
+
// A part a call may not ask for is refused before anything is fetched.
|
|
78
|
+
const problem = partProblem({ offset, maxChars });
|
|
79
|
+
if (problem) {
|
|
80
|
+
const refused = { ok: false, url: askedUrl(asked), status: 0, title: "", text: "", links: [], error: problem };
|
|
81
|
+
return { answer: refused, receipt: { op: "fetch", asked, provider: null, tries, ...judged, out: outOf(webFetchText(refused)), cost: { usd: 0, lines } } };
|
|
82
|
+
}
|
|
83
|
+
const cached = typeof url === "string" && pages.has(url);
|
|
84
|
+
const order = config.order.fetch;
|
|
85
|
+
const extract = order.includes("parallel") ? parallelOf() : null;
|
|
86
|
+
const page = await feesOfCall.run(lines, () => webFetch(url, {
|
|
87
|
+
...(lookup ? { lookup } : {}),
|
|
88
|
+
...(fetchImpl ? { fetchImpl } : {}),
|
|
89
|
+
...(signal ? { signal } : {}),
|
|
90
|
+
parallel: extract,
|
|
91
|
+
firecrawl: order.includes("firecrawl-keyless") ? firecrawlOf() : null,
|
|
92
|
+
pages,
|
|
93
|
+
order,
|
|
94
|
+
...(config.guard ? { guard: config.guard } : {}),
|
|
95
|
+
...(config.bounds?.checkMs === undefined ? {} : { checkMs: config.bounds.checkMs }),
|
|
96
|
+
...(offset === undefined ? {} : { offset }),
|
|
97
|
+
...(maxChars === undefined ? {} : { maxChars }),
|
|
98
|
+
...(config.log ? { log: config.log } : {}),
|
|
99
|
+
// Each provider the read asks, told as it answers: Firecrawl failing ahead of Parallel's page, or with nothing behind it, too.
|
|
100
|
+
tried: (one) => void tries.push(one),
|
|
101
|
+
...(order.includes("parallel") && !extract ? { noParallel: "not tried: this run holds no Parallel key" } : {}),
|
|
102
|
+
}));
|
|
103
|
+
const answer = page;
|
|
104
|
+
const provider = answer.ok && answer.via !== "stopped" && answer.via !== "none" ? answer.via : null;
|
|
105
|
+
// Copies: a read this call stopped waiting for goes on, and its later turns and fees are not on this receipt.
|
|
106
|
+
const spent = [...lines];
|
|
107
|
+
const receipt = { op: "fetch", asked, provider, tries: [...tries], ...judged, out: outOf(webFetchText(answer)), cost: { usd: usd(spent), lines: spent }, ...(cached ? { cache: "hit" } : {}) };
|
|
108
|
+
return { answer, receipt };
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-web",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0-beta.57",
|
|
4
|
+
"description": "Web search and web fetch for agents: providers asked in an order given as data, a breaker per provider, a per-run page cache read in parts, and a direct fetch through an injected public-host guard.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"agentrun",
|
|
7
|
+
"web-search",
|
|
8
|
+
"web-fetch",
|
|
9
|
+
"parallel",
|
|
10
|
+
"firecrawl",
|
|
11
|
+
"exa"
|
|
12
|
+
],
|
|
13
|
+
"type": "module",
|
|
5
14
|
"license": "Apache-2.0",
|
|
6
|
-
"
|
|
15
|
+
"author": "Parcha Labs, Inc.",
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=24.22.3"
|
|
18
|
+
},
|
|
19
|
+
"main": "./dist/index.js",
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./text-urls": {
|
|
27
|
+
"types": "./dist/text-urls.d.ts",
|
|
28
|
+
"default": "./dist/text-urls.js"
|
|
29
|
+
},
|
|
30
|
+
"./package.json": "./package.json"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE",
|
|
36
|
+
"NOTICE"
|
|
37
|
+
],
|
|
38
|
+
"sideEffects": false,
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "rm -rf dist && tsc -p tsconfig.json",
|
|
41
|
+
"prepack": "npm run build",
|
|
42
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
43
|
+
"test": "node --test --test-concurrency=8 'test/*.test.mjs'"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"undici": "^8.12.2"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@parcha/pi-browser": "0.1.0-beta.57"
|
|
50
|
+
},
|
|
51
|
+
"repository": {
|
|
52
|
+
"type": "git",
|
|
53
|
+
"url": "git+https://github.com/Parcha-ai/agentrun.git",
|
|
54
|
+
"directory": "packages/web"
|
|
55
|
+
},
|
|
56
|
+
"bugs": {
|
|
57
|
+
"url": "https://github.com/Parcha-ai/agentrun/issues"
|
|
58
|
+
},
|
|
59
|
+
"homepage": "https://agentrun.ai",
|
|
60
|
+
"publishConfig": {
|
|
61
|
+
"access": "public",
|
|
62
|
+
"tag": "beta"
|
|
63
|
+
}
|
|
7
64
|
}
|