@astratra/web-search 1.1.0 → 1.2.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/README.fr.md +230 -14
- package/README.md +222 -14
- package/package.json +15 -8
- package/src/address.js +13 -8
- package/src/browser/cli.js +298 -0
- package/src/browser/client.js +251 -0
- package/src/browser/deploy.js +426 -0
- package/src/browser/egressProxy.js +234 -0
- package/src/browser/engine.js +631 -0
- package/src/browser/guard.js +92 -0
- package/src/browser/isolation.js +81 -0
- package/src/browser/pageScript.js +214 -0
- package/src/browser/robots.js +167 -0
- package/src/browser/service.js +237 -0
- package/src/browser/siteSearch.js +149 -0
- package/src/browser/webBotAuth.js +117 -0
- package/src/errors.js +9 -1
- package/src/format.js +42 -1
- package/src/index.d.ts +242 -12
- package/src/index.js +10 -1
- package/src/mcp.d.ts +5 -2
- package/src/mcp.js +10 -6
- package/src/mcpStdio.js +21 -16
- package/src/providers/gateway.js +6 -11
- package/src/tools.js +92 -16
- package/src/webSearch.js +234 -40
package/src/index.d.ts
CHANGED
|
@@ -20,6 +20,14 @@ export const CODES: Readonly<{
|
|
|
20
20
|
BAD_STATUS: 'WEB_READ_BAD_STATUS';
|
|
21
21
|
UNSUPPORTED_TYPE: 'WEB_READ_UNSUPPORTED_TYPE';
|
|
22
22
|
READ_FAILED: 'WEB_READ_FAILED';
|
|
23
|
+
BROWSER_UNAVAILABLE: 'WEB_BROWSER_UNAVAILABLE';
|
|
24
|
+
BROWSE_REFUSED: 'WEB_BROWSE_REFUSED';
|
|
25
|
+
BROWSE_FAILED: 'WEB_BROWSE_FAILED';
|
|
26
|
+
BROWSE_ROBOTS: 'WEB_BROWSE_ROBOTS_DISALLOWED';
|
|
27
|
+
BROWSE_BUSY: 'WEB_BROWSE_BUSY';
|
|
28
|
+
BROWSE_TIMEOUT: 'WEB_BROWSE_TIMEOUT';
|
|
29
|
+
NO_SITE_SEARCH: 'WEB_BROWSE_NO_SITE_SEARCH';
|
|
30
|
+
BLOCKED_DOMAIN: 'WEB_READ_BLOCKED_DOMAIN';
|
|
23
31
|
}>;
|
|
24
32
|
|
|
25
33
|
export class WebSearchError extends Error {
|
|
@@ -98,7 +106,7 @@ export function tavilyProvider(options: ProviderOptions & { searchDepth?: 'basic
|
|
|
98
106
|
export function exaProvider(options: ProviderOptions & { type?: 'auto' | 'fast' | 'deep'; highlightChars?: number }): SearchProvider;
|
|
99
107
|
export const TAVILY_COUNTRIES: Readonly<Record<string, string>>;
|
|
100
108
|
|
|
101
|
-
/**
|
|
109
|
+
/** Une passerelle de recherche à vous : `search` reçoit la demande et rend les résultats dans ce format. */
|
|
102
110
|
export function gatewayProvider(options: {
|
|
103
111
|
search: (
|
|
104
112
|
demande: { requete: string; nombre: number; langue?: string; pays?: string; periode?: 'jour' | 'semaine' | 'mois' | 'an' },
|
|
@@ -196,12 +204,27 @@ export interface ReadPage {
|
|
|
196
204
|
modifiedAt: string | null;
|
|
197
205
|
text: string;
|
|
198
206
|
truncated: boolean;
|
|
199
|
-
|
|
207
|
+
/** null quand la page a été lue par le navigateur. */
|
|
208
|
+
bytes: number | null;
|
|
209
|
+
/** fetch : lecture simple ; browser : page rendue par le navigateur intégré. */
|
|
210
|
+
via: 'fetch' | 'browser';
|
|
200
211
|
quotes: QuoteCheck[];
|
|
201
212
|
passages: Array<Passage & { score: number }>;
|
|
202
213
|
report: { ms: number; cached: boolean };
|
|
203
214
|
}
|
|
204
215
|
|
|
216
|
+
/** Un lien d'une page rendue : numéroté, ceux du même site d'abord. */
|
|
217
|
+
export interface BrowsedLink { n: number; url: string; text: string; sameSite: boolean }
|
|
218
|
+
export interface Screenshot { mediaType: 'image/png'; data: string; width?: number; height?: number }
|
|
219
|
+
|
|
220
|
+
/** Une page ouverte par le navigateur (ws.browse), ou la page de résultats de la recherche interne d'un site (ws.searchSite). */
|
|
221
|
+
export interface BrowsedPage extends ReadPage {
|
|
222
|
+
via: 'browser';
|
|
223
|
+
links: BrowsedLink[];
|
|
224
|
+
screenshot?: Screenshot;
|
|
225
|
+
siteSearch?: { query: string; via: 'opensearch' | 'form'; searchUrl: string };
|
|
226
|
+
}
|
|
227
|
+
|
|
205
228
|
/* ─────────────────── La recherche ─────────────────── */
|
|
206
229
|
|
|
207
230
|
export interface CacheStore {
|
|
@@ -230,6 +253,10 @@ export interface ReadingOptions {
|
|
|
230
253
|
passageSize?: number;
|
|
231
254
|
ports?: number[];
|
|
232
255
|
userAgent?: string;
|
|
256
|
+
/** Avec un navigateur : 'fallback' (défaut, sous minWords mots), 'always' ou 'never'. */
|
|
257
|
+
browser?: 'fallback' | 'always' | 'never';
|
|
258
|
+
/** En dessous, la lecture simple passe la main au navigateur. Défaut 200. */
|
|
259
|
+
minWords?: number;
|
|
233
260
|
}
|
|
234
261
|
|
|
235
262
|
export interface WebSearchOptions {
|
|
@@ -247,6 +274,10 @@ export interface WebSearchOptions {
|
|
|
247
274
|
budgetMs?: number;
|
|
248
275
|
ranking?: RankingOptions;
|
|
249
276
|
reading?: ReadingOptions;
|
|
277
|
+
/** Le navigateur intégré : createBrowserClient(…) ou createLocalBrowser(…). */
|
|
278
|
+
browser?: BrowserBackend;
|
|
279
|
+
/** Si donné, seules ces pages (et leurs sous-domaines) sont lues ou ouvertes. */
|
|
280
|
+
allowDomains?: string[];
|
|
250
281
|
rewrite?: (request: SearchRequest) => string | { query: string } | null | undefined | Promise<string | { query: string } | null | undefined>;
|
|
251
282
|
extract?: (html: string, context: { url: string; now: number }) => Partial<ExtractedPage> & { text: string } | Promise<Partial<ExtractedPage> & { text: string }>;
|
|
252
283
|
onReport?: (report: SearchReport) => void;
|
|
@@ -263,6 +294,11 @@ export interface WebSearchOptions {
|
|
|
263
294
|
export interface WebSearch {
|
|
264
295
|
search(input: string | SearchInput, options?: { signal?: AbortSignal }): Promise<SearchResponse>;
|
|
265
296
|
read(url: string, options?: { quotes?: string[]; query?: string; passages?: number; lang?: string; signal?: AbortSignal }): Promise<ReadPage>;
|
|
297
|
+
/** La page rendue par le navigateur, ses liens numérotés, sa capture sur demande. */
|
|
298
|
+
browse(url: string, options?: { screenshot?: boolean; quotes?: string[]; query?: string; passages?: number; lang?: string; signal?: AbortSignal }): Promise<BrowsedPage>;
|
|
299
|
+
/** La recherche interne d'un site (OpenSearch ou formulaire GET), sans clic. */
|
|
300
|
+
searchSite(url: string, query: string, options?: { screenshot?: boolean; passages?: number; lang?: string; signal?: AbortSignal }): Promise<BrowsedPage>;
|
|
301
|
+
readonly hasBrowser: boolean;
|
|
266
302
|
readonly providerIds: string[];
|
|
267
303
|
}
|
|
268
304
|
|
|
@@ -320,30 +356,37 @@ export function createMemoryCounters(options?: { now?: () => number }): CounterS
|
|
|
320
356
|
export const CITATION_RULES: string;
|
|
321
357
|
export function formatForModel(found: SearchResponse, options?: { maxChars?: number; snippetChars?: number; passageChars?: number }): string;
|
|
322
358
|
export function formatPageForModel(page: ReadPage, options?: { maxChars?: number }): string;
|
|
359
|
+
export function formatBrowsedForModel(page: BrowsedPage, options?: { maxChars?: number; maxLinks?: number }): string;
|
|
323
360
|
|
|
324
361
|
export type ToolFormat = 'anthropic' | 'openai' | 'mistral' | 'gemini' | 'generic';
|
|
325
|
-
export
|
|
326
|
-
export
|
|
362
|
+
export type WebToolName = 'web_search' | 'read_page' | 'browse_page' | 'search_site';
|
|
363
|
+
export const TOOL_SCHEMAS: Readonly<{ web_search: Record<string, unknown>; read_page: Record<string, unknown>; browse_page: Record<string, unknown>; search_site: Record<string, unknown> }>;
|
|
364
|
+
/** browser : ajouter browse_page et search_site ; screenshots : le modèle lit les images. */
|
|
365
|
+
export function toolDefinitions(format?: ToolFormat, options?: { browser?: boolean; screenshots?: boolean }): any[];
|
|
366
|
+
export function toolList(options?: { browser?: boolean; screenshots?: boolean }): Array<{ name: WebToolName; description: string; parameters: Record<string, unknown> }>;
|
|
327
367
|
export function searchArgs(args: Record<string, unknown>, defaults?: { limit?: number; read?: number }): SearchInput;
|
|
328
368
|
|
|
329
369
|
export interface WebSource { kind: 'web'; id?: string; url: string; title: string; domain: string; publishedAt: string | null; excerpt: string }
|
|
330
|
-
export
|
|
331
|
-
|
|
332
|
-
|
|
370
|
+
export interface ToolImage { mediaType: 'image/png'; data: string }
|
|
371
|
+
export function runTool(ws: WebSearch, name: WebToolName | string, args: Record<string, unknown>, options?: {
|
|
372
|
+
signal?: AbortSignal; defaults?: { limit?: number; read?: number }; maxChars?: number; screenshots?: boolean;
|
|
373
|
+
}): Promise<{ text: string; sources: WebSource[]; images?: ToolImage[]; found: SearchResponse | ReadPage | BrowsedPage }>;
|
|
333
374
|
|
|
334
375
|
export interface WebNativeTool {
|
|
335
|
-
name:
|
|
376
|
+
name: WebToolName;
|
|
336
377
|
description: string;
|
|
337
378
|
parameters: Record<string, unknown>;
|
|
338
379
|
kind: 'read';
|
|
339
380
|
risk: 'LOW';
|
|
340
381
|
summary(args?: Record<string, unknown>): Record<string, string>;
|
|
341
|
-
|
|
382
|
+
/** images : la capture d'écran, seulement avec { screenshots: true }. */
|
|
383
|
+
run(args: Record<string, unknown>, ctx?: { signal?: AbortSignal }): Promise<{ data: string; sources: WebSource[]; images?: ToolImage[] }>;
|
|
342
384
|
}
|
|
343
|
-
|
|
385
|
+
/** Avec un navigateur branché, browse_page et search_site s'ajoutent (browser: false pour les retirer). */
|
|
386
|
+
export function nativeTools(ws: WebSearch, options?: { defaults?: { limit?: number; read?: number }; maxChars?: number; browser?: boolean; screenshots?: boolean }): WebNativeTool[];
|
|
344
387
|
|
|
345
388
|
export interface WebRegistryTool {
|
|
346
|
-
name:
|
|
389
|
+
name: WebToolName;
|
|
347
390
|
description: string;
|
|
348
391
|
type: 'read';
|
|
349
392
|
risk: 'LOW';
|
|
@@ -352,7 +395,194 @@ export interface WebRegistryTool {
|
|
|
352
395
|
params: Record<string, string>;
|
|
353
396
|
handler(params: Record<string, unknown>, ctx?: { signal?: AbortSignal }): Promise<string>;
|
|
354
397
|
}
|
|
355
|
-
export function registryTools(ws: WebSearch, options: { roles: string[]; defaults?: { limit?: number; read?: number }; maxChars?: number }): WebRegistryTool[];
|
|
398
|
+
export function registryTools(ws: WebSearch, options: { roles: string[]; defaults?: { limit?: number; read?: number }; maxChars?: number; browser?: boolean }): WebRegistryTool[];
|
|
399
|
+
|
|
400
|
+
/* ─────────────────── Navigateur intégré ─────────────────── */
|
|
401
|
+
|
|
402
|
+
export type BrowserStatus =
|
|
403
|
+
| 'ok' | 'blocked' | 'robots_disallowed' | 'domain_refused' | 'bad_status' | 'timeout' | 'too_many_redirects'
|
|
404
|
+
| 'unsupported_type' | 'no_site_search' | 'search_engine_refused' | 'failed' | 'busy' | 'invalid_input' | 'browser_unavailable';
|
|
405
|
+
|
|
406
|
+
/** Ce que rend le service (ou le moteur) pour une page. */
|
|
407
|
+
export interface BrowserResult {
|
|
408
|
+
status: BrowserStatus;
|
|
409
|
+
url?: string;
|
|
410
|
+
finalUrl?: string;
|
|
411
|
+
httpStatus?: number;
|
|
412
|
+
title?: string;
|
|
413
|
+
lang?: string | null;
|
|
414
|
+
text?: string;
|
|
415
|
+
links?: BrowsedLink[];
|
|
416
|
+
canonical?: string | null;
|
|
417
|
+
publishedAt?: string | null;
|
|
418
|
+
modifiedAt?: string | null;
|
|
419
|
+
truncated?: boolean;
|
|
420
|
+
resourceLimitReached?: boolean;
|
|
421
|
+
blockedRequests?: number;
|
|
422
|
+
removed?: { overlays: number; hidden: number };
|
|
423
|
+
screenshot?: Screenshot;
|
|
424
|
+
searchUrl?: string;
|
|
425
|
+
via?: 'opensearch' | 'form';
|
|
426
|
+
query?: string;
|
|
427
|
+
reason?: string;
|
|
428
|
+
blockedUrl?: string;
|
|
429
|
+
robotsUnavailable?: boolean;
|
|
430
|
+
ms?: number;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export interface BrowserOpenRequest { url: string; screenshot?: boolean; waitFor?: string; allowDomains?: string[]; blockDomains?: string[]; lang?: string }
|
|
434
|
+
export interface BrowserSiteSearchRequest { url: string; query: string; screenshot?: boolean; allowDomains?: string[]; blockDomains?: string[]; lang?: string }
|
|
435
|
+
|
|
436
|
+
export type BrowserCallResult =
|
|
437
|
+
| { ok: true; result: BrowserResult }
|
|
438
|
+
| { ok: false; code: string; retryable: boolean; status?: number; message?: string };
|
|
439
|
+
|
|
440
|
+
/** Ce que createWebSearch attend dans `browser`. */
|
|
441
|
+
export interface BrowserBackend {
|
|
442
|
+
open(request: BrowserOpenRequest, options?: { signal?: AbortSignal }): Promise<BrowserCallResult>;
|
|
443
|
+
siteSearch(request: BrowserSiteSearchRequest, options?: { signal?: AbortSignal }): Promise<BrowserCallResult>;
|
|
444
|
+
health?(options?: { signal?: AbortSignal }): Promise<{ ok: true; result: any } | { ok: false; code: string; retryable: boolean }>;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export interface BrowserClient extends BrowserBackend {
|
|
448
|
+
health(options?: { signal?: AbortSignal }): Promise<{ ok: true; result: any } | { ok: false; code: string; retryable: boolean }>;
|
|
449
|
+
breakerStatus(): { state: 'closed' | 'open' | 'half-open'; failures: number } | null;
|
|
450
|
+
readonly kind: 'service';
|
|
451
|
+
}
|
|
452
|
+
export function createBrowserClient(options?: {
|
|
453
|
+
baseUrl?: string;
|
|
454
|
+
token?: string | (() => string | Promise<string>);
|
|
455
|
+
tokenFile?: string;
|
|
456
|
+
fetch?: (url: string, init?: any) => Promise<any>;
|
|
457
|
+
timeoutMs?: number;
|
|
458
|
+
retry?: { attempts?: number; baseDelayMs?: number; maxDelayMs?: number };
|
|
459
|
+
breaker?: { failureThreshold?: number; recoveryMs?: number } | false;
|
|
460
|
+
onEvent?: (event: { type: string; [key: string]: unknown }) => void;
|
|
461
|
+
now?: () => number;
|
|
462
|
+
sleep?: (ms: number) => Promise<void>;
|
|
463
|
+
random?: () => number;
|
|
464
|
+
}): BrowserClient;
|
|
465
|
+
|
|
466
|
+
export interface BrowserEngineOptions {
|
|
467
|
+
playwright?: unknown;
|
|
468
|
+
executablePath?: string;
|
|
469
|
+
infoUrl?: string;
|
|
470
|
+
userAgent?: string;
|
|
471
|
+
signer?: RequestSigner | null;
|
|
472
|
+
robots?: boolean;
|
|
473
|
+
fetchRobots?: (url: string, ctx: { signal?: AbortSignal }) => Promise<{ status: number; body: string }>;
|
|
474
|
+
ports?: number[];
|
|
475
|
+
allowHttp?: boolean;
|
|
476
|
+
resolve?: (...args: any[]) => any;
|
|
477
|
+
proxyPort?: number;
|
|
478
|
+
maxContexts?: number;
|
|
479
|
+
queueMs?: number;
|
|
480
|
+
maxQueue?: number;
|
|
481
|
+
pageTimeoutMs?: number;
|
|
482
|
+
requestTimeoutMs?: number;
|
|
483
|
+
settleMs?: number;
|
|
484
|
+
maxRedirects?: number;
|
|
485
|
+
maxResourceBytes?: number;
|
|
486
|
+
maxTextChars?: number;
|
|
487
|
+
maxLinks?: number;
|
|
488
|
+
/** Tests seulement. */
|
|
489
|
+
connect?: (target: { hostname: string; address: string; port: number }) => unknown;
|
|
490
|
+
/** Tests seulement : certificats non vérifiés. */
|
|
491
|
+
insecureTls?: boolean;
|
|
492
|
+
}
|
|
493
|
+
export interface BrowserEngine {
|
|
494
|
+
open(request: BrowserOpenRequest, options?: { signal?: AbortSignal }): Promise<BrowserResult>;
|
|
495
|
+
siteSearch(request: BrowserSiteSearchRequest, options?: { signal?: AbortSignal }): Promise<BrowserResult>;
|
|
496
|
+
health(): Promise<{ ok: boolean; version: string; chromium: string | null; sandbox: boolean; userAgent: string; robots: boolean; signing: { keyid: string } | null; active: number; queued: number; max: number; error?: string }>;
|
|
497
|
+
start(): Promise<unknown>;
|
|
498
|
+
close(): Promise<void>;
|
|
499
|
+
readonly userAgent: string;
|
|
500
|
+
}
|
|
501
|
+
export function createBrowserEngine(options?: BrowserEngineOptions): BrowserEngine;
|
|
502
|
+
/** Pour le développement : refuse NODE_ENV=production sans allowInProduction: true. */
|
|
503
|
+
export function createLocalBrowser(options?: BrowserEngineOptions & { engine?: BrowserEngine; allowInProduction?: boolean }): BrowserBackend & { start(): Promise<unknown>; close(): Promise<void>; readonly kind: 'local' };
|
|
504
|
+
export function browserUserAgent(options?: { version?: string; infoUrl?: string }): string;
|
|
505
|
+
export const BROWSER_DEFAULTS: Readonly<{ maxContexts: number; queueMs: number; maxQueue: number; pageTimeoutMs: number; requestTimeoutMs: number; settleMs: number; maxRedirects: number; maxResourceBytes: number; maxTextChars: number; maxLinks: number; viewport: { width: number; height: number } }>;
|
|
506
|
+
export const DEFAULT_INFO_URL: string;
|
|
507
|
+
|
|
508
|
+
export interface IsolationReport { ok: boolean; checkedAt: string; probes: Array<{ name: string; host: string; port: number; outcome: 'reached' | 'blocked' | 'timeout' | 'unreachable' }> }
|
|
509
|
+
export function checkIsolation(options: { servicePort?: number; timeoutMs?: number; targets?: Array<{ name: string; host: string; port: number }>; connect?: (...args: any[]) => any }): Promise<IsolationReport>;
|
|
510
|
+
|
|
511
|
+
export function createBrowserService(options: {
|
|
512
|
+
engine: BrowserEngine;
|
|
513
|
+
tokenFile: string;
|
|
514
|
+
host?: '127.0.0.1' | '::1';
|
|
515
|
+
port?: number;
|
|
516
|
+
unsafeNoFirewall?: boolean;
|
|
517
|
+
checkIsolation?: (options: { servicePort: number }) => Promise<IsolationReport>;
|
|
518
|
+
log?: (event: { route: string; outcome: string; ms: number }) => void;
|
|
519
|
+
}): {
|
|
520
|
+
start(): Promise<{ host: string; port: number; isolation: IsolationReport }>;
|
|
521
|
+
close(): Promise<void>;
|
|
522
|
+
address(): unknown;
|
|
523
|
+
isolation(): IsolationReport | null;
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
export function startEgressProxy(options?: { resolve?: (...args: any[]) => any; connect?: (...args: any[]) => any; ports?: number[]; allowHttp?: boolean; port?: number; host?: string; idleMs?: number; onRefused?: (event: { hostname: string; port: number; reason: string }) => void }): Promise<{
|
|
527
|
+
port: number; server: string; username: string; password: string; stats(): { tunnels: number; refused: number; open: number }; close(): Promise<void>;
|
|
528
|
+
}>;
|
|
529
|
+
|
|
530
|
+
export interface ParsedRobots { groups: Array<{ agents: string[]; rules: Array<{ allow: boolean; path: string }> }> }
|
|
531
|
+
export function parseRobots(text: string): ParsedRobots;
|
|
532
|
+
export function robotsAllows(parsed: ParsedRobots | { allowAll: true } | { disallowAll: true }, target: string | URL, token?: string): boolean;
|
|
533
|
+
export function createRobotsCache(options: { fetchRobots: (url: string, ctx: { signal?: AbortSignal }) => Promise<{ status: number; body: string }>; ttlMs?: number; errorTtlMs?: number; maxEntries?: number; token?: string; now?: () => number }): {
|
|
534
|
+
check(target: string | URL, options?: { signal?: AbortSignal }): Promise<{ allowed: boolean; unavailable?: boolean }>;
|
|
535
|
+
clear(): void;
|
|
536
|
+
size(): number;
|
|
537
|
+
};
|
|
538
|
+
export const ROBOTS_AGENT_TOKEN: 'AstratraWebBrowser';
|
|
539
|
+
|
|
540
|
+
export function openSearchUrl(xml: string, context: { query: string; pageUrl: string }): string | null;
|
|
541
|
+
export function formSearchUrl(form: { action?: string; method?: string; searchRole?: boolean; fields: Array<{ name: string; type: string; value?: string; checked?: boolean }> }, context: { query: string; pageUrl: string }): string | null;
|
|
542
|
+
export function isSearchEngine(value: string): boolean;
|
|
543
|
+
export const SEARCH_ENGINES: readonly string[];
|
|
544
|
+
|
|
545
|
+
export interface RequestSigner {
|
|
546
|
+
sign(url: string | URL): { 'signature-agent': string; 'signature-input': string; signature: string };
|
|
547
|
+
readonly keyid: string;
|
|
548
|
+
readonly publicJwk: { kty: 'OKP'; crv: 'Ed25519'; x: string };
|
|
549
|
+
}
|
|
550
|
+
export function createSigningKey(): { privateKeyPem: string; publicJwk: { kty: 'OKP'; crv: 'Ed25519'; x: string } };
|
|
551
|
+
export function createRequestSigner(options: { privateKey: string | unknown; signatureAgent: string; validitySeconds?: number; now?: () => number }): RequestSigner;
|
|
552
|
+
export function signerFromFile(options?: { signingKeyFile?: string; signatureAgent?: string }): RequestSigner | null;
|
|
553
|
+
export function jwkThumbprint(jwk: { kty: string; crv: string; x: string }): string;
|
|
554
|
+
export function signatureDirectory(publicJwks: { kty: string; crv: string; x: string } | Array<{ kty: string; crv: string; x: string }>): { keys: Array<{ kty: 'OKP'; crv: 'Ed25519'; x: string }> };
|
|
555
|
+
export const SIGNATURE_DIRECTORY_PATH: string;
|
|
556
|
+
export const SIGNATURE_DIRECTORY_TYPE: string;
|
|
557
|
+
|
|
558
|
+
export interface BrowserDeployOptions {
|
|
559
|
+
port?: number;
|
|
560
|
+
proxyPort?: number;
|
|
561
|
+
maxContexts?: number;
|
|
562
|
+
queueMs?: number;
|
|
563
|
+
infoUrl?: string;
|
|
564
|
+
signatureAgent?: string;
|
|
565
|
+
browsersPath?: string;
|
|
566
|
+
tokenFile?: string;
|
|
567
|
+
signingKeyFile?: string;
|
|
568
|
+
env?: Record<string, string>;
|
|
569
|
+
}
|
|
570
|
+
export function browserServiceEnv(options?: BrowserDeployOptions): Record<string, string>;
|
|
571
|
+
export function createBrowserSystemdUnit(options: BrowserDeployOptions & {
|
|
572
|
+
node: string; user: string; tokenFile: string; script?: string; group?: string; description?: string; workingDirectory?: string;
|
|
573
|
+
environmentFile?: string; memoryMax?: string; memoryHigh?: string; cpuQuota?: string; tasksMax?: number; restartSec?: number; readWritePaths?: string[];
|
|
574
|
+
}): string;
|
|
575
|
+
export function createBrowserPm2App(options: BrowserDeployOptions & { tokenFile: string; node?: string; script?: string; name?: string; cwd?: string; maxRestarts?: number; restartDelay?: number; killTimeout?: number; maxMemoryRestart?: string }): Record<string, unknown>;
|
|
576
|
+
export function createBrowserFirewall(options?: { user?: string; proxyPort?: number; dnsServers?: string[]; table?: string }): string;
|
|
577
|
+
/** L'unité systemd qui charge la seule table du navigateur au démarrage, avant le service. */
|
|
578
|
+
export function createBrowserFirewallUnit(options?: { nftFile?: string; nft?: string }): string;
|
|
579
|
+
export function createBrowserAppArmorProfile(options: { chromiumPath: string; name?: string }): string;
|
|
580
|
+
/** clientsGroup : le groupe des applications qui lisent le jeton (défaut astratra-browser). */
|
|
581
|
+
export function browserSetupFiles(options: Parameters<typeof createBrowserSystemdUnit>[0] & { chromiumPath?: string; dnsServers?: string[]; table?: string; clientsGroup?: string; nftFile?: string }): Record<string, string>;
|
|
582
|
+
export const BROWSER_CLI: string;
|
|
583
|
+
|
|
584
|
+
export const BLOCKED_IPV4: ReadonlyArray<readonly [string, number]>;
|
|
585
|
+
export const BLOCKED_IPV6: ReadonlyArray<readonly [string, number]>;
|
|
356
586
|
|
|
357
587
|
/* ─────────────────── Évaluation ─────────────────── */
|
|
358
588
|
|
package/src/index.js
CHANGED
|
@@ -22,5 +22,14 @@ module.exports = {
|
|
|
22
22
|
...require('./providers/brave'),
|
|
23
23
|
...require('./providers/tavily'),
|
|
24
24
|
...require('./providers/exa'),
|
|
25
|
-
...require('./providers/gateway')
|
|
25
|
+
...require('./providers/gateway'),
|
|
26
|
+
...require('./browser/client'),
|
|
27
|
+
...require('./browser/engine'),
|
|
28
|
+
...require('./browser/service'),
|
|
29
|
+
...require('./browser/deploy'),
|
|
30
|
+
...require('./browser/robots'),
|
|
31
|
+
...require('./browser/siteSearch'),
|
|
32
|
+
...require('./browser/webBotAuth'),
|
|
33
|
+
...require('./browser/isolation'),
|
|
34
|
+
...require('./browser/egressProxy')
|
|
26
35
|
};
|
package/src/mcp.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import type { WebSearch } from './index';
|
|
2
2
|
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Un serveur MCP (SDK officiel, serveur bas niveau) qui sert web_search et read_page, et browse_page et search_site quand le
|
|
5
|
+
* navigateur est branché. screenshots : le client lit les images (capture rendue en contenu image). Brancher avec `server.connect(transport)`.
|
|
6
|
+
*/
|
|
7
|
+
export function createMcpServer(ws: WebSearch, options?: { name?: string; version?: string; defaults?: { limit?: number; read?: number }; maxChars?: number; browser?: boolean; screenshots?: boolean }): {
|
|
5
8
|
connect(transport: unknown): Promise<void>;
|
|
6
9
|
close(): Promise<void>;
|
|
7
10
|
};
|
package/src/mcp.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@astratra/web-search/mcp` : la recherche servie en MCP, avec les
|
|
3
|
-
* outils (`web_search`, `read_page
|
|
2
|
+
* `@astratra/web-search/mcp` : la recherche servie en MCP, avec les mêmes
|
|
3
|
+
* outils (`web_search`, `read_page`, et `browse_page`, `search_site` quand le
|
|
4
|
+
* navigateur est branché) et le même texte cadré. Une capture d'écran revient
|
|
5
|
+
* en contenu image, seulement avec `screenshots: true`.
|
|
4
6
|
*
|
|
5
7
|
* Le SDK MCP officiel (@modelcontextprotocol/sdk) est une dépendance
|
|
6
8
|
* facultative : il n'est chargé qu'ici. Le serveur bas niveau prend les
|
|
@@ -28,7 +30,7 @@ function loadSdk() {
|
|
|
28
30
|
|
|
29
31
|
/**
|
|
30
32
|
* @param {object} ws createWebSearch(…)
|
|
31
|
-
* @param {{ name?: string, version?: string, defaults?: object, maxChars?: number }} [options]
|
|
33
|
+
* @param {{ name?: string, version?: string, defaults?: object, maxChars?: number, browser?: boolean, screenshots?: boolean }} [options]
|
|
32
34
|
*/
|
|
33
35
|
function createMcpServer(ws, options = {}) {
|
|
34
36
|
if (!ws || typeof ws.search !== 'function' || typeof ws.read !== 'function') throw new Error('createMcpServer needs a web search from createWebSearch().');
|
|
@@ -40,7 +42,8 @@ function createMcpServer(ws, options = {}) {
|
|
|
40
42
|
instructions: 'Web search where every result is one page of one site. Cite sources by their id and url; never merge two sources into one claim.'
|
|
41
43
|
}
|
|
42
44
|
);
|
|
43
|
-
const
|
|
45
|
+
const offered = { browser: Boolean(ws.hasBrowser) && options.browser !== false, screenshots: options.screenshots === true };
|
|
46
|
+
const tools = toolDefinitions('generic', offered).map(({ name, description, parameters }) => ({
|
|
44
47
|
name,
|
|
45
48
|
description,
|
|
46
49
|
inputSchema: parameters,
|
|
@@ -50,8 +53,9 @@ function createMcpServer(ws, options = {}) {
|
|
|
50
53
|
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
51
54
|
const { name, arguments: args } = request.params;
|
|
52
55
|
try {
|
|
53
|
-
|
|
54
|
-
|
|
56
|
+
if ((name === 'browse_page' || name === 'search_site') && !offered.browser) throw Object.assign(new Error(`unknown tool ${name}`), { code: 'WEB_SEARCH_BAD_REQUEST' });
|
|
57
|
+
const { text, images } = await runTool(ws, name, args || {}, { signal: extra?.signal, defaults: options.defaults, maxChars: options.maxChars, screenshots: offered.screenshots });
|
|
58
|
+
return { content: [{ type: 'text', text }, ...(images || []).map((image) => ({ type: 'image', data: image.data, mimeType: image.mediaType }))] };
|
|
55
59
|
} catch (error) {
|
|
56
60
|
if (extra?.signal?.aborted) throw error;
|
|
57
61
|
return { isError: true, content: [{ type: 'text', text: `${error.code || 'WEB_SEARCH_ERROR'}: ${error.code ? error.message : 'the tool failed'}` }] };
|
package/src/mcpStdio.js
CHANGED
|
@@ -3,27 +3,21 @@
|
|
|
3
3
|
* Le serveur MCP en stdio, prêt pour un client (éditeur, assistant de bureau).
|
|
4
4
|
*
|
|
5
5
|
* Les moteurs viennent de l'environnement, dans cet ordre :
|
|
6
|
-
* CENTRALE_ADRESSE + CENTRALE_PASSERELLE_JETON la passerelle (conseillé : aucune clé de moteur ici) ;
|
|
7
6
|
* SERPER_API_KEY, BRAVE_SEARCH_API_KEY, TAVILY_API_KEY, EXA_API_KEY des clés directes.
|
|
8
7
|
* WEB_SEARCH_MODE=fallback pour un moteur à la fois (défaut : fuse).
|
|
8
|
+
* Navigateur intégré (facultatif) : WEB_BROWSER_URL (ex. http://127.0.0.1:5008) +
|
|
9
|
+
* WEB_BROWSER_TOKEN_FILE ajoutent browse_page et search_site ;
|
|
10
|
+
* WEB_BROWSER_SCREENSHOTS=1 si le client lit les images.
|
|
9
11
|
*
|
|
10
12
|
* Rien n'est écrit sur stdout hors du protocole ; les clés ne sont jamais écrites.
|
|
11
13
|
*/
|
|
12
14
|
|
|
13
|
-
const { createWebSearch, serperProvider, braveProvider, tavilyProvider, exaProvider
|
|
15
|
+
const { createWebSearch, serperProvider, braveProvider, tavilyProvider, exaProvider } = require('./index');
|
|
16
|
+
const { createBrowserClient } = require('./browser/client');
|
|
14
17
|
const { createMcpServer } = require('./mcp');
|
|
15
18
|
|
|
16
19
|
async function providersFromEnv(env) {
|
|
17
20
|
const providers = [];
|
|
18
|
-
if (env.CENTRALE_ADRESSE && env.CENTRALE_PASSERELLE_JETON) {
|
|
19
|
-
try {
|
|
20
|
-
const { lirePasserelle, rechercher } = await import('@astratra/centrale/passerelle');
|
|
21
|
-
const gateway = lirePasserelle(env);
|
|
22
|
-
if (gateway) providers.push(gatewayProvider({ search: (demande, { signal } = {}) => rechercher(gateway, demande, { signal }) }));
|
|
23
|
-
} catch (_error) {
|
|
24
|
-
process.stderr.write('web-search: @astratra/centrale is not installed; the gateway is skipped.\n');
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
21
|
if (env.SERPER_API_KEY) providers.push(serperProvider({ key: () => env.SERPER_API_KEY }));
|
|
28
22
|
if (env.BRAVE_SEARCH_API_KEY) providers.push(braveProvider({ key: () => env.BRAVE_SEARCH_API_KEY }));
|
|
29
23
|
if (env.TAVILY_API_KEY) providers.push(tavilyProvider({ key: () => env.TAVILY_API_KEY }));
|
|
@@ -31,16 +25,27 @@ async function providersFromEnv(env) {
|
|
|
31
25
|
return providers;
|
|
32
26
|
}
|
|
33
27
|
|
|
28
|
+
/** Le client du navigateur intégré, si WEB_BROWSER_URL et WEB_BROWSER_TOKEN_FILE sont donnés. */
|
|
29
|
+
function browserFromEnv(env) {
|
|
30
|
+
if (!env.WEB_BROWSER_URL) return null;
|
|
31
|
+
if (!env.WEB_BROWSER_TOKEN_FILE) {
|
|
32
|
+
process.stderr.write('web-search: WEB_BROWSER_URL needs WEB_BROWSER_TOKEN_FILE; the browser is skipped.\n');
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
return createBrowserClient({ baseUrl: env.WEB_BROWSER_URL, tokenFile: env.WEB_BROWSER_TOKEN_FILE });
|
|
36
|
+
}
|
|
37
|
+
|
|
34
38
|
async function main() {
|
|
35
39
|
const providers = await providersFromEnv(process.env);
|
|
36
40
|
if (!providers.length) {
|
|
37
|
-
process.stderr.write('web-search: no search provider configured (
|
|
41
|
+
process.stderr.write('web-search: no search provider configured (SERPER_API_KEY, BRAVE_SEARCH_API_KEY, TAVILY_API_KEY, EXA_API_KEY).\n');
|
|
38
42
|
process.exit(1);
|
|
39
43
|
}
|
|
40
|
-
const
|
|
44
|
+
const browser = browserFromEnv(process.env);
|
|
45
|
+
const ws = createWebSearch({ providers, mode: process.env.WEB_SEARCH_MODE === 'fallback' ? 'fallback' : 'fuse', ...(browser ? { browser } : {}) });
|
|
41
46
|
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
|
|
42
|
-
await createMcpServer(ws).connect(new StdioServerTransport());
|
|
43
|
-
process.stderr.write(`web-search: MCP server ready (${ws.providerIds.join(', ')}).\n`);
|
|
47
|
+
await createMcpServer(ws, { screenshots: process.env.WEB_BROWSER_SCREENSHOTS === '1' }).connect(new StdioServerTransport());
|
|
48
|
+
process.stderr.write(`web-search: MCP server ready (${ws.providerIds.join(', ')}${browser ? ', browser' : ''}).\n`);
|
|
44
49
|
}
|
|
45
50
|
|
|
46
51
|
if (require.main === module) {
|
|
@@ -50,4 +55,4 @@ if (require.main === module) {
|
|
|
50
55
|
});
|
|
51
56
|
}
|
|
52
57
|
|
|
53
|
-
module.exports = { providersFromEnv };
|
|
58
|
+
module.exports = { providersFromEnv, browserFromEnv };
|
package/src/providers/gateway.js
CHANGED
|
@@ -1,14 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Une passerelle de recherche à l'appelant : l'app ne garde pas les clés des
|
|
3
|
+
* moteurs, sa passerelle les tient et compte le coût. Le client de la
|
|
4
|
+
* passerelle n'est pas importé ici, il est passé par l'appelant :
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
* pas importé ici, il est passé par l'appelant.
|
|
8
|
-
*
|
|
9
|
-
* const { lirePasserelle, rechercher } = await import('@astratra/centrale/passerelle');
|
|
10
|
-
* const p = lirePasserelle(process.env);
|
|
11
|
-
* gatewayProvider({ search: (demande, { signal }) => rechercher(p, demande, { signal }) });
|
|
6
|
+
* gatewayProvider({ search: (demande, { signal }) => maPasserelle.rechercher(demande, { signal }) });
|
|
12
7
|
*
|
|
13
8
|
* La passerelle n'a pas de filtre de sites : les sites partent en opérateurs
|
|
14
9
|
* (`site:`, `-site:`), que le moteur derrière (Google) comprend, et sont
|
|
@@ -29,11 +24,11 @@ const PERIODS = { day: 'jour', week: 'semaine', month: 'mois', year: 'an' };
|
|
|
29
24
|
* @param {string} [options.id] Défaut 'gateway'.
|
|
30
25
|
*/
|
|
31
26
|
function gatewayProvider(options = {}) {
|
|
32
|
-
if (typeof options.search !== 'function') throw new Error('gatewayProvider requires options.search (
|
|
27
|
+
if (typeof options.search !== 'function') throw new Error('gatewayProvider requires options.search (the search function of your gateway).');
|
|
33
28
|
const id = options.id || 'gateway';
|
|
34
29
|
return {
|
|
35
30
|
id,
|
|
36
|
-
/* La
|
|
31
|
+
/* La passerelle compte le coût elle-même : ici, inconnu. */
|
|
37
32
|
costPerCallUsd: null,
|
|
38
33
|
cacheTtlMs: options.cacheTtlMs,
|
|
39
34
|
async search(request, { signal, now = Date.now() } = {}) {
|