@abhishek944/pi-web-access 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ASTACK.md +23 -0
- package/CHANGELOG.md +1289 -0
- package/LICENSE +21 -0
- package/README.md +1215 -2
- package/SECURITY.md +5 -0
- package/abortable.ts +17 -0
- package/activity.ts +101 -0
- package/anysearch.ts +188 -0
- package/auth-fetch.ts +152 -0
- package/baizhi.ts +124 -0
- package/banner.png +0 -0
- package/bocha.ts +203 -0
- package/brave-rate-limit.ts +176 -0
- package/brave.ts +247 -0
- package/brightdata-unlocker.ts +272 -0
- package/ceramic.ts +220 -0
- package/chrome-cookies.ts +752 -0
- package/cloudflare-search.ts +237 -0
- package/content-find.ts +255 -0
- package/crawl4ai.ts +196 -0
- package/credential-source.ts +242 -0
- package/curator-page.ts +3607 -0
- package/curator-run.ts +45 -0
- package/curator-server.ts +761 -0
- package/custom-search.ts +226 -0
- package/data-uri-sanitize.ts +406 -0
- package/datalab-pdf-extract.ts +568 -0
- package/declared-web-links.ts +173 -0
- package/deepseek.ts +377 -0
- package/degoog.ts +323 -0
- package/dist/index.js +28286 -0
- package/dist/mcp-cli.js +29186 -0
- package/dist/pi-mcp.js +20855 -0
- package/dist/types/abortable.d.ts +2 -0
- package/dist/types/activity.d.ts +33 -0
- package/dist/types/anysearch.d.ts +7 -0
- package/dist/types/auth-fetch.d.ts +14 -0
- package/dist/types/baizhi.d.ts +3 -0
- package/dist/types/bocha.d.ts +3 -0
- package/dist/types/brave-rate-limit.d.ts +35 -0
- package/dist/types/brave.d.ts +3 -0
- package/dist/types/brightdata-unlocker.d.ts +11 -0
- package/dist/types/ceramic.d.ts +3 -0
- package/dist/types/chrome-cookies.d.ts +44 -0
- package/dist/types/cloudflare-search.d.ts +4 -0
- package/dist/types/content-find.d.ts +10 -0
- package/dist/types/crawl4ai.d.ts +8 -0
- package/dist/types/credential-source.d.ts +29 -0
- package/dist/types/curator-page.d.ts +5 -0
- package/dist/types/curator-run.d.ts +10 -0
- package/dist/types/curator-server.d.ts +72 -0
- package/dist/types/custom-search.d.ts +22 -0
- package/dist/types/data-uri-sanitize.d.ts +20 -0
- package/dist/types/datalab-pdf-extract.d.ts +59 -0
- package/dist/types/declared-web-links.d.ts +7 -0
- package/dist/types/deepseek.d.ts +13 -0
- package/dist/types/degoog.d.ts +3 -0
- package/dist/types/domain-filter-normalization.d.ts +9 -0
- package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
- package/dist/types/duckduckgo.d.ts +6 -0
- package/dist/types/endpoint-pdf-extract.d.ts +22 -0
- package/dist/types/exa.d.ts +17 -0
- package/dist/types/extract.d.ts +70 -0
- package/dist/types/feature-config.d.ts +2 -0
- package/dist/types/fetch-params.d.ts +39 -0
- package/dist/types/field-extract.d.ts +37 -0
- package/dist/types/firecrawl.d.ts +18 -0
- package/dist/types/gemini-adc.d.ts +9 -0
- package/dist/types/gemini-api.d.ts +37 -0
- package/dist/types/gemini-pdf-extract.d.ts +8 -0
- package/dist/types/gemini-search.d.ts +76 -0
- package/dist/types/gemini-url-context.d.ts +3 -0
- package/dist/types/gemini-web-config.d.ts +25 -0
- package/dist/types/gemini-web.d.ts +31 -0
- package/dist/types/github-api.d.ts +6 -0
- package/dist/types/github-extract.d.ts +19 -0
- package/dist/types/github-issue-pr.d.ts +28 -0
- package/dist/types/index.d.ts +53 -0
- package/dist/types/jina-search.d.ts +7 -0
- package/dist/types/kagi.d.ts +14 -0
- package/dist/types/keenable.d.ts +3 -0
- package/dist/types/kimi-search.d.ts +4 -0
- package/dist/types/linkup.d.ts +5 -0
- package/dist/types/mcp-cli.d.ts +2 -0
- package/dist/types/mcp-server.d.ts +10 -0
- package/dist/types/mcp-tool-definitions.d.ts +16 -0
- package/dist/types/mistral-search.d.ts +3 -0
- package/dist/types/ninerouter.d.ts +3 -0
- package/dist/types/offtopic-judge.d.ts +26 -0
- package/dist/types/ollama.d.ts +14 -0
- package/dist/types/openai-search.d.ts +23 -0
- package/dist/types/page-query.d.ts +22 -0
- package/dist/types/parallel-mcp.d.ts +10 -0
- package/dist/types/parallel.d.ts +13 -0
- package/dist/types/pdf-extract.d.ts +44 -0
- package/dist/types/perplexity.d.ts +26 -0
- package/dist/types/pi-mcp.d.ts +56 -0
- package/dist/types/pi-session-results.d.ts +8 -0
- package/dist/types/querit.d.ts +9 -0
- package/dist/types/query-rewrite.d.ts +2 -0
- package/dist/types/render-search-error.d.ts +56 -0
- package/dist/types/retrieval-only.d.ts +78 -0
- package/dist/types/rsc-extract.d.ts +11 -0
- package/dist/types/search-answer-formatting.d.ts +7 -0
- package/dist/types/search-result-count-normalization.d.ts +1 -0
- package/dist/types/searchinfinity.d.ts +7 -0
- package/dist/types/searxng.d.ts +3 -0
- package/dist/types/source-check.d.ts +102 -0
- package/dist/types/ssrf-protection.d.ts +66 -0
- package/dist/types/storage.d.ts +69 -0
- package/dist/types/summary-model-scope.d.ts +33 -0
- package/dist/types/summary-review.d.ts +30 -0
- package/dist/types/tabstack.d.ts +5 -0
- package/dist/types/tavily.d.ts +7 -0
- package/dist/types/tinyfish.d.ts +10 -0
- package/dist/types/tool-activation.d.ts +7 -0
- package/dist/types/tool-arguments.d.ts +1 -0
- package/dist/types/upgrade-notice.d.ts +6 -0
- package/dist/types/utils.d.ts +55 -0
- package/dist/types/valyu.d.ts +5 -0
- package/dist/types/video-extract.d.ts +15 -0
- package/dist/types/web-tool-contract.d.ts +98 -0
- package/dist/types/web-tool-core.d.ts +227 -0
- package/dist/types/xai-search.d.ts +12 -0
- package/dist/types/you.d.ts +3 -0
- package/dist/types/youtube-extract.d.ts +29 -0
- package/dist/types/zai.d.ts +3 -0
- package/docs/pi-mcp.md +41 -0
- package/domain-filter-normalization.ts +44 -0
- package/duckduckgo-rate-limit.ts +205 -0
- package/duckduckgo.ts +123 -0
- package/endpoint-pdf-extract.ts +225 -0
- package/exa.ts +620 -0
- package/extract.ts +1721 -0
- package/feature-config.ts +29 -0
- package/fetch-params.ts +147 -0
- package/field-extract.ts +347 -0
- package/firecrawl.ts +476 -0
- package/gemini-adc.ts +345 -0
- package/gemini-api.ts +368 -0
- package/gemini-pdf-extract.ts +108 -0
- package/gemini-search.ts +1162 -0
- package/gemini-url-context.ts +128 -0
- package/gemini-web-config.ts +131 -0
- package/gemini-web.ts +527 -0
- package/github-api.ts +197 -0
- package/github-extract.ts +1064 -0
- package/github-issue-pr.ts +717 -0
- package/index.ts +2819 -0
- package/jina-search.ts +275 -0
- package/kagi.ts +257 -0
- package/keenable.ts +222 -0
- package/kimi-search.ts +209 -0
- package/linkup.ts +170 -0
- package/mcp-cli.ts +40 -0
- package/mcp-server.ts +84 -0
- package/mcp-tool-definitions.ts +143 -0
- package/mistral-search.ts +268 -0
- package/ninerouter.ts +92 -0
- package/offtopic-judge.ts +72 -0
- package/ollama.ts +237 -0
- package/openai-search.ts +855 -0
- package/package.json +108 -4
- package/page-query.ts +185 -0
- package/parallel-mcp.ts +255 -0
- package/parallel.ts +373 -0
- package/pdf-extract.ts +447 -0
- package/perplexity.ts +245 -0
- package/pi-mcp.ts +139 -0
- package/pi-session-results.ts +40 -0
- package/pi-web-fetch-demo.mp4 +0 -0
- package/promise-try.d.ts +7 -0
- package/querit.ts +394 -0
- package/query-rewrite.ts +84 -0
- package/render-search-error.ts +170 -0
- package/retrieval-only.ts +102 -0
- package/rsc-extract.ts +338 -0
- package/search-answer-formatting.ts +11 -0
- package/search-result-count-normalization.ts +4 -0
- package/searchinfinity.ts +246 -0
- package/searxng.ts +236 -0
- package/source-check.ts +269 -0
- package/ssrf-protection.ts +602 -0
- package/storage.ts +547 -0
- package/summary-model-scope.ts +72 -0
- package/summary-review.ts +476 -0
- package/tabstack.ts +289 -0
- package/tavily.ts +257 -0
- package/tinyfish.ts +373 -0
- package/tool-activation.ts +169 -0
- package/tool-arguments.ts +23 -0
- package/upgrade-notice.ts +47 -0
- package/utils.ts +693 -0
- package/valyu.ts +177 -0
- package/video-extract.ts +398 -0
- package/web-tool-contract.ts +93 -0
- package/web-tool-core.ts +1810 -0
- package/xai-search.ts +443 -0
- package/you.ts +165 -0
- package/youtube-extract.ts +336 -0
- package/zai.ts +161 -0
package/tabstack.ts
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.ts";
|
|
3
|
+
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
|
|
4
|
+
import type { ExtractedContent, ExtractOptions } from "./extract.ts";
|
|
5
|
+
import type { SearchOptions, SearchResponse } from "./perplexity.ts";
|
|
6
|
+
import { getWebSearchConfigPath, resolveProviderApiUrl, fetchWithCredentialRedirects } from "./utils.ts";
|
|
7
|
+
|
|
8
|
+
const TABSTACK_RESEARCH_URL = "https://api.tabstack.ai/v1/research";
|
|
9
|
+
const TABSTACK_EXTRACT_URL = "https://api.tabstack.ai/v1/extract/markdown";
|
|
10
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
11
|
+
const RESEARCH_MODES = ["fast", "balanced"] as const;
|
|
12
|
+
type TabstackResearchMode = typeof RESEARCH_MODES[number];
|
|
13
|
+
// Fast research usually answers in seconds; balanced runs several iterations and can take minutes.
|
|
14
|
+
const RESEARCH_TIMEOUT_MS: Record<TabstackResearchMode, number> = { fast: 120_000, balanced: 300_000 };
|
|
15
|
+
const EXTRACT_TIMEOUT_MS = 90_000;
|
|
16
|
+
|
|
17
|
+
interface WebSearchConfig {
|
|
18
|
+
tabstackBaseUrl?: unknown;
|
|
19
|
+
tabstackApiKey?: unknown;
|
|
20
|
+
tabstackResearchMode?: unknown;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface TabstackCitedPage {
|
|
24
|
+
id?: string;
|
|
25
|
+
url?: string;
|
|
26
|
+
title?: string | null;
|
|
27
|
+
summary?: string | null;
|
|
28
|
+
claims?: string[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface TabstackResearchComplete {
|
|
32
|
+
report?: string;
|
|
33
|
+
metadata?: { citedPages?: TabstackCitedPage[] };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface TabstackResearchError {
|
|
37
|
+
message?: string;
|
|
38
|
+
error?: { message?: string; name?: string };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface TabstackExtractResponse {
|
|
42
|
+
url?: string;
|
|
43
|
+
content?: string;
|
|
44
|
+
metadata?: { title?: string | null } | null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let cachedConfig: WebSearchConfig | null = null;
|
|
48
|
+
|
|
49
|
+
function loadConfig(): WebSearchConfig {
|
|
50
|
+
if (cachedConfig) return cachedConfig;
|
|
51
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
52
|
+
cachedConfig = {};
|
|
53
|
+
return cachedConfig;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let parsed: unknown;
|
|
57
|
+
try {
|
|
58
|
+
parsed = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
|
|
59
|
+
} catch {
|
|
60
|
+
// JSON parse errors can quote credentials from the config file.
|
|
61
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: expected valid JSON`);
|
|
62
|
+
}
|
|
63
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
64
|
+
throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
|
|
65
|
+
}
|
|
66
|
+
cachedConfig = parsed as WebSearchConfig;
|
|
67
|
+
return cachedConfig;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function getApiKey(signal?: AbortSignal): Promise<string> {
|
|
71
|
+
const key = await resolveCredential({
|
|
72
|
+
provider: "Tabstack",
|
|
73
|
+
configuredValue: loadConfig().tabstackApiKey,
|
|
74
|
+
environmentValue: process.env.TABSTACK_API_KEY,
|
|
75
|
+
signal,
|
|
76
|
+
});
|
|
77
|
+
if (!key) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
"Tabstack API key not found. Either:\n" +
|
|
80
|
+
` 1. Create ${CONFIG_PATH} with { "tabstackApiKey": "your-key" }\n` +
|
|
81
|
+
" 2. Set TABSTACK_API_KEY environment variable\n" +
|
|
82
|
+
"Get a key at https://console.tabstack.ai",
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
return key;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function isTabstackAvailable(): boolean {
|
|
89
|
+
return hasCredentialSource({
|
|
90
|
+
provider: "Tabstack",
|
|
91
|
+
configuredValue: loadConfig().tabstackApiKey,
|
|
92
|
+
environmentValue: process.env.TABSTACK_API_KEY,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function getResearchMode(): TabstackResearchMode {
|
|
97
|
+
const value = loadConfig().tabstackResearchMode;
|
|
98
|
+
if (value === undefined) return "fast";
|
|
99
|
+
if (typeof value !== "string" || !RESEARCH_MODES.includes(value as TabstackResearchMode)) {
|
|
100
|
+
throw new Error(`tabstackResearchMode in ${CONFIG_PATH} must be one of: ${RESEARCH_MODES.join(", ")}`);
|
|
101
|
+
}
|
|
102
|
+
return value as TabstackResearchMode;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function errorMessage(err: unknown): string {
|
|
106
|
+
return err instanceof Error ? err.message : String(err);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function requestSignal(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
|
|
110
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
111
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function tabstackRequest(
|
|
115
|
+
label: "Research" | "Extract",
|
|
116
|
+
url: string,
|
|
117
|
+
apiKey: string,
|
|
118
|
+
body: Record<string, unknown>,
|
|
119
|
+
accept: string,
|
|
120
|
+
timeoutMs: number,
|
|
121
|
+
signal?: AbortSignal,
|
|
122
|
+
): Promise<string> {
|
|
123
|
+
try {
|
|
124
|
+
const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("tabstack", url, loadConfig().tabstackBaseUrl), {
|
|
125
|
+
method: "POST",
|
|
126
|
+
headers: {
|
|
127
|
+
Authorization: `Bearer ${apiKey}`,
|
|
128
|
+
Accept: accept,
|
|
129
|
+
"Content-Type": "application/json",
|
|
130
|
+
},
|
|
131
|
+
body: JSON.stringify(body),
|
|
132
|
+
signal: requestSignal(signal, timeoutMs),
|
|
133
|
+
}, ["Authorization"]);
|
|
134
|
+
// Research streams until the report is written, so the deadline also covers the body read.
|
|
135
|
+
const raw = await response.text();
|
|
136
|
+
if (!response.ok) {
|
|
137
|
+
throw new Error(`Tabstack ${label} API error ${response.status}: ${redactCredential(raw, apiKey).slice(0, 300)}`);
|
|
138
|
+
}
|
|
139
|
+
return raw;
|
|
140
|
+
} catch (err) {
|
|
141
|
+
const message = errorMessage(err);
|
|
142
|
+
const isRequestAbort = err instanceof Error
|
|
143
|
+
? err.name === "AbortError" || err.name === "TimeoutError" || /abort|timeout/i.test(message)
|
|
144
|
+
: /abort|timeout/i.test(message);
|
|
145
|
+
if (!signal?.aborted && isRequestAbort && !message.startsWith(`Tabstack ${label} API error`)) {
|
|
146
|
+
const timeoutError = new Error(`Tabstack ${label} API request timed out after ${Math.ceil(timeoutMs / 1_000)} seconds`);
|
|
147
|
+
timeoutError.name = "TimeoutError";
|
|
148
|
+
throw timeoutError;
|
|
149
|
+
}
|
|
150
|
+
const redactedMessage = redactCredential(message, apiKey);
|
|
151
|
+
if (redactedMessage === message) throw err;
|
|
152
|
+
const redactedError = new Error(redactedMessage);
|
|
153
|
+
if (err instanceof Error) redactedError.name = err.name;
|
|
154
|
+
throw redactedError;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function parseEventStream(raw: string): Array<{ event: string; data: unknown }> {
|
|
159
|
+
const events: Array<{ event: string; data: unknown }> = [];
|
|
160
|
+
for (const block of raw.replace(/\r\n?/g, "\n").split(/\n\n+/)) {
|
|
161
|
+
let event = "message";
|
|
162
|
+
const data: string[] = [];
|
|
163
|
+
for (const line of block.split("\n")) {
|
|
164
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
165
|
+
else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
|
|
166
|
+
}
|
|
167
|
+
if (data.length === 0) continue;
|
|
168
|
+
try {
|
|
169
|
+
events.push({ event, data: JSON.parse(data.join("\n")) });
|
|
170
|
+
} catch {
|
|
171
|
+
// A malformed frame is skipped; a missing complete event is reported as an invalid response below.
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return events;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function researchErrorMessage(data: TabstackResearchError): string {
|
|
178
|
+
const nested = typeof data.error?.message === "string" ? data.error.message.trim() : "";
|
|
179
|
+
const message = typeof data.message === "string" ? data.message.trim() : "";
|
|
180
|
+
return nested || message || "unknown error";
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function mapCitedPages(pages: TabstackCitedPage[] | undefined): SearchResponse["results"] {
|
|
184
|
+
if (!Array.isArray(pages)) return [];
|
|
185
|
+
const results: SearchResponse["results"] = [];
|
|
186
|
+
for (const page of pages) {
|
|
187
|
+
if (!page || typeof page.url !== "string" || page.url.trim().length === 0) continue;
|
|
188
|
+
const url = page.url.trim();
|
|
189
|
+
const claims = Array.isArray(page.claims) ? page.claims.filter((claim) => typeof claim === "string" && claim.trim()) : [];
|
|
190
|
+
results.push({
|
|
191
|
+
title: typeof page.title === "string" && page.title.trim() ? page.title.trim() : url,
|
|
192
|
+
url,
|
|
193
|
+
snippet: (typeof page.summary === "string" && page.summary.trim() ? page.summary : claims.join(" ")).replace(/\s+/g, " ").trim(),
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
return results;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export async function searchWithTabstack(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
|
|
200
|
+
const mode = getResearchMode();
|
|
201
|
+
const apiKey = await getApiKey(options.signal);
|
|
202
|
+
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
203
|
+
try {
|
|
204
|
+
// Research has no domain, recency, or result-count parameters, so only the query and mode are sent.
|
|
205
|
+
// Every cited page is kept because the report cites them as [1], [2], ... in this order.
|
|
206
|
+
const raw = await tabstackRequest(
|
|
207
|
+
"Research",
|
|
208
|
+
TABSTACK_RESEARCH_URL,
|
|
209
|
+
apiKey,
|
|
210
|
+
{ query, mode },
|
|
211
|
+
"text/event-stream",
|
|
212
|
+
RESEARCH_TIMEOUT_MS[mode],
|
|
213
|
+
options.signal,
|
|
214
|
+
);
|
|
215
|
+
const events = parseEventStream(raw);
|
|
216
|
+
const failure = events.find((item) => item.event === "error");
|
|
217
|
+
if (failure) {
|
|
218
|
+
throw new Error(`Tabstack Research API returned error: ${researchErrorMessage(failure.data as TabstackResearchError)}`);
|
|
219
|
+
}
|
|
220
|
+
const complete = events.find((item) => item.event === "complete")?.data as TabstackResearchComplete | undefined;
|
|
221
|
+
if (!complete || typeof complete !== "object" || typeof complete.report !== "string") {
|
|
222
|
+
throw new Error("Tabstack Research API returned an invalid response: no complete event with a report");
|
|
223
|
+
}
|
|
224
|
+
const response: SearchResponse = {
|
|
225
|
+
answer: complete.report.trim(),
|
|
226
|
+
results: mapCitedPages(complete.metadata?.citedPages),
|
|
227
|
+
};
|
|
228
|
+
activityMonitor.logComplete(activityId, 200);
|
|
229
|
+
return response;
|
|
230
|
+
} catch (err) {
|
|
231
|
+
const message = errorMessage(err);
|
|
232
|
+
const redactedMessage = redactCredential(message, apiKey);
|
|
233
|
+
if (options.signal?.aborted) activityMonitor.logComplete(activityId, 0);
|
|
234
|
+
else activityMonitor.logError(activityId, redactedMessage);
|
|
235
|
+
if (redactedMessage === message) throw err;
|
|
236
|
+
const redactedError = new Error(redactedMessage);
|
|
237
|
+
if (err instanceof Error) redactedError.name = err.name;
|
|
238
|
+
throw redactedError;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function normalizeTimeoutMs(value: number | undefined): number {
|
|
243
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return EXTRACT_TIMEOUT_MS;
|
|
244
|
+
return Math.max(1, Math.floor(value));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export async function extractWithTabstack(
|
|
248
|
+
url: string,
|
|
249
|
+
signal?: AbortSignal,
|
|
250
|
+
options: ExtractOptions = {},
|
|
251
|
+
): Promise<ExtractedContent | null> {
|
|
252
|
+
const apiKey = await getApiKey(signal);
|
|
253
|
+
const activityId = activityMonitor.logStart({ type: "fetch", url });
|
|
254
|
+
try {
|
|
255
|
+
// metadata: true returns the title separately instead of as YAML front matter in the content.
|
|
256
|
+
const raw = await tabstackRequest(
|
|
257
|
+
"Extract",
|
|
258
|
+
TABSTACK_EXTRACT_URL,
|
|
259
|
+
apiKey,
|
|
260
|
+
{ url, metadata: true },
|
|
261
|
+
"application/json",
|
|
262
|
+
normalizeTimeoutMs(options.timeoutMs),
|
|
263
|
+
signal,
|
|
264
|
+
);
|
|
265
|
+
let data: TabstackExtractResponse;
|
|
266
|
+
try {
|
|
267
|
+
data = JSON.parse(raw) as TabstackExtractResponse;
|
|
268
|
+
} catch (err) {
|
|
269
|
+
throw new Error(`Tabstack Extract API returned invalid JSON: ${errorMessage(err)}`);
|
|
270
|
+
}
|
|
271
|
+
if (!data || typeof data !== "object" || typeof data.content !== "string") {
|
|
272
|
+
throw new Error("Tabstack Extract API returned an unexpected response shape");
|
|
273
|
+
}
|
|
274
|
+
activityMonitor.logComplete(activityId, 200);
|
|
275
|
+
const content = data.content.trim();
|
|
276
|
+
if (!content) return null;
|
|
277
|
+
const title = data.metadata && typeof data.metadata.title === "string" ? data.metadata.title.trim() : "";
|
|
278
|
+
return { url, title, content, error: null };
|
|
279
|
+
} catch (err) {
|
|
280
|
+
const message = errorMessage(err);
|
|
281
|
+
const redactedMessage = redactCredential(message, apiKey);
|
|
282
|
+
if (signal?.aborted) activityMonitor.logComplete(activityId, 0);
|
|
283
|
+
else activityMonitor.logError(activityId, redactedMessage);
|
|
284
|
+
if (redactedMessage === message) throw err;
|
|
285
|
+
const redactedError = new Error(redactedMessage);
|
|
286
|
+
if (err instanceof Error) redactedError.name = err.name;
|
|
287
|
+
throw redactedError;
|
|
288
|
+
}
|
|
289
|
+
}
|
package/tavily.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.ts";
|
|
3
|
+
import { normalizeDomain } from "./domain-filter-normalization.ts";
|
|
4
|
+
import type { ExtractedContent } from "./extract.ts";
|
|
5
|
+
import type { SearchOptions, SearchResponse } from "./perplexity.ts";
|
|
6
|
+
import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
|
|
7
|
+
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
|
|
8
|
+
import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveApiBaseUrl } from "./utils.ts";
|
|
9
|
+
import { getRetrievalOnlyPolicy } from "./retrieval-only.ts";
|
|
10
|
+
|
|
11
|
+
const TAVILY_API_BASE_URL = "https://api.tavily.com";
|
|
12
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
13
|
+
const SEARCH_TIMEOUT_MS = 60_000;
|
|
14
|
+
|
|
15
|
+
interface WebSearchConfig {
|
|
16
|
+
tavilyApiKey?: unknown;
|
|
17
|
+
tavilyBaseUrl?: unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface TavilyResult {
|
|
21
|
+
title?: string;
|
|
22
|
+
url?: string;
|
|
23
|
+
content?: string;
|
|
24
|
+
raw_content?: string | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface TavilyResponse {
|
|
28
|
+
answer?: string;
|
|
29
|
+
results?: TavilyResult[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface TavilySearchOptions extends SearchOptions {
|
|
33
|
+
includeContent?: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let cachedConfig: WebSearchConfig | null = null;
|
|
37
|
+
|
|
38
|
+
function loadConfig(): WebSearchConfig {
|
|
39
|
+
if (cachedConfig) return cachedConfig;
|
|
40
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
41
|
+
cachedConfig = {};
|
|
42
|
+
return cachedConfig;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
|
46
|
+
try {
|
|
47
|
+
cachedConfig = JSON.parse(raw) as WebSearchConfig;
|
|
48
|
+
return cachedConfig;
|
|
49
|
+
} catch (err) {
|
|
50
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
51
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function getApiKey(signal?: AbortSignal): Promise<string | null> {
|
|
56
|
+
return resolveCredential({
|
|
57
|
+
provider: "Tavily",
|
|
58
|
+
configuredValue: loadConfig().tavilyApiKey,
|
|
59
|
+
environmentValue: process.env.TAVILY_API_KEY,
|
|
60
|
+
signal,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const TAVILY_KEY_POOL_RETRIES = new Set([401, 402, 403, 429, 432]);
|
|
65
|
+
|
|
66
|
+
function tavilyKeyPool(): string[] {
|
|
67
|
+
const slots: Array<[number, string]> = [];
|
|
68
|
+
for (let slot = 1; slot <= 20; slot++) {
|
|
69
|
+
const key = process.env[`TAVILY_API_KEY_${slot}`]?.trim();
|
|
70
|
+
if (key) slots.push([slot, key]);
|
|
71
|
+
}
|
|
72
|
+
const requestedSlot = Number.parseInt(process.env.TAVILY_API_KEY_INDEX ?? "", 10) || 1;
|
|
73
|
+
const start = Math.max(0, slots.findIndex(([slot]) => slot >= requestedSlot));
|
|
74
|
+
return [...new Set([...slots.slice(start), ...slots.slice(0, start)].map(([, key]) => key))];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function getApiUrl(): string {
|
|
78
|
+
return `${resolveApiBaseUrl({
|
|
79
|
+
configKey: "tavilyBaseUrl",
|
|
80
|
+
configuredValue: loadConfig().tavilyBaseUrl,
|
|
81
|
+
defaultValue: TAVILY_API_BASE_URL,
|
|
82
|
+
environmentKey: "TAVILY_BASE_URL",
|
|
83
|
+
environmentValue: process.env.TAVILY_BASE_URL,
|
|
84
|
+
})}/search`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function requireApiKey(signal?: AbortSignal): Promise<string> {
|
|
88
|
+
const apiKey = await getApiKey(signal);
|
|
89
|
+
if (!apiKey) {
|
|
90
|
+
throw new Error(
|
|
91
|
+
"Tavily API key not found. Either:\n" +
|
|
92
|
+
` 1. Create ${CONFIG_PATH} with { "tavilyApiKey": "your-key" }\n` +
|
|
93
|
+
" 2. Set TAVILY_API_KEY environment variable\n" +
|
|
94
|
+
"Get a key at https://app.tavily.com/",
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
return apiKey;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function mapDomainFilter(domainFilter: string[] | undefined): { include_domains?: string[]; exclude_domains?: string[] } {
|
|
101
|
+
if (!domainFilter?.length) return {};
|
|
102
|
+
const include_domains: string[] = [];
|
|
103
|
+
const exclude_domains: string[] = [];
|
|
104
|
+
for (const raw of domainFilter) {
|
|
105
|
+
const domain = normalizeDomain(raw);
|
|
106
|
+
if (!domain) continue;
|
|
107
|
+
const target = raw.trim().startsWith("-") ? exclude_domains : include_domains;
|
|
108
|
+
if (!target.includes(domain)) target.push(domain);
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
...(include_domains.length > 0 ? { include_domains } : {}),
|
|
112
|
+
...(exclude_domains.length > 0 ? { exclude_domains } : {}),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function requestSignal(signal?: AbortSignal): AbortSignal {
|
|
117
|
+
const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
|
|
118
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function errorMessage(err: unknown): string {
|
|
122
|
+
return err instanceof Error ? err.message : String(err);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function mapResults(results: TavilyResult[] | undefined, numResults: number): SearchResponse["results"] {
|
|
126
|
+
if (!Array.isArray(results)) return [];
|
|
127
|
+
const mapped: SearchResponse["results"] = [];
|
|
128
|
+
for (const item of results) {
|
|
129
|
+
if (!item?.url) continue;
|
|
130
|
+
mapped.push({
|
|
131
|
+
title: item.title || `Source ${mapped.length + 1}`,
|
|
132
|
+
url: item.url,
|
|
133
|
+
snippet: typeof item.content === "string" ? item.content.replace(/\s+/g, " ").trim() : "",
|
|
134
|
+
});
|
|
135
|
+
if (mapped.length >= numResults) break;
|
|
136
|
+
}
|
|
137
|
+
return mapped;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function mapInlineContent(results: TavilyResult[] | undefined): ExtractedContent[] {
|
|
141
|
+
if (!Array.isArray(results)) return [];
|
|
142
|
+
return results.flatMap((item) => {
|
|
143
|
+
if (!item?.url || typeof item.raw_content !== "string" || item.raw_content.trim().length === 0) return [];
|
|
144
|
+
return [{
|
|
145
|
+
url: item.url,
|
|
146
|
+
title: item.title || "",
|
|
147
|
+
content: item.raw_content,
|
|
148
|
+
error: null,
|
|
149
|
+
}];
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function isTavilyAvailable(): boolean {
|
|
154
|
+
return hasCredentialSource({
|
|
155
|
+
provider: "Tavily",
|
|
156
|
+
configuredValue: loadConfig().tavilyApiKey,
|
|
157
|
+
environmentValue: process.env.TAVILY_API_KEY,
|
|
158
|
+
}) || tavilyKeyPool().length > 0;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export async function searchWithTavily(query: string, options: TavilySearchOptions = {}): Promise<SearchResponse> {
|
|
162
|
+
const apiUrl = getApiUrl();
|
|
163
|
+
const numResults = normalizeSearchResultCount(options.numResults);
|
|
164
|
+
const body: Record<string, unknown> = {
|
|
165
|
+
query,
|
|
166
|
+
search_depth: "basic",
|
|
167
|
+
max_results: numResults,
|
|
168
|
+
// Tavily writes this answer with a model, which the retrieval-only policy rules out.
|
|
169
|
+
include_answer: getRetrievalOnlyPolicy().enabled ? false : "basic",
|
|
170
|
+
include_raw_content: options.includeContent ? "markdown" : false,
|
|
171
|
+
...(options.recencyFilter ? { time_range: options.recencyFilter } : {}),
|
|
172
|
+
...mapDomainFilter(options.domainFilter),
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const signal = requestSignal(options.signal);
|
|
176
|
+
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
177
|
+
let data: TavilyResponse;
|
|
178
|
+
try {
|
|
179
|
+
data = await requestWithKeyFailover(apiUrl, body, signal);
|
|
180
|
+
} catch (err) {
|
|
181
|
+
if (options.signal?.aborted || (err instanceof Error && err.name === "AbortError")) activityMonitor.logComplete(activityId, 0);
|
|
182
|
+
else {
|
|
183
|
+
const status = tavilyErrorStatus(err);
|
|
184
|
+
if (status > 0) activityMonitor.logComplete(activityId, status);
|
|
185
|
+
else activityMonitor.logError(activityId, errorMessage(err));
|
|
186
|
+
}
|
|
187
|
+
throw err;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
activityMonitor.logComplete(activityId, 200);
|
|
191
|
+
const result: SearchResponse = {
|
|
192
|
+
answer: typeof data.answer === "string" ? data.answer : "",
|
|
193
|
+
results: mapResults(data.results, numResults),
|
|
194
|
+
};
|
|
195
|
+
if (options.includeContent) {
|
|
196
|
+
const inlineContent = mapInlineContent(data.results);
|
|
197
|
+
if (inlineContent.length > 0) result.inlineContent = inlineContent;
|
|
198
|
+
}
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function tavilyErrorStatus(err: unknown): number {
|
|
203
|
+
return Number(errorMessage(err).match(/^Tavily API error (\d{3}):/)?.[1] ?? 0);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function requestWithKeyFailover(apiUrl: string, body: Record<string, unknown>, signal: AbortSignal): Promise<TavilyResponse> {
|
|
207
|
+
const pool = tavilyKeyPool();
|
|
208
|
+
const keys = pool.length > 0 ? pool : [await requireApiKey(signal)];
|
|
209
|
+
let fallbackChecked = pool.length === 0;
|
|
210
|
+
for (let i = 0; ; i++) {
|
|
211
|
+
try {
|
|
212
|
+
return await tavilyRequest(apiUrl, keys[i], body, signal);
|
|
213
|
+
} catch (err) {
|
|
214
|
+
if (!TAVILY_KEY_POOL_RETRIES.has(tavilyErrorStatus(err))) throw err;
|
|
215
|
+
if (i + 1 < keys.length) continue;
|
|
216
|
+
if (fallbackChecked) throw err;
|
|
217
|
+
// Resolve the standalone credential only after every numbered pool key failed.
|
|
218
|
+
fallbackChecked = true;
|
|
219
|
+
const fallback = await getApiKey(signal);
|
|
220
|
+
if (!fallback || keys.includes(fallback)) throw err;
|
|
221
|
+
keys.push(fallback);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function tavilyRequest(apiUrl: string, apiKey: string, body: Record<string, unknown>, signal: AbortSignal): Promise<TavilyResponse> {
|
|
227
|
+
let response: Response;
|
|
228
|
+
try {
|
|
229
|
+
response = await fetchWithCredentialRedirects(apiUrl, {
|
|
230
|
+
method: "POST",
|
|
231
|
+
headers: {
|
|
232
|
+
"Authorization": `Bearer ${apiKey}`,
|
|
233
|
+
"Content-Type": "application/json",
|
|
234
|
+
},
|
|
235
|
+
body: JSON.stringify(body),
|
|
236
|
+
signal,
|
|
237
|
+
}, ["Authorization"]);
|
|
238
|
+
} catch (err) {
|
|
239
|
+
const message = errorMessage(err);
|
|
240
|
+
const redactedMessage = redactCredential(message, apiKey);
|
|
241
|
+
if (redactedMessage === message) throw err;
|
|
242
|
+
const redactedError = new Error(redactedMessage);
|
|
243
|
+
if (err instanceof Error) redactedError.name = err.name;
|
|
244
|
+
throw redactedError;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (!response.ok) {
|
|
248
|
+
const errorText = redactCredential(await response.text(), apiKey);
|
|
249
|
+
throw new Error(`Tavily API error ${response.status}: ${errorText.slice(0, 300)}`);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
try {
|
|
253
|
+
return await response.json() as TavilyResponse;
|
|
254
|
+
} catch (err) {
|
|
255
|
+
throw new Error(`Tavily API returned invalid JSON: ${errorMessage(err)}`);
|
|
256
|
+
}
|
|
257
|
+
}
|