@herbertgao/pi-extensions 2026.10.14 → 2026.10.15
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/README.md +8 -6
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/node_modules/@narumitw/pi-btw/README.md +1 -1
- package/node_modules/@narumitw/pi-btw/dist/index.ts +77 -64
- package/node_modules/@narumitw/pi-btw/dist/index.ts.map +2 -2
- package/node_modules/@narumitw/pi-btw/docs/core-alignment.md +10 -2
- package/node_modules/@narumitw/pi-btw/package.json +5 -5
- package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +83 -63
- package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
- package/node_modules/pi-web-access/CHANGELOG.md +40 -0
- package/node_modules/pi-web-access/README.md +96 -22
- package/node_modules/pi-web-access/brave-rate-limit.ts +2 -2
- package/node_modules/pi-web-access/curator-page.ts +3 -1
- package/node_modules/pi-web-access/curator-server.ts +1 -0
- package/node_modules/pi-web-access/dist/index.js +2607 -1674
- package/node_modules/pi-web-access/dist/mcp-cli.js +1119 -327
- package/node_modules/pi-web-access/duckduckgo-rate-limit.ts +95 -0
- package/node_modules/pi-web-access/duckduckgo.ts +51 -45
- package/node_modules/pi-web-access/exa.ts +48 -6
- package/node_modules/pi-web-access/extract.ts +2 -2
- package/node_modules/pi-web-access/fetch-params.ts +5 -4
- package/node_modules/pi-web-access/field-extract.ts +347 -0
- package/node_modules/pi-web-access/gemini-search.ts +151 -13
- package/node_modules/pi-web-access/index.ts +128 -125
- package/node_modules/pi-web-access/mistral-search.ts +1 -1
- package/node_modules/pi-web-access/ninerouter.ts +92 -0
- package/node_modules/pi-web-access/offtopic-judge.ts +72 -0
- package/node_modules/pi-web-access/openai-search.ts +36 -10
- package/node_modules/pi-web-access/package.json +1 -1
- package/node_modules/pi-web-access/perplexity.ts +1 -0
- package/node_modules/pi-web-access/query-rewrite.ts +39 -13
- package/node_modules/pi-web-access/source-check.ts +31 -15
- package/node_modules/pi-web-access/summary-model-scope.ts +19 -1
- package/node_modules/pi-web-access/summary-review.ts +13 -20
- package/node_modules/pi-web-access/tool-arguments.ts +1 -1
- package/node_modules/pi-web-access/upgrade-notice.ts +47 -0
- package/node_modules/pi-web-access/utils.ts +26 -1
- package/node_modules/pi-web-access/web-tool-contract.ts +4 -1
- package/node_modules/pi-web-access/web-tool-core.ts +99 -19
- package/node_modules/pi-web-access/xai-search.ts +3 -3
- package/package.json +6 -6
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
// fetch_content mode "extract": typed values read from a fetched page by Cloudflare's Clairic model.
|
|
2
|
+
import type { JsonValue } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { redactCredential } from "./credential-source.ts";
|
|
5
|
+
import { fetchWithCredentialRedirects, isRecord } from "./utils.ts";
|
|
6
|
+
|
|
7
|
+
const MAX_FIELDS = 16;
|
|
8
|
+
const MAX_PAGE_CHARS = 200_000;
|
|
9
|
+
// Measured on the extraction fixtures: no wrong value reached 0.80, so lower confidence is shown only as a guess.
|
|
10
|
+
const EXTRACT_THRESHOLD = 0.8;
|
|
11
|
+
const TIMEOUT_MS = 30_000;
|
|
12
|
+
const DURATION_UNITS = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
|
|
13
|
+
|
|
14
|
+
type ItemType = "text" | "number" | "date";
|
|
15
|
+
interface FieldSpec {
|
|
16
|
+
type: "text" | "number" | "date" | "time" | "datetime" | "duration" | "list";
|
|
17
|
+
integer?: true;
|
|
18
|
+
unit?: string;
|
|
19
|
+
items?: ItemType;
|
|
20
|
+
instructions?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type FieldResult =
|
|
24
|
+
| { status: "extracted"; value: JsonValue; confidence: number; line?: string }
|
|
25
|
+
| { status: "uncertain"; guess: JsonValue; confidence?: number; line?: string; notFound?: true }
|
|
26
|
+
| { status: "null" };
|
|
27
|
+
|
|
28
|
+
export type PageExtraction =
|
|
29
|
+
| { fields: Record<string, FieldResult>; cut: boolean }
|
|
30
|
+
| { error: string };
|
|
31
|
+
|
|
32
|
+
export function parseExtractFields(fields: unknown): Record<string, FieldSpec> {
|
|
33
|
+
if (!isRecord(fields)) throw new Error("fields must be an object mapping names to types");
|
|
34
|
+
const entries = Object.entries(fields);
|
|
35
|
+
if (entries.length === 0 || entries.length > MAX_FIELDS) throw new Error(`fields must list 1 to ${MAX_FIELDS} fields`);
|
|
36
|
+
// No prototype, so a field named "__proto__" or "constructor" is an ordinary key.
|
|
37
|
+
const specs: Record<string, FieldSpec> = Object.create(null);
|
|
38
|
+
for (const [name, raw] of entries) {
|
|
39
|
+
if (!/^[A-Za-z0-9_]{1,64}$/.test(name)) throw new Error(`field name "${name}" must be 1 to 64 letters, digits, or underscores`);
|
|
40
|
+
if (typeof raw !== "string") throw new Error(`field ${name} must be a string such as "number" or "date: when it ships"`);
|
|
41
|
+
const colon = raw.indexOf(":");
|
|
42
|
+
const type = (colon === -1 ? raw : raw.slice(0, colon)).trim();
|
|
43
|
+
const instructions = colon === -1 ? "" : raw.slice(colon + 1).trim();
|
|
44
|
+
const [base, sub, extra] = type.split(".");
|
|
45
|
+
let spec: FieldSpec | undefined;
|
|
46
|
+
if (sub === undefined && ["text", "number", "date", "time", "datetime", "duration"].includes(base)) spec = { type: base as FieldSpec["type"] };
|
|
47
|
+
else if (sub === undefined && base === "integer") spec = { type: "number", integer: true };
|
|
48
|
+
else if (sub === undefined && base === "list") spec = { type: "list", items: "text" };
|
|
49
|
+
else if (base === "duration" && DURATION_UNITS.includes(sub)) spec = { type: "duration", unit: sub };
|
|
50
|
+
else if (base === "list" && (sub === "number" || sub === "date")) spec = { type: "list", items: sub };
|
|
51
|
+
if (!spec || extra !== undefined) {
|
|
52
|
+
throw new Error(`field ${name} has unknown type "${type}"; use text, number, integer, date, time, datetime, duration, duration.<${DURATION_UNITS.join("|")}>, list, list.number, or list.date`);
|
|
53
|
+
}
|
|
54
|
+
specs[name] = instructions ? { ...spec, instructions } : spec;
|
|
55
|
+
}
|
|
56
|
+
return specs;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function realDate(text: string): boolean {
|
|
60
|
+
const [year, month, day] = text.split("-").map(Number);
|
|
61
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
62
|
+
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function realTime(text: string): boolean {
|
|
66
|
+
const [hours, minutes, seconds = 0] = text.split(":").map(Number);
|
|
67
|
+
return hours <= 23 && minutes <= 59 && seconds <= 59;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Whether the value has the field's type; dates and times must also exist on the calendar and clock. */
|
|
71
|
+
function matchesType(spec: FieldSpec, value: unknown): boolean {
|
|
72
|
+
switch (spec.type) {
|
|
73
|
+
case "text": return typeof value === "string" && value.trim() !== "";
|
|
74
|
+
case "number": return typeof value === "number" && Number.isFinite(value) && (!spec.integer || Number.isInteger(value));
|
|
75
|
+
case "duration": return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
76
|
+
case "date": return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && realDate(value);
|
|
77
|
+
case "time": return typeof value === "string" && /^\d{2}:\d{2}(:\d{2})?$/.test(value) && realTime(value);
|
|
78
|
+
case "datetime": {
|
|
79
|
+
const match = typeof value === "string" ? /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-](\d{2}:\d{2}))?$/.exec(value) : null;
|
|
80
|
+
return match !== null && realDate(match[1]) && realTime(match[2]) && (match[3] === undefined || realTime(match[3]));
|
|
81
|
+
}
|
|
82
|
+
case "list": return Array.isArray(value) && value.every((item) => matchesType({ type: spec.items! }, item));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function fieldResult(spec: FieldSpec, answer: unknown): FieldResult {
|
|
87
|
+
if (!isRecord(answer)) throw new Error("the response is invalid: a field answer is missing");
|
|
88
|
+
// Clairic may send only p_null when nothing was found.
|
|
89
|
+
// The answer was parsed from Clairic's JSON response, so its value is JSON.
|
|
90
|
+
const { value = null, confidence: rawConfidence } = answer as { value?: JsonValue; confidence?: unknown };
|
|
91
|
+
// A null value is Clairic's "not on the page" verdict; the guess it still sends then is a fallback, not evidence.
|
|
92
|
+
if (value === null) return { status: "null" };
|
|
93
|
+
const confidence = typeof rawConfidence === "number" && rawConfidence >= 0 && rawConfidence <= 1 ? rawConfidence : undefined;
|
|
94
|
+
if (confidence !== undefined && confidence >= EXTRACT_THRESHOLD && matchesType(spec, value)) return { status: "extracted", value, confidence };
|
|
95
|
+
return { status: "uncertain", guess: value, ...(confidence !== undefined ? { confidence } : {}) };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const MAX_LINE_CHARS = 200;
|
|
99
|
+
// A link target longer than this is kept as text.
|
|
100
|
+
const MAX_LINK_TARGET_CHARS = 2_048;
|
|
101
|
+
// Thousands separators seen on pages: comma, period, space, no-break and narrow no-break space, apostrophe.
|
|
102
|
+
const SEPARATORS = new Set([",", ".", " ", " ", " ", "'"]);
|
|
103
|
+
const isDigit = (char: string | undefined) => char !== undefined && char >= "0" && char <= "9";
|
|
104
|
+
|
|
105
|
+
/** A line reduced for comparison, with the raw index each of its UTF-16 units came from. */
|
|
106
|
+
interface Comparable { text: string; map: number[] }
|
|
107
|
+
|
|
108
|
+
// For each "(" on the line, the index of its ")" when it closes within the link bound. One pass with a stack.
|
|
109
|
+
function closingParens(line: string): Map<number, number> {
|
|
110
|
+
const close = new Map<number, number>();
|
|
111
|
+
const open: number[] = [];
|
|
112
|
+
for (let i = 0; i < line.length; i++) {
|
|
113
|
+
if (line[i] === "(") open.push(i);
|
|
114
|
+
else if (line[i] === ")" && open.length) {
|
|
115
|
+
const start = open.pop()!;
|
|
116
|
+
if (i - start <= MAX_LINK_TARGET_CHARS) close.set(start, i);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return close;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* One pass over the text: NFKC, lowercase, markdown backslash escapes removed (Turndown writes `my\_package`,
|
|
124
|
+
* `\[beta\]`), curly quotes and dashes made plain, `* _ \` [ ]` dropped, whitespace collapsed. With `visible`, a
|
|
125
|
+
* link or image target `](…)` (nested parentheses and a quoted title included) is skipped, leaving the text a reader sees.
|
|
126
|
+
* The same steps run on the value, so matching only ever gets looser on the page side.
|
|
127
|
+
*/
|
|
128
|
+
function comparable(raw: string, visible: boolean): Comparable {
|
|
129
|
+
const close = visible ? closingParens(raw) : undefined;
|
|
130
|
+
let text = "";
|
|
131
|
+
const map: number[] = [];
|
|
132
|
+
let space = false;
|
|
133
|
+
const emit = (chars: string, at: number) => {
|
|
134
|
+
// A character whose NFKC form is much longer (U+FDFA is 18 characters) stays as it is, on both sides.
|
|
135
|
+
const folded = chars.normalize("NFKC");
|
|
136
|
+
for (const char of folded.length > 4 * chars.length ? chars : folded) {
|
|
137
|
+
const plain = /[‘’‚‛′]/.test(char) ? "'" : /[“”„‟″]/.test(char) ? '"' : /[‐-―]/.test(char) ? "-" : char;
|
|
138
|
+
if (/[*_`[\]]/.test(plain)) continue;
|
|
139
|
+
if (/\s/.test(plain)) {
|
|
140
|
+
if (text && !space) { text += " "; map.push(at); space = true; }
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const lower = plain.toLowerCase();
|
|
144
|
+
text += lower;
|
|
145
|
+
if (lower) space = false;
|
|
146
|
+
for (let unit = 0; unit < lower.length; unit++) map.push(at);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
for (let i = 0; i < raw.length;) {
|
|
150
|
+
if (raw[i] === "\\" && i + 1 < raw.length && /[!-/:-@[-`{-~]/.test(raw[i + 1])) {
|
|
151
|
+
emit(raw[i + 1], i + 1);
|
|
152
|
+
i += 2;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const target = close && raw[i] === "]" && raw[i + 1] === "(" ? close.get(i + 1) : undefined;
|
|
156
|
+
if (target !== undefined) {
|
|
157
|
+
i = target + 1;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
// A character with its combining marks normalizes as one unit, so "e" + U+0301 meets "é".
|
|
161
|
+
let next = i + String.fromCodePoint(raw.codePointAt(i)!).length;
|
|
162
|
+
while (next < raw.length && /\p{M}/u.test(String.fromCodePoint(raw.codePointAt(next)!))) next += raw.codePointAt(next)! > 0xffff ? 2 : 1;
|
|
163
|
+
emit(raw.slice(i, next), i);
|
|
164
|
+
i = next;
|
|
165
|
+
}
|
|
166
|
+
if (space) { text = text.slice(0, -1); map.pop(); }
|
|
167
|
+
return { text, map };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
interface PageLines { lines: string[]; forms: Comparable[][]; whole: string[] }
|
|
171
|
+
|
|
172
|
+
function indexLines(page: string): PageLines {
|
|
173
|
+
const lines = page.split("\n");
|
|
174
|
+
// Without "](" there is no link target to skip, so both forms are the same.
|
|
175
|
+
const forms = lines.map((line) => { const visible = comparable(line, true); return [visible, line.includes("](") ? comparable(line, false) : visible]; });
|
|
176
|
+
// Both forms of every line joined, for a value that wraps onto the next line.
|
|
177
|
+
const whole = [0, 1].map((form) => forms.map((pair) => pair[form].text).filter(Boolean).join(" "));
|
|
178
|
+
return { lines, forms, whole };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The line, or a window of it that holds raw[start, end), at most MAX_LINE_CHARS including ellipses. */
|
|
182
|
+
function cite(line: string, start: number, end: number): string {
|
|
183
|
+
if (line.length <= MAX_LINE_CHARS) return line.replace(/\s+/g, " ").trim();
|
|
184
|
+
const size = MAX_LINE_CHARS - 2;
|
|
185
|
+
const from = Math.max(0, Math.min(line.length - size, end - start >= size ? start : start - Math.floor((size - (end - start)) / 2)));
|
|
186
|
+
return `${from > 0 ? "…" : ""}${line.slice(from, from + size).replace(/\s+/g, " ").trim()}${from + size < line.length ? "…" : ""}`;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** undefined: not on the page; null: on the page with no single line to cite, or nothing comparable in the value. */
|
|
190
|
+
function locateText(value: string, page: PageLines): string | null | undefined {
|
|
191
|
+
const wanted = comparable(value, false).text;
|
|
192
|
+
if (!wanted) return null;
|
|
193
|
+
for (const [index, pair] of page.forms.entries()) {
|
|
194
|
+
for (const form of pair) {
|
|
195
|
+
const at = form.text.indexOf(wanted);
|
|
196
|
+
if (at !== -1) return cite(page.lines[index], form.map[at], form.map[at + wanted.length - 1] + 1);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return page.whole.some((text) => text.includes(wanted)) ? null : undefined;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// The values a digit run with separators can mean: "1.299" is 1.299 or 1299, "1.299,00" is 1299, "5.3.1" is nothing.
|
|
203
|
+
function readings(groups: string[], separators: string[]): number[] {
|
|
204
|
+
const thousands = (parts: string[]) => parts.slice(1).every((part) => part.length === 3);
|
|
205
|
+
const values: number[] = [];
|
|
206
|
+
if (thousands(groups)) values.push(Number(groups.join("")));
|
|
207
|
+
const decimal = separators.at(-1);
|
|
208
|
+
if ((decimal === "." || decimal === ",") && separators.slice(0, -1).every((separator) => separator !== decimal) && thousands(groups.slice(0, -1))) {
|
|
209
|
+
values.push(Number(`${groups.slice(0, -1).join("")}.${groups.at(-1)}`));
|
|
210
|
+
}
|
|
211
|
+
return values;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The first line holding the whole number, sign included: 299 is not in "1 299", and -42 is not "42". */
|
|
215
|
+
function locateNumber(value: number, lines: string[]): string | undefined {
|
|
216
|
+
for (const line of lines) {
|
|
217
|
+
for (let i = 0; i < line.length;) {
|
|
218
|
+
if (!isDigit(line[i])) { i++; continue; }
|
|
219
|
+
const groups: string[] = [];
|
|
220
|
+
const separators: string[] = [];
|
|
221
|
+
let end = i;
|
|
222
|
+
for (;;) {
|
|
223
|
+
const from = end;
|
|
224
|
+
while (isDigit(line[end])) end++;
|
|
225
|
+
groups.push(line.slice(from, end));
|
|
226
|
+
if (!SEPARATORS.has(line[end]) || !isDigit(line[end + 1])) break;
|
|
227
|
+
separators.push(line[end]);
|
|
228
|
+
end++;
|
|
229
|
+
}
|
|
230
|
+
// A minus, optionally before a currency sign, that does not join two words or numbers ("2026-11", "a-1").
|
|
231
|
+
let sign = i - 1;
|
|
232
|
+
if (/[$€£¥]/.test(line[sign] ?? "")) sign--;
|
|
233
|
+
const negative = (line[sign] === "-" || line[sign] === "−") && !/[\p{L}\p{N}]/u.test(line[sign - 1] ?? "");
|
|
234
|
+
if (readings(groups, separators).some((reading) => (negative ? -reading : reading) === value)) return cite(line, negative ? sign : i, end);
|
|
235
|
+
i = end;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Adds the page line a text or number value was found on (dates, times and durations are rewritten by Clairic, so
|
|
243
|
+
* they have none). A number match only cites; it never changes the status.
|
|
244
|
+
*/
|
|
245
|
+
function withPageLine(spec: FieldSpec, result: FieldResult, page: () => PageLines): FieldResult {
|
|
246
|
+
if (result.status === "null") return result;
|
|
247
|
+
const value = result.status === "extracted" ? result.value : result.guess;
|
|
248
|
+
if (spec.type === "number" && typeof value === "number") {
|
|
249
|
+
const line = locateNumber(value, page().lines);
|
|
250
|
+
return line ? { ...result, line } : result;
|
|
251
|
+
}
|
|
252
|
+
if (spec.type !== "text" || typeof value !== "string") return result;
|
|
253
|
+
const line = locateText(value, page());
|
|
254
|
+
if (line) return { ...result, line };
|
|
255
|
+
// Text that is not on the page was not read from it, however confident the model is.
|
|
256
|
+
if (line === undefined && result.status === "extracted") return { status: "uncertain", guess: result.value, confidence: result.confidence, notFound: true };
|
|
257
|
+
return result;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Clairic is not in Pi's model catalog, so it is called directly with Pi's `cloudflare-workers-ai` credential.
|
|
262
|
+
* When Pi has an AI Gateway id (`CLOUDFLARE_GATEWAY_ID`), the request goes through that gateway.
|
|
263
|
+
*/
|
|
264
|
+
async function runClairic(body: string, modelRegistry: Pick<ModelRegistry, "getProviderAuth"> | undefined, signal: AbortSignal): Promise<Record<string, unknown>> {
|
|
265
|
+
if (!modelRegistry) throw new Error("extract mode runs only inside Pi");
|
|
266
|
+
if (typeof modelRegistry.getProviderAuth !== "function") throw new Error("this Pi version cannot supply the Cloudflare credential; update Pi");
|
|
267
|
+
const credential = await modelRegistry.getProviderAuth("cloudflare-workers-ai");
|
|
268
|
+
const apiKey = credential?.auth.apiKey;
|
|
269
|
+
const accountId = credential?.env?.CLOUDFLARE_ACCOUNT_ID;
|
|
270
|
+
if (!apiKey || !accountId) throw new Error("Cloudflare Workers AI is not set up in Pi; set CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID");
|
|
271
|
+
const gatewayId = (await modelRegistry.getProviderAuth("cloudflare-ai-gateway"))?.env?.CLOUDFLARE_GATEWAY_ID ?? process.env.CLOUDFLARE_GATEWAY_ID;
|
|
272
|
+
let parsed: unknown;
|
|
273
|
+
try {
|
|
274
|
+
const response = await fetchWithCredentialRedirects(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/ai/run/@cf/cloudflare/clairic`, {
|
|
275
|
+
method: "POST",
|
|
276
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", ...(gatewayId ? { "cf-aig-gateway-id": gatewayId } : {}) },
|
|
277
|
+
body,
|
|
278
|
+
signal,
|
|
279
|
+
}, ["Authorization"]);
|
|
280
|
+
const text = await response.text();
|
|
281
|
+
if (!response.ok) {
|
|
282
|
+
// Redact before cutting, so a key straddling the cut can't leave a partial copy behind.
|
|
283
|
+
const detail = redactCredential(text, apiKey).trim().slice(0, 200);
|
|
284
|
+
throw new Error(`Cloudflare Workers AI returned HTTP ${response.status}${detail ? `: ${detail}` : ""}`);
|
|
285
|
+
}
|
|
286
|
+
try {
|
|
287
|
+
parsed = JSON.parse(text);
|
|
288
|
+
} catch {
|
|
289
|
+
throw new Error("the response is invalid: it is not JSON");
|
|
290
|
+
}
|
|
291
|
+
} catch (err) {
|
|
292
|
+
throw new Error(redactCredential(err instanceof Error ? err.message : String(err), apiKey));
|
|
293
|
+
}
|
|
294
|
+
if (!isRecord(parsed) || parsed.success !== true || !isRecord(parsed.result)) throw new Error("Cloudflare Workers AI reported an unsuccessful response");
|
|
295
|
+
return parsed.result;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Provider failures, including Cloudflare not being set up in Pi, become `{ error }`; a caller abort is rethrown. */
|
|
299
|
+
export async function extractPageFields(
|
|
300
|
+
page: string,
|
|
301
|
+
fields: Record<string, FieldSpec>,
|
|
302
|
+
context: { modelRegistry?: Pick<ModelRegistry, "getProviderAuth"> },
|
|
303
|
+
signal?: AbortSignal,
|
|
304
|
+
referenceDate = new Date().toISOString().slice(0, 10),
|
|
305
|
+
): Promise<PageExtraction> {
|
|
306
|
+
const cut = page.length > MAX_PAGE_CHARS;
|
|
307
|
+
const state = cut ? page.slice(0, MAX_PAGE_CHARS) : page;
|
|
308
|
+
const body = JSON.stringify({
|
|
309
|
+
model: "clairic",
|
|
310
|
+
state,
|
|
311
|
+
fields,
|
|
312
|
+
reference_date: referenceDate,
|
|
313
|
+
});
|
|
314
|
+
const timeout = AbortSignal.timeout(TIMEOUT_MS);
|
|
315
|
+
try {
|
|
316
|
+
const result = await runClairic(body, context.modelRegistry, signal ? AbortSignal.any([signal, timeout]) : timeout);
|
|
317
|
+
const answers = result.answers;
|
|
318
|
+
if (!isRecord(answers)) throw new Error("the response is invalid: answers are missing");
|
|
319
|
+
let lines: PageLines | undefined;
|
|
320
|
+
const page = () => lines ??= indexLines(state);
|
|
321
|
+
const results = Object.fromEntries(Object.entries(fields).map(([name, spec]) => [name, withPageLine(spec, fieldResult(spec, Object.hasOwn(answers, name) ? answers[name] : undefined), page)]));
|
|
322
|
+
return { fields: results, cut: cut || result.truncated === true };
|
|
323
|
+
} catch (err) {
|
|
324
|
+
signal?.throwIfAborted();
|
|
325
|
+
if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS / 1000} s` };
|
|
326
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const MAX_SHOWN_VALUE_CHARS = 1_000;
|
|
331
|
+
// One long value must not push the other fields and pages out of the text the model sees.
|
|
332
|
+
const shown = (value: unknown) => {
|
|
333
|
+
const text = typeof value === "string" ? value : JSON.stringify(value);
|
|
334
|
+
return text.length > MAX_SHOWN_VALUE_CHARS ? `${text.slice(0, MAX_SHOWN_VALUE_CHARS)}… [${text.length} characters; the rest is in the stored page]` : text;
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
export function formatPageExtraction(extraction: PageExtraction): string {
|
|
338
|
+
if ("error" in extraction) return `Extraction failed: ${extraction.error}\n`;
|
|
339
|
+
const lines = Object.entries(extraction.fields).map(([name, result]) => {
|
|
340
|
+
const from = result.status !== "null" && result.line ? ` from "${result.line}"` : "";
|
|
341
|
+
if (result.status === "extracted") return `${name}: ${shown(result.value)} (${result.confidence.toFixed(2)})${from}`;
|
|
342
|
+
if (result.status === "uncertain") return `${name}: uncertain (guess ${shown(result.guess)}${result.confidence !== undefined ? `, ${result.confidence.toFixed(2)}` : ""}${result.notFound ? "; not found on the page" : ""})${from}`;
|
|
343
|
+
return `${name}: not on the page`;
|
|
344
|
+
});
|
|
345
|
+
if (extraction.cut) lines.push(`(Only the first part of the page was read; it is longer than the model accepts.)`);
|
|
346
|
+
return `${lines.join("\n")}\n`;
|
|
347
|
+
}
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from "node:fs";
|
|
2
2
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { awaitWithAbort } from "./abortable.ts";
|
|
3
4
|
import { activityMonitor } from "./activity.ts";
|
|
4
5
|
import { CredentialResolutionError } from "./credential-source.ts";
|
|
5
6
|
import { getApiKey, getVersionedApiBase, fetchGeminiApi, isGatewayConfigured, isGeminiApiAvailable, redactGeminiApiResponse } from "./gemini-api.ts";
|
|
6
7
|
import { isGeminiAdcAvailable } from "./gemini-adc.ts";
|
|
7
8
|
import { getGeminiWebAvailabilityDiagnostic, isGeminiWebAvailable, queryWithCookies } from "./gemini-web.ts";
|
|
8
9
|
import { isPerplexityAvailable, searchWithPerplexity, type SearchResult, type SearchResponse, type SearchOptions } from "./perplexity.ts";
|
|
10
|
+
import { normalizeDomain } from "./domain-filter-normalization.ts";
|
|
11
|
+
import { judgeOffTopic, OFFTOPIC_JUDGE_MODELS, type OffTopicJudgeModel } from "./offtopic-judge.ts";
|
|
9
12
|
import { isExaAvailable, searchWithExa } from "./exa.ts";
|
|
10
13
|
import { isBraveAvailable, searchWithBrave } from "./brave.ts";
|
|
11
14
|
import {
|
|
@@ -47,12 +50,13 @@ import { isValyuAvailable, searchWithValyu } from "./valyu.ts";
|
|
|
47
50
|
import { isKeenableAvailable, searchWithKeenable } from "./keenable.ts";
|
|
48
51
|
import { isCeramicAvailable, searchWithCeramic } from "./ceramic.ts";
|
|
49
52
|
import { isLinkupAvailable, searchWithLinkup } from "./linkup.ts";
|
|
53
|
+
import { isNineRouterAvailable, searchWithNineRouter } from "./ninerouter.ts";
|
|
50
54
|
import { isDeepSeekAvailable, searchWithDeepSeek } from "./deepseek.ts";
|
|
51
55
|
import { isKimiSearchAvailable, searchWithKimi } from "./kimi-search.ts";
|
|
52
56
|
import { isMistralAvailable, searchWithMistral } from "./mistral-search.ts";
|
|
53
57
|
import { getWebSearchConfigPath } from "./utils.ts";
|
|
54
58
|
|
|
55
|
-
export const RESOLVED_SEARCH_PROVIDERS = ["openai", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "you", "firecrawl", "jina", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "exa", "serpdive", "kagi", "ollama", "anysearch", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "bocha", "xcrawl", "baizhi", "zai", "keenable", "ceramic", "deepseek", "linkup"] as const;
|
|
59
|
+
export const RESOLVED_SEARCH_PROVIDERS = ["openai", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "you", "firecrawl", "jina", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "exa", "serpdive", "kagi", "ollama", "anysearch", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "bocha", "xcrawl", "baizhi", "zai", "keenable", "ceramic", "deepseek", "linkup", "ninerouter"] as const;
|
|
56
60
|
export const SEARCH_PROVIDERS = ["auto", "all", ...RESOLVED_SEARCH_PROVIDERS] as const;
|
|
57
61
|
|
|
58
62
|
export type ResolvedSearchProvider = typeof RESOLVED_SEARCH_PROVIDERS[number];
|
|
@@ -75,7 +79,11 @@ export type SearchProviderErrorKind =
|
|
|
75
79
|
export interface SearchRoutingConfig {
|
|
76
80
|
providers: ResolvedSearchProvider[];
|
|
77
81
|
useCurrentModel?: boolean;
|
|
78
|
-
fallbackOn: Array<
|
|
82
|
+
fallbackOn: Array<typeof VALID_ROUTING_KINDS[number]>;
|
|
83
|
+
/** Total budget for one routed search across every candidate, in milliseconds. */
|
|
84
|
+
timeoutMs?: number;
|
|
85
|
+
/** Classifier that judges the "off-topic" fallback; required when fallbackOn lists it. */
|
|
86
|
+
offTopicModel?: OffTopicJudgeModel;
|
|
79
87
|
}
|
|
80
88
|
|
|
81
89
|
export class SearchProviderError extends Error {
|
|
@@ -117,10 +125,11 @@ export interface AttributedSearchResponse extends SearchResponse {
|
|
|
117
125
|
|
|
118
126
|
const CONFIG_PATH = getWebSearchConfigPath();
|
|
119
127
|
const DEFAULT_SEARCH_MODEL = "gemini-3.6-flash";
|
|
120
|
-
// Explicit-only providers (Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, XCrawl, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, Keenable, Ceramic, DeepSeek, Linkup) are deliberately absent:
|
|
128
|
+
// Explicit-only providers (Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, XCrawl, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, Keenable, Ceramic, DeepSeek, Linkup, 9router) are deliberately absent:
|
|
121
129
|
// `all` must never fan out to an opt-in or paid provider without the user asking for it.
|
|
122
130
|
export const ALL_SEARCH_PROVIDERS: ResolvedSearchProvider[] = ["searxng", "openai", "exa", "brave", "parallel", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "serpdive", "kagi", "ollama", "perplexity", "gemini", "bocha"];
|
|
123
|
-
const VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported"] as const;
|
|
131
|
+
const VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported", "empty", "domain-miss", "off-topic"] as const;
|
|
132
|
+
const MAX_ROUTING_TIMEOUT_MS = 600_000;
|
|
124
133
|
|
|
125
134
|
type SearchConfig = {
|
|
126
135
|
searchProvider: SearchProviderSelection;
|
|
@@ -198,16 +207,29 @@ function normalizeSearchRouting(value: unknown): SearchRoutingConfig {
|
|
|
198
207
|
const fallbackOn: SearchRoutingConfig["fallbackOn"] = [];
|
|
199
208
|
for (const kind of raw.fallbackOn) {
|
|
200
209
|
if (typeof kind !== "string" || !VALID_ROUTING_KINDS.includes(kind as typeof VALID_ROUTING_KINDS[number])) {
|
|
201
|
-
throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH} may only contain transient, quota, network, invalid-response, or
|
|
210
|
+
throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH} may only contain transient, quota, network, invalid-response, unsupported, empty, domain-miss, or off-topic`);
|
|
202
211
|
}
|
|
203
212
|
if (!fallbackOn.includes(kind as SearchRoutingConfig["fallbackOn"][number])) {
|
|
204
213
|
fallbackOn.push(kind as SearchRoutingConfig["fallbackOn"][number]);
|
|
205
214
|
}
|
|
206
215
|
}
|
|
216
|
+
const timeoutMs = raw.timeoutMs;
|
|
217
|
+
if (timeoutMs !== undefined && (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_ROUTING_TIMEOUT_MS)) {
|
|
218
|
+
throw new Error(`searchRouting.timeoutMs in ${CONFIG_PATH} must be an integer from 1 through ${MAX_ROUTING_TIMEOUT_MS}`);
|
|
219
|
+
}
|
|
220
|
+
const offTopicModel = raw.offTopicModel;
|
|
221
|
+
if (offTopicModel !== undefined && (typeof offTopicModel !== "string" || !Object.hasOwn(OFFTOPIC_JUDGE_MODELS, offTopicModel))) {
|
|
222
|
+
throw new Error(`searchRouting.offTopicModel in ${CONFIG_PATH} must be one of ${Object.keys(OFFTOPIC_JUDGE_MODELS).join(", ")}`);
|
|
223
|
+
}
|
|
224
|
+
if (fallbackOn.includes("off-topic") && offTopicModel === undefined) {
|
|
225
|
+
throw new Error(`searchRouting.fallbackOn in ${CONFIG_PATH} lists off-topic, which needs searchRouting.offTopicModel`);
|
|
226
|
+
}
|
|
207
227
|
return {
|
|
208
228
|
providers,
|
|
209
229
|
...(useCurrentModel !== undefined ? { useCurrentModel: useCurrentModel as boolean } : {}),
|
|
210
230
|
fallbackOn,
|
|
231
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
232
|
+
...(offTopicModel !== undefined ? { offTopicModel: offTopicModel as OffTopicJudgeModel } : {}),
|
|
211
233
|
};
|
|
212
234
|
}
|
|
213
235
|
|
|
@@ -265,6 +287,55 @@ export function normalizeSearchProviderSelection(value: unknown, label = "provid
|
|
|
265
287
|
return SEARCH_PROVIDERS.includes(normalized as SearchProvider) ? normalized as SearchProvider : "auto";
|
|
266
288
|
}
|
|
267
289
|
|
|
290
|
+
/** Strict parser for tool-call `provider` arguments; config values keep the lenient normalizer. */
|
|
291
|
+
export function parseProviderArgument(value: unknown): SearchProviderSelection | undefined {
|
|
292
|
+
if (value === undefined) return undefined;
|
|
293
|
+
if (Array.isArray(value)) return normalizeResolvedProviderList(value, "provider");
|
|
294
|
+
const unknown = (name: string) => new Error(`Unknown search provider "${name}". Use auto, all, or one or more comma-separated names: ${getAllowedSearchProviders().join(", ")}`);
|
|
295
|
+
if (typeof value !== "string") throw unknown(String(value));
|
|
296
|
+
const normalized = value.trim().toLowerCase();
|
|
297
|
+
if (normalized === "") return undefined;
|
|
298
|
+
let names: string[];
|
|
299
|
+
if (normalized.startsWith("[")) {
|
|
300
|
+
let parsed: unknown[];
|
|
301
|
+
try {
|
|
302
|
+
parsed = JSON.parse(normalized);
|
|
303
|
+
} catch {
|
|
304
|
+
throw new Error("provider must be a provider name or comma-separated names; the given value is not valid JSON");
|
|
305
|
+
}
|
|
306
|
+
names = parsed.map(entry => String(entry).trim());
|
|
307
|
+
} else {
|
|
308
|
+
names = normalized.split(",").map(name => name.trim()).filter(Boolean);
|
|
309
|
+
if (names.length < 2) {
|
|
310
|
+
if (!SEARCH_PROVIDERS.includes(names[0] as SearchProvider)) throw unknown(names[0] ?? value);
|
|
311
|
+
return names[0] as SearchProvider;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (names.some(name => name === "auto" || name === "all")) {
|
|
315
|
+
throw new Error('"auto" and "all" cannot be combined with provider names');
|
|
316
|
+
}
|
|
317
|
+
const invalid = names.find(name => !RESOLVED_SEARCH_PROVIDERS.includes(name as ResolvedSearchProvider));
|
|
318
|
+
if (invalid !== undefined) throw unknown(invalid);
|
|
319
|
+
return normalizeResolvedProviderList(names, "provider");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Validate the original arguments, before config can supply an implicit provider. */
|
|
323
|
+
export function validateSearchModelOverride(provider: unknown, model: unknown): string | undefined {
|
|
324
|
+
if (model === undefined) return undefined;
|
|
325
|
+
if (typeof model !== "string" || !model.trim()) {
|
|
326
|
+
throw new Error("model must be a non-empty model ID");
|
|
327
|
+
}
|
|
328
|
+
const selected = parseProviderArgument(provider);
|
|
329
|
+
if (selected === undefined || Array.isArray(selected) || selected === "auto" || selected === "all") {
|
|
330
|
+
throw new Error("model requires one explicit provider: openai, xai, mistral, or gemini (API only); omitted, auto, all, and provider lists are ambiguous");
|
|
331
|
+
}
|
|
332
|
+
if (!["openai", "xai", "mistral", "gemini"].includes(selected)) {
|
|
333
|
+
throw new Error(`model is not supported for provider ${JSON.stringify(selected)}; use openai, xai, mistral, or gemini (API only)`);
|
|
334
|
+
}
|
|
335
|
+
assertSearchProviderSelectionAllowed(selected, "Requested provider");
|
|
336
|
+
return model.trim();
|
|
337
|
+
}
|
|
338
|
+
|
|
268
339
|
export interface FullSearchOptions extends SearchOptions {
|
|
269
340
|
provider?: SearchProviderSelection;
|
|
270
341
|
/** The caller already substituted the configured default for an omitted or "auto" provider. */
|
|
@@ -303,6 +374,12 @@ async function searchWithGemini(
|
|
|
303
374
|
options: SearchOptions,
|
|
304
375
|
strictErrors: boolean,
|
|
305
376
|
): Promise<SearchResponse | null> {
|
|
377
|
+
// Gemini Web cannot honor an explicit model, so never fall back to it.
|
|
378
|
+
if (options.model !== undefined) {
|
|
379
|
+
const result = await searchWithGeminiApi(query, options);
|
|
380
|
+
if (result) return result;
|
|
381
|
+
throw new Error("Gemini API search unavailable: an explicit model requires API-path authentication (API key, ADC, or gateway), not browser cookies");
|
|
382
|
+
}
|
|
306
383
|
const errors: string[] = [];
|
|
307
384
|
|
|
308
385
|
try {
|
|
@@ -433,6 +510,7 @@ async function searchWithResolvedProvider(
|
|
|
433
510
|
if (provider === "keenable") return { ...(await searchWithKeenable(query, options)), provider };
|
|
434
511
|
if (provider === "ceramic") return { ...(await searchWithCeramic(query, options)), provider };
|
|
435
512
|
if (provider === "linkup") return { ...(await searchWithLinkup(query, options)), provider };
|
|
513
|
+
if (provider === "ninerouter") return { ...(await searchWithNineRouter(query, options)), provider };
|
|
436
514
|
if (provider === "deepseek") return { ...(await searchWithDeepSeek(query, options)), provider };
|
|
437
515
|
if (provider === "xcrawl") return { ...(await searchWithXCrawl(query, options)), provider };
|
|
438
516
|
if (provider === "perplexity") return { ...(await searchWithPerplexity(query, options)), provider };
|
|
@@ -491,6 +569,7 @@ async function isResolvedProviderAvailable(provider: ResolvedSearchProvider, opt
|
|
|
491
569
|
if (provider === "keenable") return isKeenableAvailable();
|
|
492
570
|
if (provider === "ceramic") return isCeramicAvailable();
|
|
493
571
|
if (provider === "linkup") return isLinkupAvailable();
|
|
572
|
+
if (provider === "ninerouter") return isNineRouterAvailable();
|
|
494
573
|
if (provider === "deepseek") return isDeepSeekAvailable();
|
|
495
574
|
if (provider === "xcrawl") return isXcrawlAvailable();
|
|
496
575
|
if (provider === "perplexity") return isPerplexityAvailable();
|
|
@@ -541,6 +620,7 @@ export function providerLabel(provider: ResolvedSearchProvider): string {
|
|
|
541
620
|
if (provider === "keenable") return "Keenable";
|
|
542
621
|
if (provider === "ceramic") return "Ceramic";
|
|
543
622
|
if (provider === "linkup") return "Linkup";
|
|
623
|
+
if (provider === "ninerouter") return "9router";
|
|
544
624
|
if (provider === "deepseek") return "DeepSeek";
|
|
545
625
|
return provider.charAt(0).toUpperCase() + provider.slice(1);
|
|
546
626
|
}
|
|
@@ -570,7 +650,7 @@ async function searchWithProviders(
|
|
|
570
650
|
: await isResolvedProviderAvailable(provider, options),
|
|
571
651
|
})))).filter((entry) => entry.available).map((entry) => entry.provider);
|
|
572
652
|
if (providers.length === 0) {
|
|
573
|
-
throw new Error("No configured search provider available for provider \"all\". Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, XCrawl, Keenable, Ceramic, DeepSeek, and
|
|
653
|
+
throw new Error("No configured search provider available for provider \"all\". Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, XCrawl, Keenable, Ceramic, DeepSeek, Linkup, and 9router are excluded.");
|
|
574
654
|
}
|
|
575
655
|
|
|
576
656
|
const settled = await Promise.allSettled(
|
|
@@ -644,21 +724,74 @@ async function searchWithProviders(
|
|
|
644
724
|
};
|
|
645
725
|
}
|
|
646
726
|
|
|
727
|
+
/** A successful response a route may still move past: no results and no answer (`empty`), or no result on a requested domain (`domain-miss`). */
|
|
728
|
+
function weakResult(response: SearchResponse, domainFilter: string[] | undefined): { empty: boolean; domainMiss: boolean } {
|
|
729
|
+
const empty = response.results.length === 0 && !response.answer.trim();
|
|
730
|
+
const wanted = (domainFilter ?? [])
|
|
731
|
+
.filter((domain) => !domain.trim().startsWith("-"))
|
|
732
|
+
.flatMap((domain) => normalizeDomain(domain) ?? []);
|
|
733
|
+
const domainMiss = wanted.length > 0 && !response.results.some((result) => {
|
|
734
|
+
const host = URL.parse(result.url)?.hostname;
|
|
735
|
+
return host !== undefined && wanted.some((domain) => host === domain || host.endsWith(`.${domain}`));
|
|
736
|
+
});
|
|
737
|
+
return { empty, domainMiss };
|
|
738
|
+
}
|
|
739
|
+
|
|
647
740
|
async function searchWithConfiguredRouting(
|
|
648
741
|
query: string,
|
|
649
|
-
|
|
742
|
+
callerOptions: FullSearchOptions,
|
|
650
743
|
routing: SearchRoutingConfig,
|
|
651
744
|
): Promise<AttributedSearchResponse> {
|
|
745
|
+
const deadline = routing.timeoutMs ? AbortSignal.timeout(routing.timeoutMs) : undefined;
|
|
746
|
+
const signal = deadline && (callerOptions.signal ? AbortSignal.any([callerOptions.signal, deadline]) : deadline);
|
|
747
|
+
const options: FullSearchOptions = signal ? { ...callerOptions, signal } : callerOptions;
|
|
748
|
+
const timedOut = () => deadline?.aborted === true && callerOptions.signal?.aborted !== true;
|
|
749
|
+
// Availability checks, Pi auth, and cookie scans ignore the signal, so race each step against it (caller abort or deadline); abandoned work finishes in the background and is ignored.
|
|
750
|
+
const untilDeadline = <T>(work: Promise<T>): Promise<T> => awaitWithAbort(work, signal);
|
|
652
751
|
const diagnostics: string[] = [];
|
|
752
|
+
let firstWeak: AttributedSearchResponse | undefined;
|
|
653
753
|
for (const provider of routing.providers) {
|
|
754
|
+
if (timedOut()) {
|
|
755
|
+
diagnostics.push(`routing timeout after ${routing.timeoutMs}ms`);
|
|
756
|
+
break;
|
|
757
|
+
}
|
|
654
758
|
const useCurrentModel = provider === "openai" && routing.useCurrentModel === true;
|
|
655
|
-
|
|
759
|
+
const available = await untilDeadline(isResolvedProviderAvailable(provider, options, useCurrentModel)).catch((err) => {
|
|
760
|
+
if (timedOut()) return undefined;
|
|
761
|
+
throw err;
|
|
762
|
+
});
|
|
763
|
+
if (available === undefined) {
|
|
764
|
+
diagnostics.push(`${provider}: routing timeout after ${routing.timeoutMs}ms`);
|
|
765
|
+
break;
|
|
766
|
+
}
|
|
767
|
+
if (!available) {
|
|
656
768
|
diagnostics.push(`${provider}: unavailable`);
|
|
657
769
|
continue;
|
|
658
770
|
}
|
|
659
771
|
try {
|
|
660
|
-
|
|
772
|
+
const response = await untilDeadline(searchWithResolvedProvider(provider, query, options, useCurrentModel));
|
|
773
|
+
const weak = weakResult(response, options.domainFilter);
|
|
774
|
+
let kind = weak.empty && routing.fallbackOn.includes("empty") ? "empty" : weak.domainMiss && routing.fallbackOn.includes("domain-miss") ? "domain-miss" : undefined;
|
|
775
|
+
// Over MCP there is no Pi model registry, so the off-topic check is inactive there.
|
|
776
|
+
const registry = options.extensionContext?.modelRegistry;
|
|
777
|
+
if (!kind && !weak.empty && routing.offTopicModel && routing.fallbackOn.includes("off-topic") && registry) {
|
|
778
|
+
// A deadline during the check keeps the response: it is still a success.
|
|
779
|
+
const judgment = await untilDeadline(judgeOffTopic(routing.offTopicModel, query, response, registry, options.signal))
|
|
780
|
+
.catch((err) => { if (timedOut()) return { error: `routing timeout after ${routing.timeoutMs}ms` }; throw err; });
|
|
781
|
+
if ("error" in judgment) {
|
|
782
|
+
const line = `${provider}: off-topic check failed: ${judgment.error}`;
|
|
783
|
+
diagnostics.push(line);
|
|
784
|
+
activityMonitor.logError(activityMonitor.logStart({ type: "api", query }), line);
|
|
785
|
+
} else if (judgment.probabilities.off_topic >= OFFTOPIC_JUDGE_MODELS[routing.offTopicModel]) kind = "off-topic";
|
|
786
|
+
}
|
|
787
|
+
if (!kind) return response;
|
|
788
|
+
diagnostics.push(`${provider} [${kind}]`);
|
|
789
|
+
firstWeak ??= response;
|
|
661
790
|
} catch (err) {
|
|
791
|
+
if (timedOut()) {
|
|
792
|
+
diagnostics.push(`${provider}: routing timeout after ${routing.timeoutMs}ms`);
|
|
793
|
+
break;
|
|
794
|
+
}
|
|
662
795
|
const classified = classifyProviderError(provider, err);
|
|
663
796
|
diagnostics.push(`${provider} [${classified.kind}]: ${errorMessage(err)}`);
|
|
664
797
|
if (!routing.fallbackOn.includes(classified.kind as SearchRoutingConfig["fallbackOn"][number])) {
|
|
@@ -666,6 +799,8 @@ async function searchWithConfiguredRouting(
|
|
|
666
799
|
}
|
|
667
800
|
}
|
|
668
801
|
}
|
|
802
|
+
// Like the built-in auto chain, hand back the first weak response rather than an error.
|
|
803
|
+
if (firstWeak) return firstWeak;
|
|
669
804
|
throw new Error(`Configured search routing exhausted:\n - ${diagnostics.join("\n - ")}`);
|
|
670
805
|
}
|
|
671
806
|
|
|
@@ -759,7 +894,7 @@ export async function search(query: string, options: FullSearchOptions = {}): Pr
|
|
|
759
894
|
" 3. Set OPENAI_API_KEY, BRAVE_API_KEY, PARALLEL_API_KEY, TINYFISH_API_KEY, SEARCH1API_KEY, SEARCHINFINITY_API_KEY, QUERIT_API_KEY, TAVILY_API_KEY, FIRECRAWL_BASE_URL, JINA_API_KEY, SERPDIVE_API_KEY, KAGI_API_KEY, BOCHA_API_KEY, OLLAMA_API_KEY, SEARXNG_BASE_URL, EXA_API_KEY, PERPLEXITY_API_KEY, GEMINI_API_KEY, or CLOUDFLARE_API_KEY env vars\n" +
|
|
760
895
|
" 4. Set GOOGLE_GEMINI_BASE_URL with CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing\n" +
|
|
761
896
|
" 5. Sign into gemini.google.com in a supported Chromium-based browser\n" +
|
|
762
|
-
" 6. Explicitly select provider: \"anysearch\" for anonymous AnySearch, \"xcrawl\" for XCrawl, \"xai\" for Grok, \"mistral\" for Mistral Conversations web search, \"brightdata\" with brightdataSerpZone for paid Bright Data SERP, \"serpbase\", \"serpapi\", \"serper\", or \"serply\" for Google SERP, \"you\" for You.com, \"zai\" for Z.ai GLM Coding Plan search, \"valyu\" for research search, \"keenable\" for keyless Keenable search, \"ceramic\" for Ceramic search, \"deepseek\" for DeepSeek search,
|
|
897
|
+
" 6. Explicitly select provider: \"anysearch\" for anonymous AnySearch, \"xcrawl\" for XCrawl, \"xai\" for Grok, \"mistral\" for Mistral Conversations web search, \"brightdata\" with brightdataSerpZone for paid Bright Data SERP, \"serpbase\", \"serpapi\", \"serper\", or \"serply\" for Google SERP, \"you\" for You.com, \"zai\" for Z.ai GLM Coding Plan search, \"valyu\" for research search, \"keenable\" for keyless Keenable search, \"ceramic\" for Ceramic search, \"deepseek\" for DeepSeek search, \"linkup\" for Linkup search, or \"ninerouter\" for a 9router gateway"
|
|
763
898
|
);
|
|
764
899
|
}
|
|
765
900
|
|
|
@@ -774,13 +909,13 @@ async function searchWithGeminiApi(query: string, options: SearchOptions = {}):
|
|
|
774
909
|
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
775
910
|
|
|
776
911
|
try {
|
|
777
|
-
const model = getSearchConfig().searchModel ?? DEFAULT_SEARCH_MODEL;
|
|
912
|
+
const model = options.model ?? getSearchConfig().searchModel ?? DEFAULT_SEARCH_MODEL;
|
|
778
913
|
const body = {
|
|
779
914
|
contents: [{ role: "user", parts: [{ text: query }] }],
|
|
780
915
|
tools: [{ google_search: {} }],
|
|
781
916
|
};
|
|
782
917
|
|
|
783
|
-
const res = await fetchGeminiApi(`${getVersionedApiBase()}/models/${model}:generateContent`, {
|
|
918
|
+
const res = await fetchGeminiApi(`${getVersionedApiBase()}/models/${options.model !== undefined ? encodeURIComponent(model) : model}:generateContent`, {
|
|
784
919
|
method: "POST",
|
|
785
920
|
headers: { "Content-Type": "application/json" },
|
|
786
921
|
body: JSON.stringify(body),
|
|
@@ -801,7 +936,10 @@ async function searchWithGeminiApi(query: string, options: SearchOptions = {}):
|
|
|
801
936
|
const metadata = data.candidates?.[0]?.groundingMetadata;
|
|
802
937
|
const results = await resolveGroundingChunks(metadata?.groundingChunks, options.signal);
|
|
803
938
|
|
|
804
|
-
if (!answer && results.length === 0)
|
|
939
|
+
if (!answer && results.length === 0) {
|
|
940
|
+
if (options.model !== undefined) throw new Error("Gemini API returned no answer or sources");
|
|
941
|
+
return null;
|
|
942
|
+
}
|
|
805
943
|
return { answer, results };
|
|
806
944
|
} catch (err) {
|
|
807
945
|
const message = err instanceof Error ? err.message : String(err);
|