@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,336 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { activityMonitor } from "./activity.ts";
|
|
4
|
+
import { canAttachImages } from "./feature-config.ts";
|
|
5
|
+
import { browserCookieAccessHint, browserCookieAccessHintLine, isGeminiWebAvailable, queryWithCookies, requestBrowserCookieAccess } from "./gemini-web.ts";
|
|
6
|
+
import { isBrowserCookieAccessAllowed, type BrowserCookieConsent } from "./gemini-web-config.ts";
|
|
7
|
+
import { isGeminiApiAvailableWithVideo, queryGeminiApiWithVideo } from "./gemini-api.ts";
|
|
8
|
+
import { askPerplexity, isPerplexityAvailable } from "./perplexity.ts";
|
|
9
|
+
import { extractHeadingTitle, type ExtractedContent, type FrameResult, type VideoFrame } from "./extract.ts";
|
|
10
|
+
import { formatSeconds, readExecError, isTimeoutError, trimErrorText, mapFfmpegError, getWebSearchConfigPath, FRAME_SCALE_FILTER } from "./utils.ts";
|
|
11
|
+
import { getRetrievalOnlyPolicy, retrievalOnlyError } from "./retrieval-only.ts";
|
|
12
|
+
|
|
13
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
14
|
+
|
|
15
|
+
const YOUTUBE_PROMPT = `Extract the complete content of this YouTube video. Include:
|
|
16
|
+
1. Video title, channel name, and duration
|
|
17
|
+
2. A brief summary (2-3 sentences)
|
|
18
|
+
3. Full transcript with timestamps
|
|
19
|
+
4. Descriptions of any code, terminal commands, diagrams, slides, or UI shown on screen
|
|
20
|
+
|
|
21
|
+
Format as markdown.`;
|
|
22
|
+
|
|
23
|
+
const YOUTUBE_REGEX =
|
|
24
|
+
/(?:(?:www\.|m\.)?youtube\.com\/(?:watch\?.*v=|shorts\/|live\/|embed\/|v\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
|
|
25
|
+
|
|
26
|
+
function errorMessage(err: unknown): string {
|
|
27
|
+
return err instanceof Error ? err.message : String(err);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function shouldRethrow(err: unknown): boolean {
|
|
31
|
+
return errorMessage(err).startsWith("Failed to parse ");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function addAttemptError(errors: string[], label: string, err: unknown): void {
|
|
35
|
+
const message = errorMessage(err).replace(/\s+/g, " ").trim();
|
|
36
|
+
if (message) errors.push(`${label}: ${message}`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface YouTubeConfig {
|
|
40
|
+
enabled: boolean;
|
|
41
|
+
preferredModel: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function normalizePreferredModel(value: unknown, fallback: string): string {
|
|
45
|
+
if (typeof value !== "string") return fallback;
|
|
46
|
+
const normalized = value.trim();
|
|
47
|
+
return normalized.length > 0 ? normalized : fallback;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function normalizeEnabled(value: unknown, fallback: boolean): boolean {
|
|
51
|
+
return typeof value === "boolean" ? value : fallback;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const defaults: YouTubeConfig = { enabled: true, preferredModel: "gemini-3.6-flash" };
|
|
55
|
+
let cachedConfig: YouTubeConfig | null = null;
|
|
56
|
+
|
|
57
|
+
function loadYouTubeConfig(): YouTubeConfig {
|
|
58
|
+
if (cachedConfig) return cachedConfig;
|
|
59
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
60
|
+
cachedConfig = { ...defaults };
|
|
61
|
+
return cachedConfig;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const rawText = readFileSync(CONFIG_PATH, "utf-8");
|
|
65
|
+
let raw: { youtube?: { enabled?: boolean; preferredModel?: string } };
|
|
66
|
+
try {
|
|
67
|
+
raw = JSON.parse(rawText) as { youtube?: { enabled?: boolean; preferredModel?: string } };
|
|
68
|
+
} catch (err) {
|
|
69
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
70
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const yt = raw.youtube ?? {};
|
|
74
|
+
cachedConfig = {
|
|
75
|
+
enabled: normalizeEnabled(yt.enabled, defaults.enabled),
|
|
76
|
+
preferredModel: normalizePreferredModel(yt.preferredModel, defaults.preferredModel),
|
|
77
|
+
};
|
|
78
|
+
return cachedConfig;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function isYouTubeURL(url: string): { isYouTube: boolean; videoId: string | null } {
|
|
82
|
+
try {
|
|
83
|
+
const parsed = new URL(url);
|
|
84
|
+
if (parsed.pathname === "/playlist") {
|
|
85
|
+
return { isYouTube: false, videoId: null };
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const match = url.match(YOUTUBE_REGEX);
|
|
91
|
+
if (!match) return { isYouTube: false, videoId: null };
|
|
92
|
+
return { isYouTube: true, videoId: match[1] };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function isYouTubeEnabled(): boolean {
|
|
96
|
+
return loadYouTubeConfig().enabled;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The error when no route could read a YouTube video and none said why. */
|
|
100
|
+
export function youTubeAccessError(browserCookieConsent?: BrowserCookieConsent): string {
|
|
101
|
+
return `Could not extract YouTube video content. Set GEMINI_API_KEY in ${CONFIG_PATH}, or:\n${browserCookieAccessHint(browserCookieConsent)}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function extractYouTube(
|
|
105
|
+
url: string,
|
|
106
|
+
signal?: AbortSignal,
|
|
107
|
+
prompt?: string,
|
|
108
|
+
model?: string,
|
|
109
|
+
browserCookieConsent?: BrowserCookieConsent,
|
|
110
|
+
): Promise<ExtractedContent | null> {
|
|
111
|
+
// Every route below (Gemini Web, Gemini API, Perplexity Sonar) has a model watch the video.
|
|
112
|
+
if (getRetrievalOnlyPolicy().enabled) throw retrievalOnlyError("YouTube video analysis");
|
|
113
|
+
const config = loadYouTubeConfig();
|
|
114
|
+
const { videoId } = isYouTubeURL(url);
|
|
115
|
+
const canonicalUrl = videoId
|
|
116
|
+
? `https://www.youtube.com/watch?v=${videoId}`
|
|
117
|
+
: url;
|
|
118
|
+
const effectivePrompt = prompt ?? YOUTUBE_PROMPT;
|
|
119
|
+
const effectiveModel = model ?? config.preferredModel;
|
|
120
|
+
|
|
121
|
+
const activityId = activityMonitor.logStart({ type: "fetch", url: `youtube.com/${videoId ?? "video"}` });
|
|
122
|
+
const attemptErrors: string[] = [];
|
|
123
|
+
|
|
124
|
+
const result = await tryGeminiWeb(canonicalUrl, effectivePrompt, effectiveModel, signal, attemptErrors)
|
|
125
|
+
?? await tryGeminiApi(canonicalUrl, effectivePrompt, effectiveModel, signal, attemptErrors)
|
|
126
|
+
// Perplexity only summarizes the video, so ask for the browser login before settling for it.
|
|
127
|
+
?? (await requestBrowserCookieAccess(browserCookieConsent, signal) ? await tryGeminiWeb(canonicalUrl, effectivePrompt, effectiveModel, signal, attemptErrors) : null)
|
|
128
|
+
?? await tryPerplexity(url, effectivePrompt, signal, attemptErrors);
|
|
129
|
+
|
|
130
|
+
if (result) {
|
|
131
|
+
result.url = url;
|
|
132
|
+
if (!result.error && videoId && canAttachImages()) {
|
|
133
|
+
const thumb = await fetchYouTubeThumbnail(videoId);
|
|
134
|
+
if (thumb) result.thumbnail = thumb;
|
|
135
|
+
}
|
|
136
|
+
activityMonitor.logComplete(activityId, result.error ? 0 : 200);
|
|
137
|
+
return result;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (signal?.aborted) {
|
|
141
|
+
activityMonitor.logComplete(activityId, 0);
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const error = attemptErrors.length > 0
|
|
146
|
+
? ["Could not extract YouTube video content.", "", ...attemptErrors.map(message => `- ${message}`), ...(isBrowserCookieAccessAllowed() ? [] : ["", browserCookieAccessHint(browserCookieConsent)])].join("\n")
|
|
147
|
+
: youTubeAccessError(browserCookieConsent);
|
|
148
|
+
activityMonitor.logError(activityId, error);
|
|
149
|
+
return { url, title: "", content: "", error };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
type StreamInfo = { streamUrl: string; duration: number | null };
|
|
153
|
+
type StreamResult = StreamInfo | { error: string };
|
|
154
|
+
|
|
155
|
+
function mapYtDlpError(err: unknown): string {
|
|
156
|
+
const { code, stderr, message } = readExecError(err);
|
|
157
|
+
if (code === "ENOENT") return "yt-dlp is not installed. Install with: brew install yt-dlp";
|
|
158
|
+
if (isTimeoutError(err)) return "yt-dlp timed out fetching video info";
|
|
159
|
+
const lower = stderr.toLowerCase();
|
|
160
|
+
if (lower.includes("private")) return "Video is private or unavailable";
|
|
161
|
+
if (lower.includes("sign in")) return "Video is age-restricted and requires authentication";
|
|
162
|
+
if (lower.includes("not available")) return "Video is unavailable in your region or has been removed";
|
|
163
|
+
if (lower.includes("live")) return "Cannot extract frames from a live stream";
|
|
164
|
+
const snippet = trimErrorText(stderr || message);
|
|
165
|
+
return snippet ? `yt-dlp failed: ${snippet}` : "yt-dlp failed";
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function getYouTubeStreamInfo(videoId: string): Promise<StreamResult> {
|
|
169
|
+
try {
|
|
170
|
+
const output = execFileSync("yt-dlp", [
|
|
171
|
+
"--print", "duration",
|
|
172
|
+
"-g", `https://www.youtube.com/watch?v=${videoId}`,
|
|
173
|
+
], { timeout: 15000, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
|
|
174
|
+
const lines = output.split(/\r?\n/);
|
|
175
|
+
const rawDuration = lines[0]?.trim();
|
|
176
|
+
const streamUrl = lines[1]?.trim();
|
|
177
|
+
if (!streamUrl) return { error: "yt-dlp failed: missing stream URL" };
|
|
178
|
+
const parsedDuration = rawDuration && rawDuration !== "NA" ? Number.parseFloat(rawDuration) : NaN;
|
|
179
|
+
const duration = Number.isFinite(parsedDuration) ? parsedDuration : null;
|
|
180
|
+
return { streamUrl, duration };
|
|
181
|
+
} catch (err) {
|
|
182
|
+
return { error: mapYtDlpError(err) };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function extractFrameFromStream(streamUrl: string, seconds: number): Promise<FrameResult> {
|
|
187
|
+
try {
|
|
188
|
+
const buffer = execFileSync("ffmpeg", [
|
|
189
|
+
"-ss", String(seconds), "-i", streamUrl,
|
|
190
|
+
"-frames:v", "1", "-vf", FRAME_SCALE_FILTER, "-f", "image2pipe", "-vcodec", "mjpeg", "pipe:1",
|
|
191
|
+
], { maxBuffer: 5 * 1024 * 1024, timeout: 30000, stdio: ["pipe", "pipe", "pipe"] });
|
|
192
|
+
if (buffer.length === 0) return { error: "ffmpeg failed: empty output" };
|
|
193
|
+
return { data: buffer.toString("base64"), mimeType: "image/jpeg" };
|
|
194
|
+
} catch (err) {
|
|
195
|
+
return { error: mapFfmpegError(err) };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export async function extractYouTubeFrame(
|
|
200
|
+
videoId: string,
|
|
201
|
+
seconds: number,
|
|
202
|
+
streamInfo?: StreamInfo,
|
|
203
|
+
): Promise<FrameResult> {
|
|
204
|
+
const info = streamInfo ?? await getYouTubeStreamInfo(videoId);
|
|
205
|
+
if ("error" in info) return info;
|
|
206
|
+
return extractFrameFromStream(info.streamUrl, seconds);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export async function extractYouTubeFrames(
|
|
210
|
+
videoId: string,
|
|
211
|
+
timestamps: number[],
|
|
212
|
+
streamInfo?: StreamInfo,
|
|
213
|
+
): Promise<{ frames: VideoFrame[]; duration: number | null; error: string | null }> {
|
|
214
|
+
const info = streamInfo ?? await getYouTubeStreamInfo(videoId);
|
|
215
|
+
if ("error" in info) return { frames: [], duration: null, error: info.error };
|
|
216
|
+
const results = await Promise.all(timestamps.map(async (t) => {
|
|
217
|
+
const frame = await extractFrameFromStream(info.streamUrl, t);
|
|
218
|
+
if ("error" in frame) return { error: frame.error };
|
|
219
|
+
return { ...frame, timestamp: formatSeconds(t) };
|
|
220
|
+
}));
|
|
221
|
+
const frames = results.filter((f): f is VideoFrame => "data" in f);
|
|
222
|
+
const errorResult = results.find((f): f is { error: string } => "error" in f);
|
|
223
|
+
return { frames, duration: info.duration, error: frames.length === 0 && errorResult ? errorResult.error : null };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export async function fetchYouTubeThumbnail(videoId: string): Promise<{ data: string; mimeType: string } | null> {
|
|
227
|
+
try {
|
|
228
|
+
const res = await fetch(`https://img.youtube.com/vi/${videoId}/hqdefault.jpg`, {
|
|
229
|
+
signal: AbortSignal.timeout(5000),
|
|
230
|
+
});
|
|
231
|
+
if (!res.ok) return null;
|
|
232
|
+
const buffer = Buffer.from(await res.arrayBuffer());
|
|
233
|
+
if (buffer.length === 0) return null;
|
|
234
|
+
return { data: buffer.toString("base64"), mimeType: "image/jpeg" };
|
|
235
|
+
} catch {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function tryGeminiWeb(
|
|
241
|
+
url: string,
|
|
242
|
+
prompt: string,
|
|
243
|
+
model: string,
|
|
244
|
+
signal: AbortSignal | undefined,
|
|
245
|
+
attemptErrors: string[],
|
|
246
|
+
): Promise<ExtractedContent | null> {
|
|
247
|
+
try {
|
|
248
|
+
const cookies = await isGeminiWebAvailable();
|
|
249
|
+
if (!cookies) return null;
|
|
250
|
+
|
|
251
|
+
if (signal?.aborted) return null;
|
|
252
|
+
|
|
253
|
+
const text = await queryWithCookies(prompt, cookies, {
|
|
254
|
+
youtubeUrl: url,
|
|
255
|
+
...(model !== "gemini-3.6-flash" ? { model } : {}),
|
|
256
|
+
signal,
|
|
257
|
+
timeoutMs: 120000,
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
url,
|
|
262
|
+
title: extractHeadingTitle(text) ?? "YouTube Video",
|
|
263
|
+
content: text,
|
|
264
|
+
error: null,
|
|
265
|
+
};
|
|
266
|
+
} catch (err) {
|
|
267
|
+
if (shouldRethrow(err)) throw err;
|
|
268
|
+
if (!signal?.aborted) addAttemptError(attemptErrors, "Gemini Web", err);
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async function tryGeminiApi(
|
|
274
|
+
url: string,
|
|
275
|
+
prompt: string,
|
|
276
|
+
model: string,
|
|
277
|
+
signal: AbortSignal | undefined,
|
|
278
|
+
attemptErrors: string[],
|
|
279
|
+
): Promise<ExtractedContent | null> {
|
|
280
|
+
try {
|
|
281
|
+
if (!isGeminiApiAvailableWithVideo()) return null;
|
|
282
|
+
|
|
283
|
+
if (signal?.aborted) return null;
|
|
284
|
+
|
|
285
|
+
const text = await queryGeminiApiWithVideo(prompt, url, {
|
|
286
|
+
model,
|
|
287
|
+
signal,
|
|
288
|
+
timeoutMs: 120000,
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
return {
|
|
292
|
+
url,
|
|
293
|
+
title: extractHeadingTitle(text) ?? "YouTube Video",
|
|
294
|
+
content: text,
|
|
295
|
+
error: null,
|
|
296
|
+
};
|
|
297
|
+
} catch (err) {
|
|
298
|
+
if (shouldRethrow(err)) throw err;
|
|
299
|
+
if (!signal?.aborted) addAttemptError(attemptErrors, "Gemini API", err);
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function tryPerplexity(
|
|
305
|
+
url: string,
|
|
306
|
+
prompt: string,
|
|
307
|
+
signal: AbortSignal | undefined,
|
|
308
|
+
attemptErrors: string[],
|
|
309
|
+
): Promise<ExtractedContent | null> {
|
|
310
|
+
try {
|
|
311
|
+
if (signal?.aborted || !isPerplexityAvailable()) return null;
|
|
312
|
+
|
|
313
|
+
const perplexityQuery = prompt === YOUTUBE_PROMPT
|
|
314
|
+
? `Summarize this YouTube video in detail: ${url}`
|
|
315
|
+
: `${prompt} YouTube video: ${url}`;
|
|
316
|
+
|
|
317
|
+
const answer = await askPerplexity(perplexityQuery, { signal });
|
|
318
|
+
|
|
319
|
+
if (!answer) return null;
|
|
320
|
+
|
|
321
|
+
const content =
|
|
322
|
+
`# Video Summary (via Perplexity)\n\n${answer}\n\n` +
|
|
323
|
+
`*Full video understanding requires Gemini access. Set GEMINI_API_KEY, or: ${browserCookieAccessHintLine()}.*`;
|
|
324
|
+
|
|
325
|
+
return {
|
|
326
|
+
url,
|
|
327
|
+
title: "Video Summary (via Perplexity)",
|
|
328
|
+
content,
|
|
329
|
+
error: null,
|
|
330
|
+
};
|
|
331
|
+
} catch (err) {
|
|
332
|
+
if (shouldRethrow(err)) throw err;
|
|
333
|
+
if (!signal?.aborted) addAttemptError(attemptErrors, "Perplexity", err);
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
}
|
package/zai.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.ts";
|
|
3
|
+
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
|
|
4
|
+
import { normalizeDomain } from "./domain-filter-normalization.ts";
|
|
5
|
+
import type { SearchOptions, SearchResponse } from "./perplexity.ts";
|
|
6
|
+
import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
|
|
7
|
+
import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
|
|
8
|
+
import { getWebSearchConfigPath } from "./utils.ts";
|
|
9
|
+
|
|
10
|
+
// GLM Coding Plan keys are issued per site, so the user picks the matching endpoint.
|
|
11
|
+
const MCP_URLS = {
|
|
12
|
+
global: "https://api.z.ai/api/mcp/web_search_prime/mcp",
|
|
13
|
+
china: "https://open.bigmodel.cn/api/mcp/web_search_prime/mcp",
|
|
14
|
+
} as const;
|
|
15
|
+
const RECENCY = { day: "oneDay", week: "oneWeek", month: "oneMonth", year: "oneYear" } as const;
|
|
16
|
+
const SEARCH_TIMEOUT_MS = 60_000;
|
|
17
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
18
|
+
|
|
19
|
+
function loadConfig(): Record<string, unknown> {
|
|
20
|
+
if (!existsSync(CONFIG_PATH)) return {};
|
|
21
|
+
try {
|
|
22
|
+
const parsed: unknown = JSON.parse(readFileSync(CONFIG_PATH, "utf8"));
|
|
23
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
|
|
24
|
+
return parsed as Record<string, unknown>;
|
|
25
|
+
} catch {
|
|
26
|
+
// JSON parser errors may include a fragment containing a literal key.
|
|
27
|
+
throw new Error(`Invalid configuration in ${CONFIG_PATH}: expected a JSON object`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function credentialOptions(config: Record<string, unknown>) {
|
|
32
|
+
return { provider: "Z.ai", configuredValue: config.zaiApiKey, environmentValue: process.env.ZAI_API_KEY };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function endpointUrl(config: Record<string, unknown>): string {
|
|
36
|
+
const endpoint = config.zaiEndpoint ?? "global";
|
|
37
|
+
if (endpoint !== "global" && endpoint !== "china") {
|
|
38
|
+
throw new Error(`zaiEndpoint in ${CONFIG_PATH} must be "global" or "china"`);
|
|
39
|
+
}
|
|
40
|
+
return MCP_URLS[endpoint];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function isZaiAvailable(): boolean {
|
|
44
|
+
return hasCredentialSource(credentialOptions(loadConfig()));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function searchArguments(query: string, options: SearchOptions): Record<string, unknown> {
|
|
48
|
+
if (!query.trim()) throw new Error("Z.ai search query must not be empty");
|
|
49
|
+
const domains = (options.domainFilter ?? []).map((raw) => raw.trim()).filter(Boolean);
|
|
50
|
+
if (domains.length > 1 || domains.some((raw) => raw.startsWith("-"))) {
|
|
51
|
+
throw new Error("Z.ai domainFilter supports a single included domain");
|
|
52
|
+
}
|
|
53
|
+
const domain = domains[0] === undefined ? undefined : normalizeDomain(domains[0]);
|
|
54
|
+
if (domain === null) throw new Error("Z.ai domain filter must contain a valid domain");
|
|
55
|
+
return {
|
|
56
|
+
search_query: query.trim(),
|
|
57
|
+
...(options.recencyFilter ? { search_recency_filter: RECENCY[options.recencyFilter] } : {}),
|
|
58
|
+
...(domain ? { search_domain_filter: domain } : {}),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The tool returns its result list as JSON text, sometimes encoded twice. */
|
|
63
|
+
function parseResults(text: string, limit: number, domain: string | undefined): SearchResponse["results"] {
|
|
64
|
+
let value: unknown = JSON.parse(text);
|
|
65
|
+
if (typeof value === "string") value = JSON.parse(value);
|
|
66
|
+
if (!Array.isArray(value)) throw new Error("Z.ai returned invalid response: expected a result list");
|
|
67
|
+
const results: SearchResponse["results"] = [];
|
|
68
|
+
for (const entry of value) {
|
|
69
|
+
if (!entry || typeof entry !== "object") continue;
|
|
70
|
+
const { link, title, content } = entry as Record<string, unknown>;
|
|
71
|
+
if (typeof link !== "string") continue;
|
|
72
|
+
let url: URL;
|
|
73
|
+
try {
|
|
74
|
+
url = new URL(link);
|
|
75
|
+
} catch {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") continue;
|
|
79
|
+
// The remote filter is undocumented, so enforce it locally too.
|
|
80
|
+
const host = url.hostname.toLowerCase().replace(/\.+$/, "");
|
|
81
|
+
if (domain && host !== domain && !host.endsWith(`.${domain}`)) continue;
|
|
82
|
+
results.push({
|
|
83
|
+
title: typeof title === "string" && title.trim() ? title.trim() : `Source ${results.length + 1}`,
|
|
84
|
+
url: url.href,
|
|
85
|
+
snippet: typeof content === "string" ? content : "",
|
|
86
|
+
});
|
|
87
|
+
if (results.length >= limit) break;
|
|
88
|
+
}
|
|
89
|
+
return results;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function searchWithZai(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
|
|
93
|
+
const config = loadConfig();
|
|
94
|
+
const mcpUrl = endpointUrl(config);
|
|
95
|
+
const args = searchArguments(query, options);
|
|
96
|
+
const limit = normalizeSearchResultCount(options.numResults);
|
|
97
|
+
const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
|
|
98
|
+
const signal = options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
|
|
99
|
+
if (signal.aborted) throw new Error("Aborted");
|
|
100
|
+
const apiKey = await resolveCredential({ ...credentialOptions(config), signal });
|
|
101
|
+
if (!apiKey) throw new Error("Z.ai API key not found. Set ZAI_API_KEY or zaiApiKey in web-search.json with a GLM Coding Plan key.");
|
|
102
|
+
let headers: Headers;
|
|
103
|
+
try { headers = new Headers({ Authorization: `Bearer ${apiKey}` }); }
|
|
104
|
+
catch { throw new Error("Z.ai credential resolution failed: invalid-header-value"); }
|
|
105
|
+
// Load the protocol client only when this explicit provider is selected.
|
|
106
|
+
const [{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([
|
|
107
|
+
import("@modelcontextprotocol/sdk/client/index.js"),
|
|
108
|
+
import("@modelcontextprotocol/sdk/client/streamableHttp.js"),
|
|
109
|
+
]);
|
|
110
|
+
let cleaningUp = false;
|
|
111
|
+
const transport = new StreamableHTTPClientTransport(new URL(mcpUrl), {
|
|
112
|
+
requestInit: { headers },
|
|
113
|
+
fetch: async (url, init) => {
|
|
114
|
+
// Fixed endpoint, no redirects: neither credentials nor session IDs can
|
|
115
|
+
// be forwarded to another origin (including MCP discovery redirects).
|
|
116
|
+
if (String(url) !== mcpUrl) throw new Error("Z.ai endpoint changed unexpectedly");
|
|
117
|
+
const requestSignal = cleaningUp ? AbortSignal.timeout(1_500) : signal;
|
|
118
|
+
return fetch(url, { ...init, redirect: "error", signal: !cleaningUp && init?.signal ? AbortSignal.any([init.signal, requestSignal]) : requestSignal });
|
|
119
|
+
},
|
|
120
|
+
reconnectionOptions: { maxRetries: 0, initialReconnectionDelay: 1_000, maxReconnectionDelay: 1_000, reconnectionDelayGrowFactor: 1 },
|
|
121
|
+
});
|
|
122
|
+
const client = new Client({ name: "pi-web-access-zai", version: "1.0.0" });
|
|
123
|
+
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
124
|
+
try {
|
|
125
|
+
await client.connect(transport, { signal, timeout: SEARCH_TIMEOUT_MS });
|
|
126
|
+
// The live China server lists `web_search_prime` while both sites document
|
|
127
|
+
// `webSearchPrime`, so call whichever name this server exposes.
|
|
128
|
+
const { tools } = await client.listTools(undefined, { signal, timeout: SEARCH_TIMEOUT_MS });
|
|
129
|
+
const toolName = tools.find((tool) => tool.name === "web_search_prime" || tool.name === "webSearchPrime")?.name;
|
|
130
|
+
if (!toolName) throw new Error("Z.ai returned invalid response: web search tool not listed");
|
|
131
|
+
const result = await client.callTool({ name: toolName, arguments: args }, undefined, { signal, timeout: SEARCH_TIMEOUT_MS });
|
|
132
|
+
if (result.isError) throw new Error("Z.ai search tool returned an error");
|
|
133
|
+
const text = (Array.isArray(result.content) ? result.content : []).find((item) => item.type === "text" && typeof item.text === "string");
|
|
134
|
+
if (!text) throw new Error("Z.ai returned invalid response: no search text");
|
|
135
|
+
const results = parseResults(text.text as string, limit, args.search_domain_filter as string | undefined);
|
|
136
|
+
activityMonitor.logComplete(activityId, 200);
|
|
137
|
+
return { answer: formatSearchResultsAsAnswer(results), results };
|
|
138
|
+
} catch (err) {
|
|
139
|
+
let message: string;
|
|
140
|
+
if (options.signal?.aborted) message = "Aborted";
|
|
141
|
+
else if (timeoutSignal.aborted) message = "Z.ai request timed out after 60s";
|
|
142
|
+
else {
|
|
143
|
+
const code = err && typeof err === "object" && "code" in err ? err.code : undefined;
|
|
144
|
+
// Never expose remote HTTP/JSON-RPC bodies or nested SDK errors: they
|
|
145
|
+
// can echo credentials in plain, encoded or transformed form.
|
|
146
|
+
message = typeof code === "number" && Number.isInteger(code) && code >= 400 && code <= 599
|
|
147
|
+
? `Z.ai HTTP ${code} request failed; check your GLM Coding Plan key, zaiEndpoint and plan quota`
|
|
148
|
+
: err instanceof TypeError ? "Z.ai network request failed"
|
|
149
|
+
: err instanceof SyntaxError || code === -32700 || code === -32602 ? "Z.ai returned invalid response"
|
|
150
|
+
: err instanceof Error && /^Z\.ai (search tool returned an error|returned invalid response:)/.test(err.message) ? err.message
|
|
151
|
+
: "Z.ai MCP request failed; check your connection and GLM Coding Plan key";
|
|
152
|
+
}
|
|
153
|
+
activityMonitor.logError(activityId, redactCredential(message, apiKey));
|
|
154
|
+
throw new Error(message);
|
|
155
|
+
} finally {
|
|
156
|
+
cleaningUp = true;
|
|
157
|
+
// Best effort, separately bounded DELETE; always close the local streams.
|
|
158
|
+
try { await transport.terminateSession(); } catch { /* Server may not support DELETE. */ }
|
|
159
|
+
await client.close();
|
|
160
|
+
}
|
|
161
|
+
}
|