@duckmind/dm-windows-x64 0.62.9 → 0.63.4
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/dm.exe +0 -0
- package/extensions/.dm-extensions.json +140 -4
- package/extensions/dm-ponytail/extensions/ponytail.mjs +1 -1
- package/extensions/dm-web-access/SECURITY.md +5 -0
- package/extensions/dm-web-access/activity.js +65 -0
- package/extensions/dm-web-access/anysearch.js +158 -0
- package/extensions/dm-web-access/auth-fetch.js +131 -0
- package/extensions/dm-web-access/bocha.js +214 -0
- package/extensions/dm-web-access/brave.js +196 -0
- package/extensions/dm-web-access/brightdata-unlocker.js +202 -0
- package/extensions/dm-web-access/brightdata.js +334 -0
- package/extensions/dm-web-access/chrome-cookies.js +627 -0
- package/extensions/dm-web-access/content-find.js +114 -0
- package/extensions/dm-web-access/credential-source.js +150 -0
- package/extensions/dm-web-access/curator-page.js +3559 -0
- package/extensions/dm-web-access/curator-server.js +691 -0
- package/extensions/dm-web-access/data-uri-sanitize.js +312 -0
- package/extensions/dm-web-access/datalab-pdf-extract.js +346 -0
- package/extensions/dm-web-access/declared-web-links.js +167 -0
- package/extensions/dm-web-access/dm-web-fetch-demo.mp4 +0 -0
- package/extensions/dm-web-access/duckduckgo.js +118 -0
- package/extensions/dm-web-access/exa.js +401 -0
- package/extensions/dm-web-access/extract.js +1220 -0
- package/extensions/dm-web-access/feature-config.js +24 -0
- package/extensions/dm-web-access/fetch-params.js +81 -0
- package/extensions/dm-web-access/firecrawl.js +378 -0
- package/extensions/dm-web-access/gemini-adc.js +241 -0
- package/extensions/dm-web-access/gemini-api.js +258 -0
- package/extensions/dm-web-access/gemini-pdf-extract.js +74 -0
- package/extensions/dm-web-access/gemini-search.js +889 -0
- package/extensions/dm-web-access/gemini-url-context.js +97 -0
- package/extensions/dm-web-access/gemini-web-config.js +84 -0
- package/extensions/dm-web-access/gemini-web.js +351 -0
- package/extensions/dm-web-access/github-api.js +166 -0
- package/extensions/dm-web-access/github-extract.js +991 -0
- package/extensions/dm-web-access/github-issue-pr.js +750 -0
- package/extensions/dm-web-access/index.js +3117 -0
- package/extensions/dm-web-access/jina-search.js +242 -0
- package/extensions/dm-web-access/kagi.js +255 -0
- package/extensions/dm-web-access/kimi-search.js +214 -0
- package/extensions/dm-web-access/ollama.js +209 -0
- package/extensions/dm-web-access/openai-search.js +510 -0
- package/extensions/dm-web-access/package.json +34 -0
- package/extensions/dm-web-access/page-query.js +124 -0
- package/extensions/dm-web-access/parallel-mcp.js +223 -0
- package/extensions/dm-web-access/parallel.js +345 -0
- package/extensions/dm-web-access/pdf-extract.js +257 -0
- package/extensions/dm-web-access/perplexity.js +151 -0
- package/extensions/dm-web-access/querit.js +327 -0
- package/extensions/dm-web-access/query-rewrite.js +40 -0
- package/extensions/dm-web-access/render-search-error.js +80 -0
- package/extensions/dm-web-access/rsc-extract.js +347 -0
- package/extensions/dm-web-access/search1api.js +245 -0
- package/extensions/dm-web-access/searchinfinity.js +221 -0
- package/extensions/dm-web-access/searxng.js +223 -0
- package/extensions/dm-web-access/serpbase.js +205 -0
- package/extensions/dm-web-access/serpdive.js +238 -0
- package/extensions/dm-web-access/serper.js +200 -0
- package/extensions/dm-web-access/source-check.js +198 -0
- package/extensions/dm-web-access/ssrf-protection.js +436 -0
- package/extensions/dm-web-access/storage.js +451 -0
- package/extensions/dm-web-access/summary-model-scope.js +83 -0
- package/extensions/dm-web-access/summary-review.js +364 -0
- package/extensions/dm-web-access/tavily.js +199 -0
- package/extensions/dm-web-access/tinyfish.js +325 -0
- package/extensions/dm-web-access/utils.js +476 -0
- package/extensions/dm-web-access/valyu.js +189 -0
- package/extensions/dm-web-access/video-extract.js +336 -0
- package/extensions/dm-web-access/xai-search.js +285 -0
- package/extensions/dm-web-access/xcrawl.js +221 -0
- package/extensions/dm-web-access/youtube-extract.js +279 -0
- package/package.json +9 -1
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { resolve, extname, basename, join, dirname } from "node:path";
|
|
5
|
+
import { activityMonitor } from "./activity.js";
|
|
6
|
+
import { canAttachImages } from "./feature-config.js";
|
|
7
|
+
import { isGeminiWebAvailable, queryWithCookies } from "./gemini-web.js";
|
|
8
|
+
import { queryGeminiApiWithVideo, getApiKey, fetchGeminiApi, getVersionedApiBase, getUploadBase, redactGeminiApiResponse } from "./gemini-api.js";
|
|
9
|
+
import { extractHeadingTitle } from "./extract.js";
|
|
10
|
+
import { readExecError, trimErrorText, mapFfmpegError, getWebSearchConfigPath } from "./utils.js";
|
|
11
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
12
|
+
const DEFAULT_VIDEO_PROMPT = `Extract the complete content of this video. Include:
|
|
13
|
+
1. Video title (infer from content if not explicit), duration
|
|
14
|
+
2. A brief summary (2-3 sentences)
|
|
15
|
+
3. Full transcript with timestamps
|
|
16
|
+
4. Descriptions of any code, terminal commands, diagrams, slides, or UI shown on screen
|
|
17
|
+
|
|
18
|
+
Format as markdown.`;
|
|
19
|
+
const VIDEO_EXTENSIONS = {
|
|
20
|
+
".mp4": "video/mp4",
|
|
21
|
+
".mov": "video/quicktime",
|
|
22
|
+
".webm": "video/webm",
|
|
23
|
+
".avi": "video/x-msvideo",
|
|
24
|
+
".mpeg": "video/mpeg",
|
|
25
|
+
".mpg": "video/mpeg",
|
|
26
|
+
".wmv": "video/x-ms-wmv",
|
|
27
|
+
".flv": "video/x-flv",
|
|
28
|
+
".3gp": "video/3gpp",
|
|
29
|
+
".3gpp": "video/3gpp"
|
|
30
|
+
};
|
|
31
|
+
function shouldRethrow(err) {
|
|
32
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
33
|
+
return message.startsWith("Failed to parse ");
|
|
34
|
+
}
|
|
35
|
+
function normalizePreferredModel(value, fallback) {
|
|
36
|
+
if (typeof value !== "string")
|
|
37
|
+
return fallback;
|
|
38
|
+
const normalized = value.trim();
|
|
39
|
+
return normalized.length > 0 ? normalized : fallback;
|
|
40
|
+
}
|
|
41
|
+
function normalizeEnabled(value, fallback) {
|
|
42
|
+
return typeof value === "boolean" ? value : fallback;
|
|
43
|
+
}
|
|
44
|
+
function normalizeMaxSizeMB(value, fallback) {
|
|
45
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
46
|
+
return fallback;
|
|
47
|
+
return value > 0 ? value : fallback;
|
|
48
|
+
}
|
|
49
|
+
const VIDEO_CONFIG_DEFAULTS = {
|
|
50
|
+
enabled: true,
|
|
51
|
+
preferredModel: "gemini-3.6-flash",
|
|
52
|
+
maxSizeMB: 50
|
|
53
|
+
};
|
|
54
|
+
let cachedVideoConfig = null;
|
|
55
|
+
function loadVideoConfig() {
|
|
56
|
+
if (cachedVideoConfig)
|
|
57
|
+
return cachedVideoConfig;
|
|
58
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
59
|
+
cachedVideoConfig = { ...VIDEO_CONFIG_DEFAULTS };
|
|
60
|
+
return cachedVideoConfig;
|
|
61
|
+
}
|
|
62
|
+
const rawText = readFileSync(CONFIG_PATH, "utf-8");
|
|
63
|
+
let raw;
|
|
64
|
+
try {
|
|
65
|
+
raw = JSON.parse(rawText);
|
|
66
|
+
} catch (err) {
|
|
67
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
68
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
69
|
+
}
|
|
70
|
+
const v = raw.video ?? {};
|
|
71
|
+
cachedVideoConfig = {
|
|
72
|
+
enabled: normalizeEnabled(v.enabled, VIDEO_CONFIG_DEFAULTS.enabled),
|
|
73
|
+
preferredModel: normalizePreferredModel(v.preferredModel, VIDEO_CONFIG_DEFAULTS.preferredModel),
|
|
74
|
+
maxSizeMB: normalizeMaxSizeMB(v.maxSizeMB, VIDEO_CONFIG_DEFAULTS.maxSizeMB)
|
|
75
|
+
};
|
|
76
|
+
return cachedVideoConfig;
|
|
77
|
+
}
|
|
78
|
+
export function isVideoFile(input) {
|
|
79
|
+
const config = loadVideoConfig();
|
|
80
|
+
if (!config.enabled)
|
|
81
|
+
return null;
|
|
82
|
+
const isFilePath = input.startsWith("/") || input.startsWith("./") || input.startsWith("../") || input.startsWith("file://");
|
|
83
|
+
if (!isFilePath)
|
|
84
|
+
return null;
|
|
85
|
+
let filePath = input;
|
|
86
|
+
if (input.startsWith("file://")) {
|
|
87
|
+
try {
|
|
88
|
+
filePath = decodeURIComponent(new URL(input).pathname);
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const ext = extname(filePath).toLowerCase();
|
|
94
|
+
const mimeType = VIDEO_EXTENSIONS[ext];
|
|
95
|
+
if (!mimeType)
|
|
96
|
+
return null;
|
|
97
|
+
const absolutePath = resolveFilePath(filePath);
|
|
98
|
+
if (!absolutePath)
|
|
99
|
+
return null;
|
|
100
|
+
let stat;
|
|
101
|
+
try {
|
|
102
|
+
stat = statSync(absolutePath);
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
if (!stat.isFile())
|
|
107
|
+
return null;
|
|
108
|
+
const maxBytes = config.maxSizeMB * 1024 * 1024;
|
|
109
|
+
return {
|
|
110
|
+
absolutePath,
|
|
111
|
+
mimeType,
|
|
112
|
+
sizeBytes: stat.size,
|
|
113
|
+
maxSizeBytes: maxBytes,
|
|
114
|
+
withinUploadLimit: stat.size <= maxBytes
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function resolveFilePath(filePath) {
|
|
118
|
+
const absolutePath = resolve(filePath);
|
|
119
|
+
if (existsSync(absolutePath))
|
|
120
|
+
return absolutePath;
|
|
121
|
+
const dir = dirname(absolutePath);
|
|
122
|
+
const base = basename(absolutePath);
|
|
123
|
+
if (!existsSync(dir))
|
|
124
|
+
return null;
|
|
125
|
+
try {
|
|
126
|
+
const normalizedBase = normalizeSpaces(base);
|
|
127
|
+
const match = readdirSync(dir).find((f) => normalizeSpaces(f) === normalizedBase);
|
|
128
|
+
return match ? join(dir, match) : null;
|
|
129
|
+
} catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function normalizeSpaces(s) {
|
|
134
|
+
return s.replace(/[\u00A0\u2000-\u200B\u202F\u205F\u3000\uFEFF]/g, " ");
|
|
135
|
+
}
|
|
136
|
+
export async function extractVideo(info, signal, options) {
|
|
137
|
+
const config = loadVideoConfig();
|
|
138
|
+
const effectivePrompt = options?.prompt ?? DEFAULT_VIDEO_PROMPT;
|
|
139
|
+
const effectiveModel = options?.model ?? config.preferredModel;
|
|
140
|
+
const displayName = basename(info.absolutePath);
|
|
141
|
+
if (!info.withinUploadLimit) {
|
|
142
|
+
const sizeMB = (info.sizeBytes / 1024 / 1024).toFixed(1);
|
|
143
|
+
const maxSizeMB = (info.maxSizeBytes / 1024 / 1024).toFixed(1);
|
|
144
|
+
const error = `Local video ${displayName} is ${sizeMB} MiB, above configured video.maxSizeMB (${maxSizeMB} MiB) for Gemini analysis. Use timestamp/frames for ffmpeg frame extraction, increase video.maxSizeMB, or compress the file.`;
|
|
145
|
+
return { url: info.absolutePath, title: displayName, content: error, error };
|
|
146
|
+
}
|
|
147
|
+
const activityId = activityMonitor.logStart({ type: "fetch", url: `video:${displayName}` });
|
|
148
|
+
const result = await tryVideoGeminiApi(info, effectivePrompt, effectiveModel, signal) ?? await tryVideoGeminiWeb(info, effectivePrompt, effectiveModel, signal);
|
|
149
|
+
if (result) {
|
|
150
|
+
if (canAttachImages()) {
|
|
151
|
+
const thumbnail = await extractVideoFrame(info.absolutePath);
|
|
152
|
+
if (!("error" in thumbnail)) {
|
|
153
|
+
result.thumbnail = thumbnail;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
activityMonitor.logComplete(activityId, 200);
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
if (signal?.aborted) {
|
|
160
|
+
activityMonitor.logComplete(activityId, 0);
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
activityMonitor.logError(activityId, "all video extraction paths failed");
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
function mapFfprobeError(err) {
|
|
167
|
+
const { code, stderr, message } = readExecError(err);
|
|
168
|
+
if (code === "ENOENT")
|
|
169
|
+
return "ffprobe is not installed. Install ffmpeg which includes ffprobe";
|
|
170
|
+
const snippet = trimErrorText(stderr || message);
|
|
171
|
+
return snippet ? `ffprobe failed: ${snippet}` : "ffprobe failed";
|
|
172
|
+
}
|
|
173
|
+
export async function extractVideoFrame(filePath, seconds = 1) {
|
|
174
|
+
try {
|
|
175
|
+
const buffer = execFileSync("ffmpeg", [
|
|
176
|
+
"-ss",
|
|
177
|
+
String(seconds),
|
|
178
|
+
"-i",
|
|
179
|
+
filePath,
|
|
180
|
+
"-frames:v",
|
|
181
|
+
"1",
|
|
182
|
+
"-f",
|
|
183
|
+
"image2pipe",
|
|
184
|
+
"-vcodec",
|
|
185
|
+
"mjpeg",
|
|
186
|
+
"pipe:1"
|
|
187
|
+
], { maxBuffer: 5 * 1024 * 1024, timeout: 1e4, stdio: ["pipe", "pipe", "pipe"] });
|
|
188
|
+
if (buffer.length === 0)
|
|
189
|
+
return { error: "ffmpeg failed: empty output" };
|
|
190
|
+
return { data: buffer.toString("base64"), mimeType: "image/jpeg" };
|
|
191
|
+
} catch (err) {
|
|
192
|
+
return { error: mapFfmpegError(err) };
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
export async function getLocalVideoDuration(filePath) {
|
|
196
|
+
try {
|
|
197
|
+
const output = execFileSync("ffprobe", [
|
|
198
|
+
"-v",
|
|
199
|
+
"quiet",
|
|
200
|
+
"-show_entries",
|
|
201
|
+
"format=duration",
|
|
202
|
+
"-of",
|
|
203
|
+
"csv=p=0",
|
|
204
|
+
filePath
|
|
205
|
+
], { timeout: 1e4, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
|
|
206
|
+
const duration = Number.parseFloat(output);
|
|
207
|
+
if (!Number.isFinite(duration))
|
|
208
|
+
return { error: "ffprobe failed: invalid duration output" };
|
|
209
|
+
return duration;
|
|
210
|
+
} catch (err) {
|
|
211
|
+
return { error: mapFfprobeError(err) };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
async function tryVideoGeminiWeb(info, prompt, model, signal) {
|
|
215
|
+
try {
|
|
216
|
+
const cookies = await isGeminiWebAvailable();
|
|
217
|
+
if (!cookies)
|
|
218
|
+
return null;
|
|
219
|
+
if (signal?.aborted)
|
|
220
|
+
return null;
|
|
221
|
+
const text = await queryWithCookies(prompt, cookies, {
|
|
222
|
+
files: [info.absolutePath],
|
|
223
|
+
...model !== "gemini-3.6-flash" ? { model } : {},
|
|
224
|
+
signal,
|
|
225
|
+
timeoutMs: 180000
|
|
226
|
+
});
|
|
227
|
+
return {
|
|
228
|
+
url: info.absolutePath,
|
|
229
|
+
title: extractVideoTitle(text, info.absolutePath),
|
|
230
|
+
content: text,
|
|
231
|
+
error: null
|
|
232
|
+
};
|
|
233
|
+
} catch (err) {
|
|
234
|
+
if (shouldRethrow(err))
|
|
235
|
+
throw err;
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async function tryVideoGeminiApi(info, prompt, model, signal) {
|
|
240
|
+
const apiKey = await getApiKey(signal);
|
|
241
|
+
if (!apiKey)
|
|
242
|
+
return null;
|
|
243
|
+
if (signal?.aborted)
|
|
244
|
+
return null;
|
|
245
|
+
let fileName = null;
|
|
246
|
+
try {
|
|
247
|
+
const uploaded = await uploadToFilesApi(info, apiKey, signal);
|
|
248
|
+
fileName = uploaded.name;
|
|
249
|
+
await pollFileState(fileName, apiKey, signal, 120000);
|
|
250
|
+
const text = await queryGeminiApiWithVideo(prompt, uploaded.uri, {
|
|
251
|
+
apiKey,
|
|
252
|
+
model,
|
|
253
|
+
mimeType: info.mimeType,
|
|
254
|
+
signal,
|
|
255
|
+
timeoutMs: 120000
|
|
256
|
+
});
|
|
257
|
+
return {
|
|
258
|
+
url: info.absolutePath,
|
|
259
|
+
title: extractVideoTitle(text, info.absolutePath),
|
|
260
|
+
content: text,
|
|
261
|
+
error: null
|
|
262
|
+
};
|
|
263
|
+
} catch (err) {
|
|
264
|
+
if (shouldRethrow(err))
|
|
265
|
+
throw err;
|
|
266
|
+
return null;
|
|
267
|
+
} finally {
|
|
268
|
+
if (fileName)
|
|
269
|
+
deleteGeminiFile(fileName, apiKey);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
async function uploadToFilesApi(info, apiKey, signal) {
|
|
273
|
+
const displayName = basename(info.absolutePath);
|
|
274
|
+
const initRes = await fetchGeminiApi(`${getUploadBase()}/files`, {
|
|
275
|
+
method: "POST",
|
|
276
|
+
headers: {
|
|
277
|
+
"X-Goog-Upload-Protocol": "resumable",
|
|
278
|
+
"X-Goog-Upload-Command": "start",
|
|
279
|
+
"X-Goog-Upload-Header-Content-Length": String(info.sizeBytes),
|
|
280
|
+
"X-Goog-Upload-Header-Content-Type": info.mimeType,
|
|
281
|
+
"Content-Type": "application/json"
|
|
282
|
+
},
|
|
283
|
+
body: JSON.stringify({ file: { display_name: displayName } }),
|
|
284
|
+
signal
|
|
285
|
+
}, apiKey);
|
|
286
|
+
if (!initRes.ok) {
|
|
287
|
+
const text = redactGeminiApiResponse(initRes, await initRes.text(), apiKey);
|
|
288
|
+
throw new Error(`File upload init failed: ${initRes.status} (${text.slice(0, 200)})`);
|
|
289
|
+
}
|
|
290
|
+
const uploadUrl = initRes.headers.get("x-goog-upload-url");
|
|
291
|
+
if (!uploadUrl)
|
|
292
|
+
throw new Error("No upload URL in response headers");
|
|
293
|
+
const fileData = await readFile(info.absolutePath);
|
|
294
|
+
const uploadRes = await fetchGeminiApi(uploadUrl, {
|
|
295
|
+
method: "PUT",
|
|
296
|
+
headers: {
|
|
297
|
+
"Content-Length": String(info.sizeBytes),
|
|
298
|
+
"X-Goog-Upload-Offset": "0",
|
|
299
|
+
"X-Goog-Upload-Command": "upload, finalize"
|
|
300
|
+
},
|
|
301
|
+
body: fileData,
|
|
302
|
+
signal
|
|
303
|
+
}, apiKey);
|
|
304
|
+
if (!uploadRes.ok) {
|
|
305
|
+
const text = redactGeminiApiResponse(uploadRes, await uploadRes.text(), apiKey);
|
|
306
|
+
throw new Error(`File upload failed: ${uploadRes.status} (${text.slice(0, 200)})`);
|
|
307
|
+
}
|
|
308
|
+
const result = await uploadRes.json();
|
|
309
|
+
return result.file;
|
|
310
|
+
}
|
|
311
|
+
async function pollFileState(fileName, apiKey, signal, timeoutMs = 120000) {
|
|
312
|
+
const deadline = Date.now() + timeoutMs;
|
|
313
|
+
while (Date.now() < deadline) {
|
|
314
|
+
if (signal?.aborted)
|
|
315
|
+
throw new Error("Aborted");
|
|
316
|
+
const res = await fetchGeminiApi(`${getVersionedApiBase()}/${fileName}`, { signal }, apiKey);
|
|
317
|
+
if (!res.ok)
|
|
318
|
+
throw new Error(`File state check failed: ${res.status}`);
|
|
319
|
+
const data = await res.json();
|
|
320
|
+
if (data.state === "ACTIVE")
|
|
321
|
+
return;
|
|
322
|
+
if (data.state === "FAILED")
|
|
323
|
+
throw new Error("File processing failed");
|
|
324
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
325
|
+
}
|
|
326
|
+
throw new Error("File processing timed out");
|
|
327
|
+
}
|
|
328
|
+
function deleteGeminiFile(fileName, apiKey) {
|
|
329
|
+
fetchGeminiApi(`${getVersionedApiBase()}/${fileName}`, { method: "DELETE" }, apiKey).catch((err) => {
|
|
330
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
331
|
+
console.error(`Failed to delete Gemini file ${fileName}: ${message}`);
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
function extractVideoTitle(text, filePath) {
|
|
335
|
+
return extractHeadingTitle(text) ?? basename(filePath, extname(filePath));
|
|
336
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.js";
|
|
3
|
+
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.js";
|
|
4
|
+
import { getWebSearchConfigPath } from "./utils.js";
|
|
5
|
+
const XAI_RESPONSES_URL = "https://api.x.ai/v1/responses";
|
|
6
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
7
|
+
const SEARCH_TIMEOUT_MS = 60000;
|
|
8
|
+
const AUTH_MODEL_CANDIDATES = ["grok-4.5", "grok-4.3", "grok-build-0.1"];
|
|
9
|
+
let cachedConfig = null;
|
|
10
|
+
function loadConfig() {
|
|
11
|
+
if (cachedConfig)
|
|
12
|
+
return cachedConfig;
|
|
13
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
14
|
+
cachedConfig = {};
|
|
15
|
+
return cachedConfig;
|
|
16
|
+
}
|
|
17
|
+
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
|
18
|
+
try {
|
|
19
|
+
cachedConfig = JSON.parse(raw);
|
|
20
|
+
return cachedConfig;
|
|
21
|
+
} catch (err) {
|
|
22
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
23
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function resolveConfiguredSearchModel(value) {
|
|
27
|
+
if (value == null)
|
|
28
|
+
return;
|
|
29
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
30
|
+
throw new Error(`xaiSearchModel in ${CONFIG_PATH} must be a non-empty string`);
|
|
31
|
+
}
|
|
32
|
+
return value.trim();
|
|
33
|
+
}
|
|
34
|
+
function toRequestHeaders(headers) {
|
|
35
|
+
const requestHeaders = {};
|
|
36
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
37
|
+
if (value !== null)
|
|
38
|
+
requestHeaders[name] = value;
|
|
39
|
+
}
|
|
40
|
+
return requestHeaders;
|
|
41
|
+
}
|
|
42
|
+
async function resolvePiAuth(ctx, modelOverride) {
|
|
43
|
+
for (const modelId of AUTH_MODEL_CANDIDATES) {
|
|
44
|
+
try {
|
|
45
|
+
const model = ctx.modelRegistry.find("xai", modelId);
|
|
46
|
+
if (!model)
|
|
47
|
+
continue;
|
|
48
|
+
const resolved = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
49
|
+
if (resolved.ok && resolved.apiKey) {
|
|
50
|
+
return { apiKey: resolved.apiKey, model: modelOverride ?? modelId, headers: resolved.headers ?? {} };
|
|
51
|
+
}
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
export async function resolveXaiAuth(ctx, signal) {
|
|
57
|
+
const config = loadConfig();
|
|
58
|
+
const modelOverride = resolveConfiguredSearchModel(config.xaiSearchModel);
|
|
59
|
+
if (ctx) {
|
|
60
|
+
const auth = await resolvePiAuth(ctx, modelOverride);
|
|
61
|
+
if (auth)
|
|
62
|
+
return auth;
|
|
63
|
+
}
|
|
64
|
+
const hasSource = hasCredentialSource({
|
|
65
|
+
provider: "xAI",
|
|
66
|
+
configuredValue: config.xaiApiKey,
|
|
67
|
+
environmentValue: process.env.XAI_API_KEY
|
|
68
|
+
});
|
|
69
|
+
if (!hasSource)
|
|
70
|
+
return;
|
|
71
|
+
const apiKey = await resolveCredential({
|
|
72
|
+
provider: "xAI",
|
|
73
|
+
configuredValue: config.xaiApiKey,
|
|
74
|
+
environmentValue: process.env.XAI_API_KEY,
|
|
75
|
+
signal
|
|
76
|
+
});
|
|
77
|
+
return apiKey ? { apiKey, model: modelOverride ?? AUTH_MODEL_CANDIDATES[0], headers: {} } : undefined;
|
|
78
|
+
}
|
|
79
|
+
export async function isXaiSearchAvailable(ctx) {
|
|
80
|
+
if (ctx && await resolvePiAuth(ctx))
|
|
81
|
+
return true;
|
|
82
|
+
const config = loadConfig();
|
|
83
|
+
return hasCredentialSource({
|
|
84
|
+
provider: "xAI",
|
|
85
|
+
configuredValue: config.xaiApiKey,
|
|
86
|
+
environmentValue: process.env.XAI_API_KEY
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function normalizeDomain(value) {
|
|
90
|
+
let input = value.trim().toLowerCase();
|
|
91
|
+
if (!input)
|
|
92
|
+
return null;
|
|
93
|
+
if (input.startsWith("-"))
|
|
94
|
+
input = input.slice(1).trim();
|
|
95
|
+
if (!input)
|
|
96
|
+
return null;
|
|
97
|
+
try {
|
|
98
|
+
const parsed = input.includes("://") ? new URL(input) : new URL(`https://${input}`);
|
|
99
|
+
input = parsed.hostname;
|
|
100
|
+
} catch {
|
|
101
|
+
input = input.split("/")[0]?.split(":")[0] ?? "";
|
|
102
|
+
}
|
|
103
|
+
input = input.replace(/^\.+|\.+$/g, "");
|
|
104
|
+
return /^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(input) ? input : null;
|
|
105
|
+
}
|
|
106
|
+
function buildInput(query, options) {
|
|
107
|
+
const lines = [
|
|
108
|
+
"Search the web and answer using only what the web results say.",
|
|
109
|
+
"Cite your sources inline."
|
|
110
|
+
];
|
|
111
|
+
if (options.recencyFilter) {
|
|
112
|
+
const labels = {
|
|
113
|
+
day: "past 24 hours",
|
|
114
|
+
week: "past week",
|
|
115
|
+
month: "past month",
|
|
116
|
+
year: "past year"
|
|
117
|
+
};
|
|
118
|
+
lines.push(`Prefer sources from the ${labels[options.recencyFilter]}.`);
|
|
119
|
+
}
|
|
120
|
+
if (typeof options.numResults === "number" && Number.isFinite(options.numResults) && options.numResults > 0) {
|
|
121
|
+
lines.push(`Prefer around ${Math.min(Math.floor(options.numResults), 20)} distinct sources.`);
|
|
122
|
+
}
|
|
123
|
+
const allowed = [];
|
|
124
|
+
const blocked = [];
|
|
125
|
+
for (const raw of options.domainFilter ?? []) {
|
|
126
|
+
const domain = normalizeDomain(raw);
|
|
127
|
+
if (!domain)
|
|
128
|
+
continue;
|
|
129
|
+
const target = raw.trim().startsWith("-") ? blocked : allowed;
|
|
130
|
+
if (!target.includes(domain))
|
|
131
|
+
target.push(domain);
|
|
132
|
+
}
|
|
133
|
+
if (allowed.length > 0)
|
|
134
|
+
lines.push(`Only use sources from: ${allowed.slice(0, 100).join(", ")}.`);
|
|
135
|
+
if (blocked.length > 0)
|
|
136
|
+
lines.push(`Do not use sources from: ${blocked.slice(0, 100).join(", ")}.`);
|
|
137
|
+
return `${lines.join(" ")}
|
|
138
|
+
|
|
139
|
+
${query}`;
|
|
140
|
+
}
|
|
141
|
+
function addResult(results, seen, url, title, snippet = "") {
|
|
142
|
+
if (typeof url !== "string" || url.trim().length === 0)
|
|
143
|
+
return;
|
|
144
|
+
if (seen.has(url))
|
|
145
|
+
return;
|
|
146
|
+
seen.add(url);
|
|
147
|
+
results.push({
|
|
148
|
+
title: typeof title === "string" && title.trim().length > 0 ? title : url,
|
|
149
|
+
url,
|
|
150
|
+
snippet
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
function extractSnippetAround(text, start, end) {
|
|
154
|
+
if (typeof start !== "number" || typeof end !== "number" || !text)
|
|
155
|
+
return "";
|
|
156
|
+
const before = Math.max(0, start - 100);
|
|
157
|
+
const after = Math.min(text.length, end + 100);
|
|
158
|
+
const snippet = text.slice(before, after).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
|
|
159
|
+
return snippet.length > 300 ? `${snippet.slice(0, 297)}...` : snippet;
|
|
160
|
+
}
|
|
161
|
+
function extractAnswer(output) {
|
|
162
|
+
const parts = [];
|
|
163
|
+
for (const item of output) {
|
|
164
|
+
if (!item || typeof item !== "object" || item.type !== "message")
|
|
165
|
+
continue;
|
|
166
|
+
const content = item.content;
|
|
167
|
+
if (!Array.isArray(content))
|
|
168
|
+
continue;
|
|
169
|
+
for (const part of content) {
|
|
170
|
+
if (!part || typeof part !== "object")
|
|
171
|
+
continue;
|
|
172
|
+
const text = part.text;
|
|
173
|
+
if (typeof text === "string" && text.trim().length > 0)
|
|
174
|
+
parts.push(text);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return parts.join(`
|
|
178
|
+
`).trim();
|
|
179
|
+
}
|
|
180
|
+
function extractSearchResults(output, numResults) {
|
|
181
|
+
const results = [];
|
|
182
|
+
const seenUrls = new Set;
|
|
183
|
+
for (const item of output) {
|
|
184
|
+
if (!item || typeof item !== "object" || item.type !== "message")
|
|
185
|
+
continue;
|
|
186
|
+
const content = item.content;
|
|
187
|
+
if (!Array.isArray(content))
|
|
188
|
+
continue;
|
|
189
|
+
for (const part of content) {
|
|
190
|
+
if (!part || typeof part !== "object")
|
|
191
|
+
continue;
|
|
192
|
+
const text = typeof part.text === "string" ? part.text : "";
|
|
193
|
+
const annotations = part.annotations;
|
|
194
|
+
if (!Array.isArray(annotations))
|
|
195
|
+
continue;
|
|
196
|
+
for (const annotation of annotations) {
|
|
197
|
+
if (!annotation || typeof annotation !== "object")
|
|
198
|
+
continue;
|
|
199
|
+
if (annotation.type !== "url_citation")
|
|
200
|
+
continue;
|
|
201
|
+
addResult(results, seenUrls, annotation.url, annotation.title, extractSnippetAround(text, annotation.start_index, annotation.end_index));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
for (const item of output) {
|
|
206
|
+
if (!item || typeof item !== "object" || item.type !== "web_search_call")
|
|
207
|
+
continue;
|
|
208
|
+
const value = item;
|
|
209
|
+
const actionSources = value.action && typeof value.action === "object" ? value.action.sources : undefined;
|
|
210
|
+
for (const group of [actionSources, value.sources, value.results]) {
|
|
211
|
+
if (!Array.isArray(group))
|
|
212
|
+
continue;
|
|
213
|
+
for (const source of group) {
|
|
214
|
+
if (!source || typeof source !== "object")
|
|
215
|
+
continue;
|
|
216
|
+
const record = source;
|
|
217
|
+
addResult(results, seenUrls, record.url ?? record.source_website_url, record.title ?? record.caption);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (typeof numResults === "number" && Number.isFinite(numResults) && numResults > 0) {
|
|
222
|
+
return results.slice(0, Math.min(Math.floor(numResults), 20));
|
|
223
|
+
}
|
|
224
|
+
return results;
|
|
225
|
+
}
|
|
226
|
+
export async function searchWithXai(query, options = {}, ctx) {
|
|
227
|
+
const auth = await resolveXaiAuth(ctx, options.signal);
|
|
228
|
+
if (!auth) {
|
|
229
|
+
throw new Error(`xAI web search unavailable. Either:
|
|
230
|
+
` + ` 1. Use /login to sign in with a SuperGrok or X Premium subscription
|
|
231
|
+
` + ` 2. Create ${CONFIG_PATH} with { "xaiApiKey": "your-key" }
|
|
232
|
+
` + " 3. Set XAI_API_KEY environment variable");
|
|
233
|
+
}
|
|
234
|
+
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
235
|
+
try {
|
|
236
|
+
const response = await fetch(XAI_RESPONSES_URL, {
|
|
237
|
+
method: "POST",
|
|
238
|
+
headers: {
|
|
239
|
+
...toRequestHeaders(auth.headers),
|
|
240
|
+
Authorization: `Bearer ${auth.apiKey}`,
|
|
241
|
+
"Content-Type": "application/json"
|
|
242
|
+
},
|
|
243
|
+
body: JSON.stringify({
|
|
244
|
+
model: auth.model,
|
|
245
|
+
input: buildInput(query, options),
|
|
246
|
+
tools: [{ type: "web_search" }]
|
|
247
|
+
}),
|
|
248
|
+
signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS)
|
|
249
|
+
});
|
|
250
|
+
if (!response.ok) {
|
|
251
|
+
activityMonitor.logError(activityId, `HTTP ${response.status}`);
|
|
252
|
+
const errorText = redactCredential(await response.text(), auth.apiKey);
|
|
253
|
+
throw new Error(`xAI API error ${response.status}: ${errorText.slice(0, 300)}`);
|
|
254
|
+
}
|
|
255
|
+
let parsed;
|
|
256
|
+
try {
|
|
257
|
+
parsed = await response.json();
|
|
258
|
+
} catch (err) {
|
|
259
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
260
|
+
throw new Error(`xAI API returned invalid JSON: ${message}`);
|
|
261
|
+
}
|
|
262
|
+
const output = Array.isArray(parsed.output) ? parsed.output : [];
|
|
263
|
+
const answer = extractAnswer(output);
|
|
264
|
+
const results = extractSearchResults(output, options.numResults);
|
|
265
|
+
if (!answer && results.length === 0) {
|
|
266
|
+
throw new Error("xAI web_search returned no answer or sources");
|
|
267
|
+
}
|
|
268
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
269
|
+
return { answer, results };
|
|
270
|
+
} catch (err) {
|
|
271
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
272
|
+
const redactedMessage = redactCredential(message, auth.apiKey);
|
|
273
|
+
if (redactedMessage.toLowerCase().includes("abort")) {
|
|
274
|
+
activityMonitor.logComplete(activityId, 0);
|
|
275
|
+
} else {
|
|
276
|
+
activityMonitor.logError(activityId, redactedMessage);
|
|
277
|
+
}
|
|
278
|
+
if (redactedMessage === message)
|
|
279
|
+
throw err;
|
|
280
|
+
const redactedError = new Error(redactedMessage);
|
|
281
|
+
if (err instanceof Error)
|
|
282
|
+
redactedError.name = err.name;
|
|
283
|
+
throw redactedError;
|
|
284
|
+
}
|
|
285
|
+
}
|