@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
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure, dependency-free renderer for web_search error / cancel results.
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS EXISTS: the upstream web_search `renderResult` (index.ts) early-returns
|
|
5
|
+
* a SINGLE line on the error/cancel path, before the collapsed/expanded branch.
|
|
6
|
+
* That makes Ctrl+O (app.tools.expand) flip `expanded` with zero visible effect —
|
|
7
|
+
* a dead-end with no diagnostics. It also discards the partial search results
|
|
8
|
+
* gathered before the cancel, so even an expandable view would have nothing to show.
|
|
9
|
+
*
|
|
10
|
+
* This module is the single source of truth for the error/cancel render PLAN
|
|
11
|
+
* (plain strings, no theme/ANSI), so it is unit-testable without pi's runtime
|
|
12
|
+
* (@mariozechner/pi-tui Text/Box). index.ts.renderResult delegates to it and only
|
|
13
|
+
* applies theme colors + creates Text/Box components.
|
|
14
|
+
*
|
|
15
|
+
* Contract for callers:
|
|
16
|
+
* const plan = buildSearchErrorPlan(details);
|
|
17
|
+
* if (plan === null) ... // not an error/cancel result; use the normal renderer
|
|
18
|
+
* // collapsed: [statusLine, ...plan.collapsed, plan.expandHint].filter(Boolean)
|
|
19
|
+
* // expanded: plan.expanded
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export interface CancelledQueryDetail {
|
|
23
|
+
query: string;
|
|
24
|
+
provider: string | null;
|
|
25
|
+
error: string | null; // null = completed ok; string = per-query error
|
|
26
|
+
resultCount: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface SearchErrorDetails {
|
|
30
|
+
/** The headline error/cancel message, e.g. "Search curation cancelled (stale)." */
|
|
31
|
+
error?: string;
|
|
32
|
+
cancelled?: boolean;
|
|
33
|
+
cancelReason?: string;
|
|
34
|
+
/** Did the curator browser page ever establish a connection? */
|
|
35
|
+
browserConnected?: boolean;
|
|
36
|
+
/** Age (ms) of the last curator heartbeat at cancel time, if known. */
|
|
37
|
+
lastHeartbeatAgeMs?: number | null;
|
|
38
|
+
/** Total queries the user requested. */
|
|
39
|
+
queryCount?: number;
|
|
40
|
+
/** Partial per-query results gathered before the cancel/error. */
|
|
41
|
+
cancelledQueries?: CancelledQueryDetail[];
|
|
42
|
+
/** Arbitrary extra diagnostic lines (e.g. URLs, response id) for non-cancel errors
|
|
43
|
+
* like fetch_content / get_search_content. Shown in the expanded view. */
|
|
44
|
+
extraLines?: string[];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface SearchErrorPlan {
|
|
48
|
+
/** Full diagnostic block, shown when expanded (Ctrl+O). */
|
|
49
|
+
expanded: string[];
|
|
50
|
+
/** Short preview lines, shown under the headline when collapsed. */
|
|
51
|
+
collapsed: string[];
|
|
52
|
+
/** The "... (N more lines, ctrl+o to expand)" hint, or null if nothing is hidden. */
|
|
53
|
+
expandHint: string | null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function truncate(text: string, max: number): string {
|
|
57
|
+
return text.length > max ? text.slice(0, max - 1) + "\u2026" : text;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Build the error/cancel render plan. Returns null when `details` carries no
|
|
62
|
+
* error/cancel signal (so the caller falls through to the normal success renderer).
|
|
63
|
+
*/
|
|
64
|
+
export function buildSearchErrorPlan(details: SearchErrorDetails | undefined | null): SearchErrorPlan | null {
|
|
65
|
+
if (!details || (!details.error && !details.cancelled)) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const headline = details.error ?? "Search cancelled.";
|
|
70
|
+
const queries = details.cancelledQueries ?? [];
|
|
71
|
+
const queryCount = typeof details.queryCount === "number" && details.queryCount > 0
|
|
72
|
+
? details.queryCount
|
|
73
|
+
: queries.length;
|
|
74
|
+
const done = queries.length;
|
|
75
|
+
const errored = queries.filter(q => q.error).length;
|
|
76
|
+
|
|
77
|
+
// Rich diagnostics only make sense when there is something to diagnose: a
|
|
78
|
+
// cancelled/curator result with partial data, OR a non-cancel error that carries
|
|
79
|
+
// extra detail (urls/response-id for fetch_content, the failed query for
|
|
80
|
+
// get_search_content). A bare argument error (e.g. "No URL
|
|
81
|
+
// provided") stays a clean single line -- no noise.
|
|
82
|
+
const extras = details.extraLines ?? [];
|
|
83
|
+
const rich = details.cancelled === true || queries.length > 0 || extras.length > 0;
|
|
84
|
+
if (!rich) {
|
|
85
|
+
return { expanded: [headline], collapsed: [], expandHint: null };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// --- diagnostics block (expanded): curator/cancel-specific only. For non-cancel
|
|
89
|
+
// errors (fetch_content/get_search_content) there is no browser or
|
|
90
|
+
// query-curation state to report, so we skip this block and show only Details. ---
|
|
91
|
+
const expanded: string[] = [headline, ""];
|
|
92
|
+
|
|
93
|
+
if (details.cancelled === true || queries.length > 0) {
|
|
94
|
+
const diag: string[] = [];
|
|
95
|
+
if (details.cancelled) {
|
|
96
|
+
diag.push(`cancel reason : ${details.cancelReason ?? "unknown"}`);
|
|
97
|
+
}
|
|
98
|
+
// Browser connection state — the most common stale cause (page never opened).
|
|
99
|
+
const browserLabel = details.browserConnected === undefined
|
|
100
|
+
? "unknown"
|
|
101
|
+
: details.browserConnected
|
|
102
|
+
? "connected"
|
|
103
|
+
: "never connected";
|
|
104
|
+
diag.push(`browser : ${browserLabel}`);
|
|
105
|
+
if (typeof details.lastHeartbeatAgeMs === "number" && Number.isFinite(details.lastHeartbeatAgeMs)) {
|
|
106
|
+
diag.push(`last heartbeat : ${Math.round(details.lastHeartbeatAgeMs / 1000)}s ago`);
|
|
107
|
+
}
|
|
108
|
+
if (queryCount > 0) {
|
|
109
|
+
diag.push(`queries started : ${queryCount}`);
|
|
110
|
+
diag.push(`queries done : ${done}`);
|
|
111
|
+
if (errored > 0) diag.push(`queries errored : ${errored}`);
|
|
112
|
+
}
|
|
113
|
+
expanded.push("Diagnostics:");
|
|
114
|
+
for (const line of diag) expanded.push(` ${line}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// --- per-query results gathered before cancel ---
|
|
118
|
+
if (queries.length > 0) {
|
|
119
|
+
expanded.push("");
|
|
120
|
+
expanded.push("Per-query results (gathered before cancel):");
|
|
121
|
+
for (const q of queries) {
|
|
122
|
+
const dq = truncate(q.query, 52);
|
|
123
|
+
const tag = q.error ? "[err] " : "[ok] ";
|
|
124
|
+
const provider = q.provider ? ` (${q.provider})` : "";
|
|
125
|
+
const tail = q.error
|
|
126
|
+
? `\u2014 ${truncate(q.error, 60)}`
|
|
127
|
+
: `\u2014 ${q.resultCount} source${q.resultCount === 1 ? "" : "s"}`;
|
|
128
|
+
expanded.push(` ${tag}"${dq}"${provider} ${tail}`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// --- arbitrary extra detail (non-cancel errors) ---
|
|
133
|
+
if (extras.length > 0) {
|
|
134
|
+
expanded.push("");
|
|
135
|
+
expanded.push("Details:");
|
|
136
|
+
for (const e of extras) expanded.push(` ${e}`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// --- collapsed preview ---
|
|
140
|
+
const collapsed: string[] = [];
|
|
141
|
+
const parts: string[] = [];
|
|
142
|
+
if (queryCount > 0) {
|
|
143
|
+
parts.push(`${done}/${queryCount} queries completed`);
|
|
144
|
+
}
|
|
145
|
+
if (errored > 0) {
|
|
146
|
+
parts.push(`${errored} errored`);
|
|
147
|
+
}
|
|
148
|
+
if (details.browserConnected === false) {
|
|
149
|
+
parts.push("browser never connected");
|
|
150
|
+
} else if (details.cancelReason) {
|
|
151
|
+
parts.push(`reason: ${details.cancelReason}`);
|
|
152
|
+
}
|
|
153
|
+
if (parts.length > 0) {
|
|
154
|
+
collapsed.push(parts.join("; ") + ".");
|
|
155
|
+
}
|
|
156
|
+
// For non-cancel errors with extra detail, preview the first detail line.
|
|
157
|
+
if (collapsed.length === 0 && extras.length > 0) {
|
|
158
|
+
for (const e of extras.slice(0, 2)) {
|
|
159
|
+
collapsed.push(truncate(e, 100));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// --- expand hint ---
|
|
164
|
+
const hiddenLines = Math.max(0, expanded.length - (1 + collapsed.length)); // headline + preview shown when collapsed
|
|
165
|
+
const expandHint = hiddenLines > 0
|
|
166
|
+
? `... (${hiddenLines} more lines, ${expanded.length} total, ctrl+o to expand)`
|
|
167
|
+
: null;
|
|
168
|
+
|
|
169
|
+
return { expanded, collapsed, expandHint };
|
|
170
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import type { BuiltinSearchProvider } from "./gemini-search.ts";
|
|
3
|
+
import type { FetchProvider } from "./extract.ts";
|
|
4
|
+
import type { PDFProvider } from "./pdf-extract.ts";
|
|
5
|
+
import { getWebSearchConfigPath, isRecord } from "./utils.ts";
|
|
6
|
+
|
|
7
|
+
const RETRIEVAL_ONLY_ENV = "PI_WEB_ACCESS_RETRIEVAL_ONLY";
|
|
8
|
+
/** Ends the web_search and fetch_content descriptions while the policy is on, so a host can read the policy back. */
|
|
9
|
+
export const RETRIEVAL_ONLY_DESCRIPTION_SUFFIX = " Retrieval-only: no model calls.";
|
|
10
|
+
|
|
11
|
+
export interface RetrievalOnlyPolicy {
|
|
12
|
+
enabled: boolean;
|
|
13
|
+
/** Says how the policy was turned on, for error messages. */
|
|
14
|
+
source?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type RouteKind = "model" | "retrieval";
|
|
18
|
+
|
|
19
|
+
// "model": the route sends content to a model and returns what it wrote. Providers that only
|
|
20
|
+
// rank or snippet retrieved pages with models of their own count as retrieval.
|
|
21
|
+
export const SEARCH_PROVIDER_KINDS = {
|
|
22
|
+
openai: "model", gemini: "model", xai: "model", mistral: "model", tabstack: "model",
|
|
23
|
+
brave: "retrieval", parallel: "retrieval", "parallel-mcp": "retrieval", tinyfish: "retrieval",
|
|
24
|
+
searchinfinity: "retrieval", querit: "retrieval", tavily: "retrieval", you: "retrieval",
|
|
25
|
+
firecrawl: "retrieval", jina: "retrieval", searxng: "retrieval", degoog: "retrieval",
|
|
26
|
+
duckduckgo: "retrieval", perplexity: "retrieval", kimi: "retrieval", exa: "retrieval",
|
|
27
|
+
kagi: "retrieval", ollama: "retrieval", anysearch: "retrieval", valyu: "retrieval",
|
|
28
|
+
bocha: "retrieval", baizhi: "retrieval", zai: "retrieval", keenable: "retrieval",
|
|
29
|
+
ceramic: "retrieval", deepseek: "retrieval", linkup: "retrieval", ninerouter: "retrieval",
|
|
30
|
+
cloudflare: "retrieval",
|
|
31
|
+
} as const satisfies Record<BuiltinSearchProvider, RouteKind>;
|
|
32
|
+
|
|
33
|
+
export const FETCH_PROVIDER_KINDS = {
|
|
34
|
+
gemini: "model",
|
|
35
|
+
http: "retrieval", firecrawl: "retrieval", crawl4ai: "retrieval", jina: "retrieval", tinyfish: "retrieval",
|
|
36
|
+
querit: "retrieval", kagi: "retrieval", ollama: "retrieval", parallel: "retrieval", "parallel-mcp": "retrieval",
|
|
37
|
+
brightdata: "retrieval", deepseek: "retrieval", exa: "retrieval", tabstack: "retrieval",
|
|
38
|
+
} as const satisfies Record<FetchProvider, RouteKind>;
|
|
39
|
+
|
|
40
|
+
// A configured endpoint is the operator's own service, so it counts as retrieval.
|
|
41
|
+
export const PDF_PROVIDER_KINDS = {
|
|
42
|
+
gemini: "model", endpoint: "retrieval", datalab: "retrieval", unpdf: "retrieval",
|
|
43
|
+
} as const satisfies Record<Exclude<PDFProvider, "auto">, RouteKind>;
|
|
44
|
+
|
|
45
|
+
/** Custom providers are not in the table and count as retrieval: they are the operator's responsibility. */
|
|
46
|
+
export function isModelSearchProvider(provider: string): boolean {
|
|
47
|
+
return (SEARCH_PROVIDER_KINDS as Record<string, RouteKind>)[provider] === "model";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function environmentEnabled(): boolean {
|
|
51
|
+
const raw = process.env[RETRIEVAL_ONLY_ENV];
|
|
52
|
+
if (raw === undefined) return false;
|
|
53
|
+
const value = raw.trim().toLowerCase();
|
|
54
|
+
if (value === "" || value === "0" || value === "false") return false;
|
|
55
|
+
if (value === "1" || value === "true") return true;
|
|
56
|
+
throw new Error(`Invalid configuration: ${RETRIEVAL_ONLY_ENV} must be 1, true, 0, or false`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Either the environment or the config turns the policy on; neither can turn the other off. */
|
|
60
|
+
function resolveRetrievalOnlyPolicy(config: { retrievalOnly?: unknown }): RetrievalOnlyPolicy {
|
|
61
|
+
const path = getWebSearchConfigPath();
|
|
62
|
+
const fromEnvironment = environmentEnabled();
|
|
63
|
+
const configured = config.retrievalOnly;
|
|
64
|
+
if (configured !== undefined && typeof configured !== "boolean") {
|
|
65
|
+
throw new Error(`retrievalOnly in ${path} must be a boolean`);
|
|
66
|
+
}
|
|
67
|
+
const sources = [
|
|
68
|
+
...(fromEnvironment ? [`${RETRIEVAL_ONLY_ENV}=1`] : []),
|
|
69
|
+
...(configured === true ? [`retrievalOnly: true in ${path}`] : []),
|
|
70
|
+
];
|
|
71
|
+
return sources.length > 0 ? { enabled: true, source: sources.join(" and ") } : { enabled: false };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let cachedPolicy: RetrievalOnlyPolicy | undefined;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* One policy per process: the first successful read fixes it, as tool definitions are fixed at load.
|
|
78
|
+
* Pi init and the MCP core pass the config they already parsed; other first readers parse the file and
|
|
79
|
+
* throw on an unparseable one without caching. A config edited after load takes effect on restart.
|
|
80
|
+
*/
|
|
81
|
+
export function getRetrievalOnlyPolicy(config?: { retrievalOnly?: unknown }): RetrievalOnlyPolicy {
|
|
82
|
+
if (cachedPolicy) return cachedPolicy;
|
|
83
|
+
if (config) return cachedPolicy = resolveRetrievalOnlyPolicy(config);
|
|
84
|
+
const path = getWebSearchConfigPath();
|
|
85
|
+
let parsed: unknown = {};
|
|
86
|
+
if (existsSync(path)) {
|
|
87
|
+
try {
|
|
88
|
+
parsed = JSON.parse(readFileSync(path, "utf-8"));
|
|
89
|
+
} catch (err) {
|
|
90
|
+
throw new Error(`Failed to parse ${path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return cachedPolicy = resolveRetrievalOnlyPolicy(isRecord(parsed) ? parsed : {});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function retrievalOnlyError(route: string, policy = getRetrievalOnlyPolicy()): Error {
|
|
97
|
+
return new Error(`${route} is blocked by the retrieval-only policy (${policy.source}): it sends content to a model.`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function retrievalOnlyExhaustedError(routeKind: string, skipped: readonly string[], policy = getRetrievalOnlyPolicy()): Error {
|
|
101
|
+
return new Error(`No retrieval route is available under the retrieval-only policy (${policy.source}); ${routeKind} routes that use a model were skipped: ${skipped.join(", ")}.`);
|
|
102
|
+
}
|
package/rsc-extract.ts
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RSC Content Extractor
|
|
3
|
+
*
|
|
4
|
+
* Extracts readable content from Next.js React Server Components (RSC) flight payloads.
|
|
5
|
+
* RSC pages embed content as JSON in <script>self.__next_f.push([...])</script> tags.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export interface RSCExtractResult {
|
|
9
|
+
title: string;
|
|
10
|
+
content: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function extractRSCContent(html: string): RSCExtractResult | null {
|
|
14
|
+
if (!html.includes("self.__next_f.push")) {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Parse all RSC chunks into a map
|
|
19
|
+
const chunkMap = new Map<string, string>();
|
|
20
|
+
const scriptRegex = /<script>self\.__next_f\.push\(\[1,"([\s\S]*?)"\]\)<\/script>/g;
|
|
21
|
+
|
|
22
|
+
for (const match of html.matchAll(scriptRegex)) {
|
|
23
|
+
let content: string;
|
|
24
|
+
try {
|
|
25
|
+
content = JSON.parse('"' + match[1] + '"');
|
|
26
|
+
} catch {
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Parse each line as "id:payload"
|
|
31
|
+
// Lines are separated by \n, each line is one chunk
|
|
32
|
+
// Chunk IDs are hex strings, typically 1-4 chars (supports up to 65535 chunks)
|
|
33
|
+
for (const line of content.split("\n")) {
|
|
34
|
+
if (!line.trim()) continue;
|
|
35
|
+
|
|
36
|
+
const colonIdx = line.indexOf(":");
|
|
37
|
+
if (colonIdx <= 0 || colonIdx > 4) continue;
|
|
38
|
+
|
|
39
|
+
const id = line.slice(0, colonIdx);
|
|
40
|
+
if (!/^[0-9a-f]+$/i.test(id)) continue;
|
|
41
|
+
|
|
42
|
+
const payload = line.slice(colonIdx + 1);
|
|
43
|
+
if (!payload) continue;
|
|
44
|
+
|
|
45
|
+
const existing = chunkMap.get(id);
|
|
46
|
+
if (!existing || payload.length > existing.length) {
|
|
47
|
+
chunkMap.set(id, payload);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (chunkMap.size === 0) return null;
|
|
53
|
+
|
|
54
|
+
// Extract title
|
|
55
|
+
const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/);
|
|
56
|
+
const title = titleMatch?.[1]?.split("|")[0]?.trim() || "";
|
|
57
|
+
|
|
58
|
+
// Parse and cache parsed chunks
|
|
59
|
+
const parsedCache = new Map<string, unknown>();
|
|
60
|
+
|
|
61
|
+
function getParsedChunk(id: string): unknown | null {
|
|
62
|
+
if (parsedCache.has(id)) return parsedCache.get(id);
|
|
63
|
+
|
|
64
|
+
const chunk = chunkMap.get(id);
|
|
65
|
+
if (!chunk || !chunk.startsWith("[")) {
|
|
66
|
+
parsedCache.set(id, null);
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
const parsed = JSON.parse(chunk);
|
|
72
|
+
parsedCache.set(id, parsed);
|
|
73
|
+
return parsed;
|
|
74
|
+
} catch {
|
|
75
|
+
parsedCache.set(id, null);
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Extract markdown from nodes, resolving refs on the fly
|
|
81
|
+
type Node = unknown;
|
|
82
|
+
const visitedRefs = new Set<string>();
|
|
83
|
+
|
|
84
|
+
function extractNode(node: Node, ctx = { inTable: false, inCode: false }): string {
|
|
85
|
+
if (node === null || node === undefined) return "";
|
|
86
|
+
|
|
87
|
+
if (typeof node === "string") {
|
|
88
|
+
// Check if it's a reference like "$L30"
|
|
89
|
+
const refMatch = node.match(/^\$L([0-9a-f]+)$/i);
|
|
90
|
+
if (refMatch) {
|
|
91
|
+
const refId = refMatch[1];
|
|
92
|
+
if (visitedRefs.has(refId)) return ""; // Prevent cycles
|
|
93
|
+
visitedRefs.add(refId);
|
|
94
|
+
const refNode = getParsedChunk(refId);
|
|
95
|
+
const result = refNode ? extractNode(refNode, ctx) : "";
|
|
96
|
+
visitedRefs.delete(refId);
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
// Filter out RSC-specific artifacts, but preserve content inside code blocks
|
|
100
|
+
if (!ctx.inCode && (node === "$undefined" || node === "$" || /^\$[A-Z]/.test(node))) return "";
|
|
101
|
+
return node.trim() ? node : "";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (typeof node === "number") return String(node);
|
|
105
|
+
if (typeof node === "boolean") return "";
|
|
106
|
+
if (!Array.isArray(node)) return "";
|
|
107
|
+
|
|
108
|
+
// RSC element: ["$", "tag", key, props]
|
|
109
|
+
if (node[0] === "$" && typeof node[1] === "string") {
|
|
110
|
+
const tag = node[1] as string;
|
|
111
|
+
const props = (node[3] || {}) as Record<string, unknown>;
|
|
112
|
+
|
|
113
|
+
// Skip non-content
|
|
114
|
+
const skipTags = ["script", "style", "svg", "path", "circle", "link", "meta",
|
|
115
|
+
"template", "button", "input", "nav", "footer", "aside"];
|
|
116
|
+
if (skipTags.includes(tag)) return "";
|
|
117
|
+
|
|
118
|
+
// Component ref like $L25
|
|
119
|
+
if (tag.startsWith("$L")) {
|
|
120
|
+
const refId = tag.slice(2);
|
|
121
|
+
if (visitedRefs.has(refId)) return "";
|
|
122
|
+
|
|
123
|
+
// Check for heading components with baseId
|
|
124
|
+
if (props.baseId && props.children) {
|
|
125
|
+
return `## ${String(props.children)}\n\n`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
visitedRefs.add(refId);
|
|
129
|
+
const refNode = getParsedChunk(refId);
|
|
130
|
+
let result = "";
|
|
131
|
+
if (refNode) {
|
|
132
|
+
result = extractNode(refNode, ctx);
|
|
133
|
+
} else if (props.children) {
|
|
134
|
+
result = extractNode(props.children as Node, ctx);
|
|
135
|
+
}
|
|
136
|
+
visitedRefs.delete(refId);
|
|
137
|
+
return result;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const children = props.children;
|
|
141
|
+
const content = children ? extractNode(children as Node, ctx) : "";
|
|
142
|
+
|
|
143
|
+
switch (tag) {
|
|
144
|
+
case "h1": return `# ${content.trim()}\n\n`;
|
|
145
|
+
case "h2": return `## ${content.trim()}\n\n`;
|
|
146
|
+
case "h3": return `### ${content.trim()}\n\n`;
|
|
147
|
+
case "h4": return `#### ${content.trim()}\n\n`;
|
|
148
|
+
case "h5": return `##### ${content.trim()}\n\n`;
|
|
149
|
+
case "h6": return `###### ${content.trim()}\n\n`;
|
|
150
|
+
case "p": return ctx.inTable ? content : `${content.trim()}\n\n`;
|
|
151
|
+
case "code": {
|
|
152
|
+
const codeContent = children ? extractNode(children as Node, { ...ctx, inCode: true }) : "";
|
|
153
|
+
return ctx.inCode ? codeContent : `\`${codeContent}\``;
|
|
154
|
+
}
|
|
155
|
+
case "pre": {
|
|
156
|
+
const preContent = children ? extractNode(children as Node, { ...ctx, inCode: true }) : "";
|
|
157
|
+
return "```\n" + preContent + "\n```\n\n";
|
|
158
|
+
}
|
|
159
|
+
case "strong": case "b": return `**${content}**`;
|
|
160
|
+
case "em": case "i": return `*${content}*`;
|
|
161
|
+
case "li": return `- ${content.trim()}\n`;
|
|
162
|
+
case "ul": case "ol": return content + "\n";
|
|
163
|
+
case "blockquote": return `> ${content.trim()}\n\n`;
|
|
164
|
+
case "table": return extractTable(node as unknown[]) + "\n";
|
|
165
|
+
case "thead": case "tbody": case "tr": case "th": case "td":
|
|
166
|
+
return content;
|
|
167
|
+
case "div":
|
|
168
|
+
if (props.role === "alert" || props["data-slot"] === "alert") {
|
|
169
|
+
return `> ${content.trim()}\n\n`;
|
|
170
|
+
}
|
|
171
|
+
return content;
|
|
172
|
+
case "a": {
|
|
173
|
+
const href = props.href as string | undefined;
|
|
174
|
+
return href && !href.startsWith("#") ? `[${content}](${href})` : content;
|
|
175
|
+
}
|
|
176
|
+
default: return content;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Array of child nodes
|
|
181
|
+
return (node as Node[]).map(n => extractNode(n, ctx)).join("");
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function extractTable(tableNode: unknown[]): string {
|
|
185
|
+
const props = (tableNode[3] || {}) as Record<string, unknown>;
|
|
186
|
+
const rows: string[][] = [];
|
|
187
|
+
let headerRowCount = 0;
|
|
188
|
+
|
|
189
|
+
function walkTable(node: unknown, isHeader = false): void {
|
|
190
|
+
if (node === null || node === undefined) return;
|
|
191
|
+
|
|
192
|
+
// Handle string refs
|
|
193
|
+
if (typeof node === "string") {
|
|
194
|
+
const refMatch = node.match(/^\$L([0-9a-f]+)$/i);
|
|
195
|
+
if (refMatch && !visitedRefs.has(refMatch[1])) {
|
|
196
|
+
visitedRefs.add(refMatch[1]);
|
|
197
|
+
const refNode = getParsedChunk(refMatch[1]);
|
|
198
|
+
if (refNode) walkTable(refNode, isHeader);
|
|
199
|
+
visitedRefs.delete(refMatch[1]);
|
|
200
|
+
}
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (!Array.isArray(node)) return;
|
|
205
|
+
|
|
206
|
+
if (node[0] === "$") {
|
|
207
|
+
const tag = node[1] as string;
|
|
208
|
+
const nodeProps = (node[3] || {}) as Record<string, unknown>;
|
|
209
|
+
|
|
210
|
+
// Handle component refs
|
|
211
|
+
if (tag.startsWith("$L")) {
|
|
212
|
+
const refId = tag.slice(2);
|
|
213
|
+
if (!visitedRefs.has(refId)) {
|
|
214
|
+
visitedRefs.add(refId);
|
|
215
|
+
const refNode = getParsedChunk(refId);
|
|
216
|
+
if (refNode) walkTable(refNode, isHeader);
|
|
217
|
+
visitedRefs.delete(refId);
|
|
218
|
+
}
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (tag === "thead") walkTable(nodeProps.children, true);
|
|
223
|
+
else if (tag === "tbody") walkTable(nodeProps.children, false);
|
|
224
|
+
else if (tag === "tr") {
|
|
225
|
+
const cells: string[] = [];
|
|
226
|
+
walkCells(nodeProps.children, cells);
|
|
227
|
+
if (cells.length > 0) {
|
|
228
|
+
rows.push(cells);
|
|
229
|
+
if (isHeader) headerRowCount++;
|
|
230
|
+
}
|
|
231
|
+
} else walkTable(nodeProps.children, isHeader);
|
|
232
|
+
} else {
|
|
233
|
+
for (const child of node) walkTable(child, isHeader);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function walkCells(node: unknown, cells: string[]): void {
|
|
238
|
+
if (node === null || node === undefined) return;
|
|
239
|
+
|
|
240
|
+
// Handle string refs
|
|
241
|
+
if (typeof node === "string") {
|
|
242
|
+
const refMatch = node.match(/^\$L([0-9a-f]+)$/i);
|
|
243
|
+
if (refMatch && !visitedRefs.has(refMatch[1])) {
|
|
244
|
+
visitedRefs.add(refMatch[1]);
|
|
245
|
+
const refNode = getParsedChunk(refMatch[1]);
|
|
246
|
+
if (refNode) walkCells(refNode, cells);
|
|
247
|
+
visitedRefs.delete(refMatch[1]);
|
|
248
|
+
}
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (!Array.isArray(node)) return;
|
|
253
|
+
|
|
254
|
+
if (node[0] === "$" && (node[1] === "td" || node[1] === "th")) {
|
|
255
|
+
const cellProps = (node[3] || {}) as Record<string, unknown>;
|
|
256
|
+
const text = extractNode(cellProps.children, { inTable: true, inCode: false })
|
|
257
|
+
.trim()
|
|
258
|
+
.replace(/\n/g, " ")
|
|
259
|
+
.replace(/\\/g, "\\\\") // Escape backslashes first
|
|
260
|
+
.replace(/\|/g, "\\|"); // Then escape pipes
|
|
261
|
+
cells.push(text);
|
|
262
|
+
} else if (node[0] === "$" && typeof node[1] === "string" && (node[1] as string).startsWith("$L")) {
|
|
263
|
+
// Component ref for a cell
|
|
264
|
+
const refId = (node[1] as string).slice(2);
|
|
265
|
+
if (!visitedRefs.has(refId)) {
|
|
266
|
+
visitedRefs.add(refId);
|
|
267
|
+
const refNode = getParsedChunk(refId);
|
|
268
|
+
if (refNode) walkCells(refNode, cells);
|
|
269
|
+
visitedRefs.delete(refId);
|
|
270
|
+
}
|
|
271
|
+
} else {
|
|
272
|
+
for (const child of node) walkCells(child, cells);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
walkTable(props.children);
|
|
277
|
+
if (rows.length === 0) return "";
|
|
278
|
+
|
|
279
|
+
const colCount = Math.max(...rows.map(r => r.length));
|
|
280
|
+
let md = "";
|
|
281
|
+
for (let i = 0; i < rows.length; i++) {
|
|
282
|
+
const row = rows[i].concat(Array(colCount - rows[i].length).fill(""));
|
|
283
|
+
md += "| " + row.join(" | ") + " |\n";
|
|
284
|
+
if (i === headerRowCount - 1 || (headerRowCount === 0 && i === 0)) {
|
|
285
|
+
md += "| " + Array(colCount).fill("---").join(" | ") + " |\n";
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return md;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Process main content chunk (usually "23")
|
|
292
|
+
const mainChunk = getParsedChunk("23");
|
|
293
|
+
|
|
294
|
+
if (mainChunk) {
|
|
295
|
+
const content = extractNode(mainChunk);
|
|
296
|
+
if (content.trim().length > 100) {
|
|
297
|
+
const cleaned = content
|
|
298
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
299
|
+
.trim();
|
|
300
|
+
return { title, content: cleaned };
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Fallback: try other chunks
|
|
305
|
+
const contentParts: { order: number; text: string }[] = [];
|
|
306
|
+
|
|
307
|
+
for (const [id] of chunkMap) {
|
|
308
|
+
if (id === "23") continue;
|
|
309
|
+
const parsed = getParsedChunk(id);
|
|
310
|
+
if (!parsed) continue;
|
|
311
|
+
|
|
312
|
+
visitedRefs.clear();
|
|
313
|
+
const text = extractNode(parsed);
|
|
314
|
+
|
|
315
|
+
if (text.trim().length > 50 &&
|
|
316
|
+
!text.includes("page was not found") &&
|
|
317
|
+
!text.includes("404")) {
|
|
318
|
+
contentParts.push({ order: parseInt(id, 16), text: text.trim() });
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (contentParts.length === 0) return null;
|
|
323
|
+
|
|
324
|
+
contentParts.sort((a, b) => a.order - b.order);
|
|
325
|
+
|
|
326
|
+
const seen = new Set<string>();
|
|
327
|
+
const uniqueParts: string[] = [];
|
|
328
|
+
for (const part of contentParts) {
|
|
329
|
+
const key = part.text.slice(0, 150);
|
|
330
|
+
if (!seen.has(key)) {
|
|
331
|
+
seen.add(key);
|
|
332
|
+
uniqueParts.push(part.text);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const content = uniqueParts.join("\n\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
337
|
+
return content.length > 100 ? { title, content } : null;
|
|
338
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
interface AnswerResult {
|
|
2
|
+
title: string;
|
|
3
|
+
url: string;
|
|
4
|
+
snippet: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function formatSearchResultsAsAnswer(results: readonly AnswerResult[]): string {
|
|
8
|
+
return results.map((result) => result.snippet
|
|
9
|
+
? `${result.snippet}\nSource: ${result.title} (${result.url})`
|
|
10
|
+
: `Source: ${result.title} (${result.url})`).join("\n\n");
|
|
11
|
+
}
|