@abhishek944/pi-web-access 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ASTACK.md +23 -0
- package/CHANGELOG.md +1289 -0
- package/LICENSE +21 -0
- package/README.md +1215 -2
- package/SECURITY.md +5 -0
- package/abortable.ts +17 -0
- package/activity.ts +101 -0
- package/anysearch.ts +188 -0
- package/auth-fetch.ts +152 -0
- package/baizhi.ts +124 -0
- package/banner.png +0 -0
- package/bocha.ts +203 -0
- package/brave-rate-limit.ts +176 -0
- package/brave.ts +247 -0
- package/brightdata-unlocker.ts +272 -0
- package/ceramic.ts +220 -0
- package/chrome-cookies.ts +752 -0
- package/cloudflare-search.ts +237 -0
- package/content-find.ts +255 -0
- package/crawl4ai.ts +196 -0
- package/credential-source.ts +242 -0
- package/curator-page.ts +3607 -0
- package/curator-run.ts +45 -0
- package/curator-server.ts +761 -0
- package/custom-search.ts +226 -0
- package/data-uri-sanitize.ts +406 -0
- package/datalab-pdf-extract.ts +568 -0
- package/declared-web-links.ts +173 -0
- package/deepseek.ts +377 -0
- package/degoog.ts +323 -0
- package/dist/index.js +28286 -0
- package/dist/mcp-cli.js +29186 -0
- package/dist/pi-mcp.js +20855 -0
- package/dist/types/abortable.d.ts +2 -0
- package/dist/types/activity.d.ts +33 -0
- package/dist/types/anysearch.d.ts +7 -0
- package/dist/types/auth-fetch.d.ts +14 -0
- package/dist/types/baizhi.d.ts +3 -0
- package/dist/types/bocha.d.ts +3 -0
- package/dist/types/brave-rate-limit.d.ts +35 -0
- package/dist/types/brave.d.ts +3 -0
- package/dist/types/brightdata-unlocker.d.ts +11 -0
- package/dist/types/ceramic.d.ts +3 -0
- package/dist/types/chrome-cookies.d.ts +44 -0
- package/dist/types/cloudflare-search.d.ts +4 -0
- package/dist/types/content-find.d.ts +10 -0
- package/dist/types/crawl4ai.d.ts +8 -0
- package/dist/types/credential-source.d.ts +29 -0
- package/dist/types/curator-page.d.ts +5 -0
- package/dist/types/curator-run.d.ts +10 -0
- package/dist/types/curator-server.d.ts +72 -0
- package/dist/types/custom-search.d.ts +22 -0
- package/dist/types/data-uri-sanitize.d.ts +20 -0
- package/dist/types/datalab-pdf-extract.d.ts +59 -0
- package/dist/types/declared-web-links.d.ts +7 -0
- package/dist/types/deepseek.d.ts +13 -0
- package/dist/types/degoog.d.ts +3 -0
- package/dist/types/domain-filter-normalization.d.ts +9 -0
- package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
- package/dist/types/duckduckgo.d.ts +6 -0
- package/dist/types/endpoint-pdf-extract.d.ts +22 -0
- package/dist/types/exa.d.ts +17 -0
- package/dist/types/extract.d.ts +70 -0
- package/dist/types/feature-config.d.ts +2 -0
- package/dist/types/fetch-params.d.ts +39 -0
- package/dist/types/field-extract.d.ts +37 -0
- package/dist/types/firecrawl.d.ts +18 -0
- package/dist/types/gemini-adc.d.ts +9 -0
- package/dist/types/gemini-api.d.ts +37 -0
- package/dist/types/gemini-pdf-extract.d.ts +8 -0
- package/dist/types/gemini-search.d.ts +76 -0
- package/dist/types/gemini-url-context.d.ts +3 -0
- package/dist/types/gemini-web-config.d.ts +25 -0
- package/dist/types/gemini-web.d.ts +31 -0
- package/dist/types/github-api.d.ts +6 -0
- package/dist/types/github-extract.d.ts +19 -0
- package/dist/types/github-issue-pr.d.ts +28 -0
- package/dist/types/index.d.ts +53 -0
- package/dist/types/jina-search.d.ts +7 -0
- package/dist/types/kagi.d.ts +14 -0
- package/dist/types/keenable.d.ts +3 -0
- package/dist/types/kimi-search.d.ts +4 -0
- package/dist/types/linkup.d.ts +5 -0
- package/dist/types/mcp-cli.d.ts +2 -0
- package/dist/types/mcp-server.d.ts +10 -0
- package/dist/types/mcp-tool-definitions.d.ts +16 -0
- package/dist/types/mistral-search.d.ts +3 -0
- package/dist/types/ninerouter.d.ts +3 -0
- package/dist/types/offtopic-judge.d.ts +26 -0
- package/dist/types/ollama.d.ts +14 -0
- package/dist/types/openai-search.d.ts +23 -0
- package/dist/types/page-query.d.ts +22 -0
- package/dist/types/parallel-mcp.d.ts +10 -0
- package/dist/types/parallel.d.ts +13 -0
- package/dist/types/pdf-extract.d.ts +44 -0
- package/dist/types/perplexity.d.ts +26 -0
- package/dist/types/pi-mcp.d.ts +56 -0
- package/dist/types/pi-session-results.d.ts +8 -0
- package/dist/types/querit.d.ts +9 -0
- package/dist/types/query-rewrite.d.ts +2 -0
- package/dist/types/render-search-error.d.ts +56 -0
- package/dist/types/retrieval-only.d.ts +78 -0
- package/dist/types/rsc-extract.d.ts +11 -0
- package/dist/types/search-answer-formatting.d.ts +7 -0
- package/dist/types/search-result-count-normalization.d.ts +1 -0
- package/dist/types/searchinfinity.d.ts +7 -0
- package/dist/types/searxng.d.ts +3 -0
- package/dist/types/source-check.d.ts +102 -0
- package/dist/types/ssrf-protection.d.ts +66 -0
- package/dist/types/storage.d.ts +69 -0
- package/dist/types/summary-model-scope.d.ts +33 -0
- package/dist/types/summary-review.d.ts +30 -0
- package/dist/types/tabstack.d.ts +5 -0
- package/dist/types/tavily.d.ts +7 -0
- package/dist/types/tinyfish.d.ts +10 -0
- package/dist/types/tool-activation.d.ts +7 -0
- package/dist/types/tool-arguments.d.ts +1 -0
- package/dist/types/upgrade-notice.d.ts +6 -0
- package/dist/types/utils.d.ts +55 -0
- package/dist/types/valyu.d.ts +5 -0
- package/dist/types/video-extract.d.ts +15 -0
- package/dist/types/web-tool-contract.d.ts +98 -0
- package/dist/types/web-tool-core.d.ts +227 -0
- package/dist/types/xai-search.d.ts +12 -0
- package/dist/types/you.d.ts +3 -0
- package/dist/types/youtube-extract.d.ts +29 -0
- package/dist/types/zai.d.ts +3 -0
- package/docs/pi-mcp.md +41 -0
- package/domain-filter-normalization.ts +44 -0
- package/duckduckgo-rate-limit.ts +205 -0
- package/duckduckgo.ts +123 -0
- package/endpoint-pdf-extract.ts +225 -0
- package/exa.ts +620 -0
- package/extract.ts +1721 -0
- package/feature-config.ts +29 -0
- package/fetch-params.ts +147 -0
- package/field-extract.ts +347 -0
- package/firecrawl.ts +476 -0
- package/gemini-adc.ts +345 -0
- package/gemini-api.ts +368 -0
- package/gemini-pdf-extract.ts +108 -0
- package/gemini-search.ts +1162 -0
- package/gemini-url-context.ts +128 -0
- package/gemini-web-config.ts +131 -0
- package/gemini-web.ts +527 -0
- package/github-api.ts +197 -0
- package/github-extract.ts +1064 -0
- package/github-issue-pr.ts +717 -0
- package/index.ts +2819 -0
- package/jina-search.ts +275 -0
- package/kagi.ts +257 -0
- package/keenable.ts +222 -0
- package/kimi-search.ts +209 -0
- package/linkup.ts +170 -0
- package/mcp-cli.ts +40 -0
- package/mcp-server.ts +84 -0
- package/mcp-tool-definitions.ts +143 -0
- package/mistral-search.ts +268 -0
- package/ninerouter.ts +92 -0
- package/offtopic-judge.ts +72 -0
- package/ollama.ts +237 -0
- package/openai-search.ts +855 -0
- package/package.json +108 -4
- package/page-query.ts +185 -0
- package/parallel-mcp.ts +255 -0
- package/parallel.ts +373 -0
- package/pdf-extract.ts +447 -0
- package/perplexity.ts +245 -0
- package/pi-mcp.ts +139 -0
- package/pi-session-results.ts +40 -0
- package/pi-web-fetch-demo.mp4 +0 -0
- package/promise-try.d.ts +7 -0
- package/querit.ts +394 -0
- package/query-rewrite.ts +84 -0
- package/render-search-error.ts +170 -0
- package/retrieval-only.ts +102 -0
- package/rsc-extract.ts +338 -0
- package/search-answer-formatting.ts +11 -0
- package/search-result-count-normalization.ts +4 -0
- package/searchinfinity.ts +246 -0
- package/searxng.ts +236 -0
- package/source-check.ts +269 -0
- package/ssrf-protection.ts +602 -0
- package/storage.ts +547 -0
- package/summary-model-scope.ts +72 -0
- package/summary-review.ts +476 -0
- package/tabstack.ts +289 -0
- package/tavily.ts +257 -0
- package/tinyfish.ts +373 -0
- package/tool-activation.ts +169 -0
- package/tool-arguments.ts +23 -0
- package/upgrade-notice.ts +47 -0
- package/utils.ts +693 -0
- package/valyu.ts +177 -0
- package/video-extract.ts +398 -0
- package/web-tool-contract.ts +93 -0
- package/web-tool-core.ts +1810 -0
- package/xai-search.ts +443 -0
- package/you.ts +165 -0
- package/youtube-extract.ts +336 -0
- package/zai.ts +161 -0
package/web-tool-core.ts
ADDED
|
@@ -0,0 +1,1810 @@
|
|
|
1
|
+
// Host-neutral execution core for web_search (non-curator path), fetch_content,
|
|
2
|
+
// get_search_content, and source_check. The Pi extension (index.ts) and the MCP
|
|
3
|
+
// server both run tools through createWebToolCore; everything that differs per
|
|
4
|
+
// host (session persistence, background notifications, Pi model access) is a
|
|
5
|
+
// WebToolCoreHost hook. This module must stay free of runtime imports from
|
|
6
|
+
// index.ts, curator/summary/activation modules, and @earendil-works/* packages.
|
|
7
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
8
|
+
import type { Usage } from "@earendil-works/pi-ai/compat";
|
|
9
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import type { BrowserCookieConsent } from "./gemini-web-config.ts";
|
|
11
|
+
import type { KeyId } from "@earendil-works/pi-tui";
|
|
12
|
+
import pLimit from "p-limit";
|
|
13
|
+
import type { ExtractedContent, ExtractOptions } from "./extract.ts";
|
|
14
|
+
import { describeReceivedParams, normalizeFetchContentParams, type FetchContentParams } from "./fetch-params.ts";
|
|
15
|
+
import { resolveAuthFetchProfile, type AuthFetchProfile } from "./auth-fetch.ts";
|
|
16
|
+
import { findContent, type FindMode } from "./content-find.ts";
|
|
17
|
+
import { extractPageFields, formatPageExtraction, parseExtractFields } from "./field-extract.ts";
|
|
18
|
+
import {
|
|
19
|
+
assertSearchProviderSelectionAllowed,
|
|
20
|
+
normalizeSearchProviderSelection,
|
|
21
|
+
parseProviderArgument,
|
|
22
|
+
validateSearchModelOverride,
|
|
23
|
+
search,
|
|
24
|
+
type SearchProvider,
|
|
25
|
+
type SearchProviderSelection,
|
|
26
|
+
} from "./gemini-search.ts";
|
|
27
|
+
import { isOpenAISearchAvailable } from "./openai-search.ts";
|
|
28
|
+
import type { SearchResult } from "./perplexity.ts";
|
|
29
|
+
import { getWebSearchConfigPath, runWithProxy } from "./utils.ts";
|
|
30
|
+
import { getRetrievalOnlyPolicy, retrievalOnlyError, retrievalOnlyExhaustedError } from "./retrieval-only.ts";
|
|
31
|
+
import { deleteResult, generateId, getResult, storeResult, type QueryResultData, type StoredSearchData } from "./storage.ts";
|
|
32
|
+
import {
|
|
33
|
+
buildResearchArtifact,
|
|
34
|
+
getResearchArtifact,
|
|
35
|
+
storeResearchArtifact,
|
|
36
|
+
withClaimAssessment,
|
|
37
|
+
type RecencyFilter,
|
|
38
|
+
type ResearchArtifact,
|
|
39
|
+
} from "./source-check.ts";
|
|
40
|
+
import type { SummaryMeta } from "./summary-review.ts";
|
|
41
|
+
import type {
|
|
42
|
+
FetchContentCallParams,
|
|
43
|
+
FetchContentStructuredContent,
|
|
44
|
+
GetSearchContentCallParams,
|
|
45
|
+
SourceCheckCallParams,
|
|
46
|
+
WebSearchCallParams,
|
|
47
|
+
WebSearchStructuredContent,
|
|
48
|
+
WebToolContent,
|
|
49
|
+
WebToolCore,
|
|
50
|
+
WebToolResult,
|
|
51
|
+
} from "./web-tool-contract.ts";
|
|
52
|
+
|
|
53
|
+
export const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
|
|
54
|
+
|
|
55
|
+
export interface WebSearchConfig {
|
|
56
|
+
anysearchApiKey?: unknown;
|
|
57
|
+
brightdataApiKey?: unknown;
|
|
58
|
+
kagiApiKey?: unknown;
|
|
59
|
+
ollamaApiKey?: unknown;
|
|
60
|
+
youApiKey?: unknown;
|
|
61
|
+
baizhiApiKey?: unknown;
|
|
62
|
+
zaiApiKey?: unknown;
|
|
63
|
+
tinyfishApiKey?: unknown;
|
|
64
|
+
valyuApiKey?: unknown;
|
|
65
|
+
keenableApiKey?: unknown;
|
|
66
|
+
ceramicApiKey?: unknown;
|
|
67
|
+
linkupApiKey?: unknown;
|
|
68
|
+
linkupDepth?: unknown;
|
|
69
|
+
ninerouterBaseUrl?: unknown;
|
|
70
|
+
ninerouterApiKey?: unknown;
|
|
71
|
+
ninerouterProvider?: unknown;
|
|
72
|
+
cloudflareAccountId?: unknown;
|
|
73
|
+
cloudflareGatewayId?: unknown;
|
|
74
|
+
cloudflareSearchProvider?: unknown;
|
|
75
|
+
tabstackBaseUrl?: unknown;
|
|
76
|
+
tabstackApiKey?: unknown;
|
|
77
|
+
tabstackResearchMode?: unknown;
|
|
78
|
+
deepseekApiKey?: unknown;
|
|
79
|
+
degoogBaseUrl?: unknown;
|
|
80
|
+
degoogApiKey?: unknown;
|
|
81
|
+
degoogEngines?: unknown;
|
|
82
|
+
degoogHeaders?: unknown;
|
|
83
|
+
xaiApiKey?: unknown;
|
|
84
|
+
provider?: unknown;
|
|
85
|
+
searchProvider?: unknown;
|
|
86
|
+
workflow?: string;
|
|
87
|
+
curatorTimeoutSeconds?: unknown;
|
|
88
|
+
autoOpenBrowser?: unknown;
|
|
89
|
+
curatorRemote?: unknown;
|
|
90
|
+
summaryModel?: string;
|
|
91
|
+
queryRewriteModel?: string;
|
|
92
|
+
summaryGenerationDeadlineMs?: unknown;
|
|
93
|
+
summaryInstructions?: unknown;
|
|
94
|
+
maxInlineContentChars?: unknown;
|
|
95
|
+
retrievalOnly?: unknown;
|
|
96
|
+
fetch?: {
|
|
97
|
+
defaultMode?: unknown;
|
|
98
|
+
allowedModes?: unknown;
|
|
99
|
+
};
|
|
100
|
+
webSearch?: {
|
|
101
|
+
enabled?: boolean;
|
|
102
|
+
allowedProviders?: unknown;
|
|
103
|
+
};
|
|
104
|
+
tools?: Partial<Record<keyof ToolNames, { enabled?: boolean }>>;
|
|
105
|
+
toolActivation?: unknown;
|
|
106
|
+
toolExposure?: unknown;
|
|
107
|
+
commands?: Partial<Record<"websearch" | "curator" | "search" | "google-account", { enabled?: boolean }>>;
|
|
108
|
+
toolNames?: Partial<ToolNames>;
|
|
109
|
+
shortcuts?: {
|
|
110
|
+
curate?: KeyId;
|
|
111
|
+
activity?: KeyId;
|
|
112
|
+
};
|
|
113
|
+
ssrf?: {
|
|
114
|
+
/** CIDR ranges exempted from the SSRF guard (e.g. fake-IP proxy ranges). */
|
|
115
|
+
allowRanges?: string[];
|
|
116
|
+
/** Skip local hostname DNS preflight when an HTTP(S)_PROXY env var applies. */
|
|
117
|
+
trustEnvProxy?: boolean;
|
|
118
|
+
};
|
|
119
|
+
allowBrowserCookies?: unknown;
|
|
120
|
+
browserCookies?: unknown;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function parseConfigRoot(raw: string): Record<string, unknown> {
|
|
124
|
+
let parsed: unknown;
|
|
125
|
+
try {
|
|
126
|
+
parsed = JSON.parse(raw);
|
|
127
|
+
} catch (err) {
|
|
128
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
129
|
+
throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
|
|
130
|
+
}
|
|
131
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
132
|
+
throw new Error(`Invalid config in ${WEB_SEARCH_CONFIG_PATH}: expected a JSON object`);
|
|
133
|
+
}
|
|
134
|
+
return parsed as Record<string, unknown>;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function loadConfig(): WebSearchConfig {
|
|
138
|
+
if (!existsSync(WEB_SEARCH_CONFIG_PATH)) return {};
|
|
139
|
+
return parseConfigRoot(readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8")) as WebSearchConfig;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export type ToolNames = {
|
|
143
|
+
webSearch: string;
|
|
144
|
+
sourceCheck: string;
|
|
145
|
+
fetchContent: string;
|
|
146
|
+
getSearchContent: string;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
export const DEFAULT_TOOL_NAMES: ToolNames = {
|
|
150
|
+
webSearch: "web_search",
|
|
151
|
+
sourceCheck: "source_check",
|
|
152
|
+
fetchContent: "fetch_content",
|
|
153
|
+
getSearchContent: "get_search_content",
|
|
154
|
+
};
|
|
155
|
+
const SEARCH_QUERY_CONCURRENCY = 3;
|
|
156
|
+
const FETCH_MODES = ["readable", "raw", "answer", "extract"] as const;
|
|
157
|
+
export type FetchMode = typeof FETCH_MODES[number];
|
|
158
|
+
export type FetchModeConfig = { defaultMode: FetchMode; allowedModes: FetchMode[] };
|
|
159
|
+
// Extract sends page text to Cloudflare, so it is offered only when fetch.allowedModes lists it.
|
|
160
|
+
const DEFAULT_FETCH_MODES: FetchMode[] = ["readable", "raw", "answer"];
|
|
161
|
+
// Answer and extract send page content to a model.
|
|
162
|
+
const MODEL_FETCH_MODES: readonly FetchMode[] = ["answer", "extract"];
|
|
163
|
+
|
|
164
|
+
export function resolveFetchModeConfig(config: WebSearchConfig): FetchModeConfig {
|
|
165
|
+
const configuredModes = config.fetch?.allowedModes ?? DEFAULT_FETCH_MODES;
|
|
166
|
+
if (!Array.isArray(configuredModes) || configuredModes.length === 0 || configuredModes.some(mode => !FETCH_MODES.includes(mode as FetchMode))) {
|
|
167
|
+
throw new Error(`fetch.allowedModes in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array containing only "readable", "raw", "answer", or "extract"`);
|
|
168
|
+
}
|
|
169
|
+
let allowedModes = configuredModes as FetchMode[];
|
|
170
|
+
const duplicateMode = allowedModes.find((mode, index) => allowedModes.indexOf(mode) !== index);
|
|
171
|
+
if (duplicateMode) {
|
|
172
|
+
throw new Error(`fetch.allowedModes in ${WEB_SEARCH_CONFIG_PATH} must not contain duplicates: "${duplicateMode}"`);
|
|
173
|
+
}
|
|
174
|
+
let defaultMode = config.fetch?.defaultMode ?? "readable";
|
|
175
|
+
const policy = getRetrievalOnlyPolicy(config);
|
|
176
|
+
if (policy.enabled) {
|
|
177
|
+
const retrievalModes = allowedModes.filter(mode => !MODEL_FETCH_MODES.includes(mode));
|
|
178
|
+
if (retrievalModes.length === 0) throw retrievalOnlyExhaustedError("fetch mode", allowedModes, policy);
|
|
179
|
+
// A model default only adds processing on top of the fetch, so it falls back instead of failing.
|
|
180
|
+
if (MODEL_FETCH_MODES.includes(defaultMode as FetchMode)) defaultMode = retrievalModes.includes("readable") ? "readable" : retrievalModes[0];
|
|
181
|
+
allowedModes = retrievalModes;
|
|
182
|
+
}
|
|
183
|
+
if (defaultMode === "extract") {
|
|
184
|
+
throw new Error(`fetch.defaultMode in ${WEB_SEARCH_CONFIG_PATH} cannot be "extract", because extract needs fields on each call`);
|
|
185
|
+
}
|
|
186
|
+
if (!allowedModes.includes(defaultMode as FetchMode)) {
|
|
187
|
+
throw new Error(`fetch.defaultMode in ${WEB_SEARCH_CONFIG_PATH} must be one of fetch.allowedModes`);
|
|
188
|
+
}
|
|
189
|
+
return { defaultMode: defaultMode as FetchMode, allowedModes };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Limit each batch independently so separate Pi tool calls can still run in parallel.
|
|
193
|
+
export function runSearchQueries<T>(queries: string[], run: (query: string, index: number) => Promise<T>): Promise<T[]> {
|
|
194
|
+
const limit = pLimit(SEARCH_QUERY_CONCURRENCY);
|
|
195
|
+
return Promise.all(queries.map((query, index) => limit(() => run(query, index))));
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function isToolEnabled(config: WebSearchConfig, key: keyof ToolNames): boolean {
|
|
199
|
+
const override = config.tools?.[key]?.enabled;
|
|
200
|
+
if (typeof override === "boolean") return override;
|
|
201
|
+
return key !== "webSearch" && key !== "sourceCheck" || config.webSearch?.enabled !== false;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function joinToolNames(names: string[]): string {
|
|
205
|
+
if (names.length === 0) return "stored content";
|
|
206
|
+
if (names.length === 1) return names[0];
|
|
207
|
+
if (names.length === 2) return `${names[0]} or ${names[1]}`;
|
|
208
|
+
return `${names.slice(0, -1).join(", ")}, or ${names[names.length - 1]}`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function normalizeProviderInput(value: unknown, label = "provider"): SearchProviderSelection | undefined {
|
|
212
|
+
if (value === undefined) return undefined;
|
|
213
|
+
return normalizeSearchProviderSelection(value, label);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function resolveRequestedProvider(requested: unknown): SearchProviderSelection {
|
|
217
|
+
const normalizedRequested = parseProviderArgument(requested);
|
|
218
|
+
if (normalizedRequested && normalizedRequested !== "auto") {
|
|
219
|
+
assertSearchProviderSelectionAllowed(normalizedRequested, "Requested provider");
|
|
220
|
+
return normalizedRequested;
|
|
221
|
+
}
|
|
222
|
+
const config = loadConfig();
|
|
223
|
+
const provider = normalizeProviderInput(config.searchProvider ?? config.provider, `provider in ${WEB_SEARCH_CONFIG_PATH}`) ?? "auto";
|
|
224
|
+
assertSearchProviderSelectionAllowed(provider, `configured provider in ${WEB_SEARCH_CONFIG_PATH}`);
|
|
225
|
+
return provider;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export function toCuratorProvider(provider: SearchProviderSelection): SearchProvider | undefined {
|
|
229
|
+
if (Array.isArray(provider)) return "all";
|
|
230
|
+
return provider === "auto" ? undefined : provider;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function normalizeRecencyFilter(value: unknown): RecencyFilter | undefined {
|
|
234
|
+
return value === "day" || value === "week" || value === "month" || value === "year"
|
|
235
|
+
? value
|
|
236
|
+
: undefined;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export function normalizeQueryList(queryList: unknown[]): string[] {
|
|
240
|
+
const normalized: string[] = [];
|
|
241
|
+
for (const query of queryList) {
|
|
242
|
+
if (typeof query !== "string") continue;
|
|
243
|
+
const trimmed = query.trim();
|
|
244
|
+
if (trimmed.length > 0) normalized.push(trimmed);
|
|
245
|
+
}
|
|
246
|
+
return normalized;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Some local models serialize a multi-query list into the single-string `query`
|
|
250
|
+
// field as a JSON array (query: "[\"a\", \"b\"]") instead of using the
|
|
251
|
+
// `queries` parameter. Forwarding that raw string verbatim makes every backend
|
|
252
|
+
// search for the literal array text and return zero results, with no signal to
|
|
253
|
+
// the model that its argument shape was wrong. Expand a string that parses as a
|
|
254
|
+
// JSON array of strings so each element is searched independently.
|
|
255
|
+
export function expandQueryString(query: unknown): string[] {
|
|
256
|
+
if (typeof query !== "string") return [];
|
|
257
|
+
const trimmed = query.trim();
|
|
258
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
259
|
+
try {
|
|
260
|
+
const parsed: unknown = JSON.parse(trimmed);
|
|
261
|
+
// Only expand an unambiguously string-only array. Mixed or non-string
|
|
262
|
+
// arrays are kept as the literal query so we never silently drop
|
|
263
|
+
// members or collapse them into an empty search.
|
|
264
|
+
if (Array.isArray(parsed) && parsed.every((entry): entry is string => typeof entry === "string")) {
|
|
265
|
+
return parsed
|
|
266
|
+
.map((entry) => entry.trim())
|
|
267
|
+
.filter((entry) => entry.length > 0);
|
|
268
|
+
}
|
|
269
|
+
} catch {
|
|
270
|
+
// Not JSON — treat as a literal query string.
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return [query];
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
let extractModulePromise: Promise<typeof import("./extract.ts")> | undefined;
|
|
277
|
+
export async function fetchAllContent(
|
|
278
|
+
urls: string[],
|
|
279
|
+
signal?: AbortSignal,
|
|
280
|
+
options?: ExtractOptions,
|
|
281
|
+
): Promise<ExtractedContent[]> {
|
|
282
|
+
const extractModule = await (extractModulePromise ??= import("./extract.ts"));
|
|
283
|
+
return extractModule.fetchAllContent(urls, signal, options);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Returns content for every URL in order: the provider's content where it supplied some,
|
|
287
|
+
* and a page fetch only for the URLs it did not cover. */
|
|
288
|
+
export async function fetchUncoveredContent(
|
|
289
|
+
urls: string[],
|
|
290
|
+
provided: ExtractedContent[] | undefined,
|
|
291
|
+
fetchPages: (urls: string[]) => Promise<ExtractedContent[]>,
|
|
292
|
+
): Promise<ExtractedContent[]> {
|
|
293
|
+
const providedByUrl = new Map<string, ExtractedContent>();
|
|
294
|
+
for (const content of provided ?? []) {
|
|
295
|
+
if (!providedByUrl.has(content.url)) providedByUrl.set(content.url, content);
|
|
296
|
+
}
|
|
297
|
+
const missing = urls.filter(url => !providedByUrl.has(url));
|
|
298
|
+
const fetched = missing.length > 0 ? await fetchPages(missing) : [];
|
|
299
|
+
let next = 0;
|
|
300
|
+
return urls.map(url => providedByUrl.get(url) ?? fetched[next++]);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export function withRegisteredFetchOptions(
|
|
304
|
+
options: ExtractOptions | undefined,
|
|
305
|
+
toolNames: ExtractOptions["toolNames"],
|
|
306
|
+
proxy?: string,
|
|
307
|
+
): ExtractOptions {
|
|
308
|
+
return {
|
|
309
|
+
...(options ?? {}),
|
|
310
|
+
toolNames,
|
|
311
|
+
...(proxy !== undefined ? { proxy } : {}),
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function isAbortError(err: unknown): boolean {
|
|
316
|
+
return (err instanceof Error ? err.message : String(err)).toLowerCase().includes("abort");
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const DEFAULT_MAX_INLINE_CONTENT_CHARS = 30_000;
|
|
320
|
+
const MIN_INLINE_CONTENT_CHARS = 1_000;
|
|
321
|
+
const MAX_INLINE_CONTENT_CHARS = 200_000;
|
|
322
|
+
|
|
323
|
+
export function getMaxInlineContentChars(config = loadConfig()): number {
|
|
324
|
+
const value = config.maxInlineContentChars;
|
|
325
|
+
if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value) || value < MIN_INLINE_CONTENT_CHARS) {
|
|
326
|
+
return DEFAULT_MAX_INLINE_CONTENT_CHARS;
|
|
327
|
+
}
|
|
328
|
+
return Math.min(value, MAX_INLINE_CONTENT_CHARS);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export function stripThumbnails(results: ExtractedContent[]): ExtractedContent[] {
|
|
332
|
+
return results.map(({ thumbnail, frames, ...rest }) => rest);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function searchStructuredContent(responseId: string, fetchId: string | null, results: QueryResultData[]): WebSearchStructuredContent {
|
|
336
|
+
return {
|
|
337
|
+
responseId,
|
|
338
|
+
fetchId,
|
|
339
|
+
queries: results.map(({ query, answer, error, provider, providers, results }) => ({
|
|
340
|
+
query, answer, error, provider, providers,
|
|
341
|
+
results: results.map(({ title, url, snippet }) => ({ title, url, snippet })),
|
|
342
|
+
})),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Full content per URL, without thumbnails or frames.
|
|
347
|
+
function fetchStructuredContent(responseId: string | null, results: ExtractedContent[]): FetchContentStructuredContent {
|
|
348
|
+
return {
|
|
349
|
+
responseId,
|
|
350
|
+
urls: results.map(({ url, title, content, error, mimeType, status, duration }) => ({ url, title, content, error, mimeType, status, duration })),
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function initialContentSlice(content: string, maxChars: number): {
|
|
355
|
+
text: string;
|
|
356
|
+
endOffset: number;
|
|
357
|
+
totalBytes: number;
|
|
358
|
+
totalLines: number;
|
|
359
|
+
shownBytes: number;
|
|
360
|
+
shownLines: number;
|
|
361
|
+
} {
|
|
362
|
+
let endOffset = pageEnd(content, 0, Math.min(content.length, maxChars));
|
|
363
|
+
if (endOffset < content.length) {
|
|
364
|
+
const lineBreak = content.lastIndexOf("\n", endOffset);
|
|
365
|
+
if (lineBreak >= Math.floor(maxChars * 0.8)) endOffset = lineBreak + 1;
|
|
366
|
+
}
|
|
367
|
+
const text = content.slice(0, endOffset);
|
|
368
|
+
return {
|
|
369
|
+
text,
|
|
370
|
+
endOffset,
|
|
371
|
+
totalBytes: Buffer.byteLength(content),
|
|
372
|
+
totalLines: content.length === 0 ? 0 : content.split("\n").length,
|
|
373
|
+
shownBytes: Buffer.byteLength(text),
|
|
374
|
+
shownLines: text.length === 0 ? 0 : text.split("\n").length,
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function normalizeFindQueries(value: string | string[]): string[] {
|
|
379
|
+
const queries = (Array.isArray(value) ? value : [value]).map(query => query.trim()).filter(Boolean);
|
|
380
|
+
if (queries.length === 0) throw new Error("findText must contain at least one non-empty string");
|
|
381
|
+
return queries;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
type GetSearchContentParams = GetSearchContentCallParams;
|
|
385
|
+
|
|
386
|
+
export type RawGetSearchContentParams = Omit<GetSearchContentParams, "findMode"> & { findMode?: unknown };
|
|
387
|
+
|
|
388
|
+
function normalizeFindMode(value: unknown): FindMode | undefined {
|
|
389
|
+
if (value === undefined) return undefined;
|
|
390
|
+
if (value === "exact" || value === "case-insensitive" || value === "fuzzy") return value;
|
|
391
|
+
throw new Error('findMode must be "exact", "case-insensitive", or "fuzzy"');
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function normalizeGetSearchContentParams(params: RawGetSearchContentParams): GetSearchContentParams {
|
|
395
|
+
const normalized: GetSearchContentParams = { ...params, findMode: normalizeFindMode(params.findMode) };
|
|
396
|
+
|
|
397
|
+
if (normalized.query?.trim() === "") delete normalized.query;
|
|
398
|
+
if (normalized.url?.trim() === "") delete normalized.url;
|
|
399
|
+
|
|
400
|
+
if (normalized.findText !== undefined) {
|
|
401
|
+
delete normalized.offset;
|
|
402
|
+
delete normalized.limit;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
return normalized;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function formatInputValue(value: unknown): string {
|
|
409
|
+
if (typeof value === "string") return JSON.stringify(value);
|
|
410
|
+
if (typeof value === "number") return Number.isNaN(value) ? "NaN" : String(value);
|
|
411
|
+
try {
|
|
412
|
+
const serialized = JSON.stringify(value);
|
|
413
|
+
return serialized === undefined ? String(value) : serialized;
|
|
414
|
+
} catch {
|
|
415
|
+
return String(value);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function formatSearchSummary(results: SearchResult[], answer: string): string {
|
|
420
|
+
if (results.length === 0) {
|
|
421
|
+
return answer ? `${answer}\n\n---\n\n**Sources:**\nNo sources returned.` : "No results found.";
|
|
422
|
+
}
|
|
423
|
+
let output = answer ? `${answer}\n\n---\n\n**Sources:**\n` : "";
|
|
424
|
+
output += results.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}`).join("\n\n");
|
|
425
|
+
return output;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function formatSourceCheckResult(artifact: ResearchArtifact, getSearchContentTool: string | null = DEFAULT_TOOL_NAMES.getSearchContent): string {
|
|
429
|
+
const assessment = artifact.claims?.[0];
|
|
430
|
+
const lines = [`# Source check: ${artifact.query}`, ""];
|
|
431
|
+
if (assessment) {
|
|
432
|
+
lines.push(`**Status:** ${assessment.status} (confidence ${assessment.confidence.toFixed(2)})`);
|
|
433
|
+
lines.push(`**Rationale:** ${assessment.rationale}`);
|
|
434
|
+
lines.push("");
|
|
435
|
+
}
|
|
436
|
+
if (artifact.sources.length > 0) {
|
|
437
|
+
lines.push("## Sources");
|
|
438
|
+
let budget = 4_000;
|
|
439
|
+
let omitted = 0;
|
|
440
|
+
for (const source of artifact.sources) {
|
|
441
|
+
lines.push(`${source.rank}. [${source.quality}] ${source.title}\n ${source.url}`);
|
|
442
|
+
for (const passage of artifact.passages.filter((candidate) => candidate.source_rank === source.rank)) {
|
|
443
|
+
const flat = passage.text.replace(/\s+/g, " ").trim();
|
|
444
|
+
// Drop a trailing high surrogate so the cut never splits an emoji.
|
|
445
|
+
const text = flat.length > 400 ? `${flat.slice(0, 400).replace(/[\uD800-\uDBFF]$/, "")}…` : flat;
|
|
446
|
+
if (text.length > budget) omitted++;
|
|
447
|
+
else {
|
|
448
|
+
budget -= text.length;
|
|
449
|
+
const label = passage.origin === "provider_summary" ? " [provider summary, not page text]" : "";
|
|
450
|
+
lines.push(` - ${passage.passage_id}${label}: ${text}`);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
if (omitted > 0) lines.push(`${omitted} more passage${omitted === 1 ? "" : "s"} in the artifact.`);
|
|
455
|
+
lines.push("");
|
|
456
|
+
}
|
|
457
|
+
if (artifact.errors?.length) lines.push(`Search errors: ${artifact.errors.map((entry) => `${entry.query}: ${entry.error}`).join("; ")}`);
|
|
458
|
+
lines.push(getSearchContentTool
|
|
459
|
+
? `Artifact responseId: ${artifact.id} (retrievable via ${getSearchContentTool}).`
|
|
460
|
+
: `Artifact responseId: ${artifact.id}. Content retrieval is not registered.`);
|
|
461
|
+
return lines.join("\n");
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function duplicateQuerySet(results: QueryResultData[]): Set<string> {
|
|
465
|
+
const counts = new Map<string, number>();
|
|
466
|
+
for (const result of results) {
|
|
467
|
+
counts.set(result.query, (counts.get(result.query) ?? 0) + 1);
|
|
468
|
+
}
|
|
469
|
+
const duplicates = new Set<string>();
|
|
470
|
+
for (const [query, count] of counts) {
|
|
471
|
+
if (count > 1) duplicates.add(query);
|
|
472
|
+
}
|
|
473
|
+
return duplicates;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function formatQueryHeader(query: string, provider: string | undefined, duplicateQueries: Set<string>): string {
|
|
477
|
+
const suffix = duplicateQueries.has(query) && provider ? ` (${provider})` : "";
|
|
478
|
+
return `## Query: "${query}"${suffix}\n\n`;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function hasFullInlineCoverage(urls: string[], inlineContent: ExtractedContent[] | undefined): boolean {
|
|
482
|
+
if (!inlineContent || inlineContent.length === 0) return false;
|
|
483
|
+
const coveredUrls = new Set(inlineContent.map(c => c.url));
|
|
484
|
+
return urls.every(url => coveredUrls.has(url));
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function formatFullResults(queryData: QueryResultData): string {
|
|
488
|
+
let output = `## Results for: "${queryData.query}"\n\n`;
|
|
489
|
+
const providers = queryData.providers ?? (queryData.provider ? [queryData.provider] : []);
|
|
490
|
+
if (providers.length > 0) output += `**Provider${providers.length === 1 ? "" : "s"}:** ${providers.join(", ")}\n\n`;
|
|
491
|
+
if (queryData.answer) {
|
|
492
|
+
output += `${queryData.answer}\n\n---\n\n`;
|
|
493
|
+
}
|
|
494
|
+
for (const r of queryData.results) {
|
|
495
|
+
output += `### ${r.title}\n${r.url}${r.snippet ? `\n\n${r.snippet}` : ""}\n\n`;
|
|
496
|
+
}
|
|
497
|
+
return output;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
interface StoredEntry {
|
|
501
|
+
label: string;
|
|
502
|
+
content: string | null;
|
|
503
|
+
error: string | null;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// Last resort for a limit smaller than the fixed wording; budgeting below keeps normal limits clear of it.
|
|
507
|
+
function capText(text: string, maxChars: number): string {
|
|
508
|
+
if (text.length <= maxChars) return text;
|
|
509
|
+
const marker = "\n[Output truncated.]";
|
|
510
|
+
return marker.length >= maxChars ? text.slice(0, maxChars) : text.slice(0, maxChars - marker.length) + marker;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// A responseId with several queries or URLs and no index: list the entries, or run findText over all
|
|
514
|
+
// of them, instead of failing the call (#687). The returned text stays within maxChars.
|
|
515
|
+
function readAllStoredEntries(
|
|
516
|
+
params: GetSearchContentParams,
|
|
517
|
+
indexKey: "queryIndex" | "urlIndex",
|
|
518
|
+
noun: "queries" | "URLs",
|
|
519
|
+
entries: StoredEntry[],
|
|
520
|
+
maxChars: number,
|
|
521
|
+
): WebToolResult {
|
|
522
|
+
const responseId = params.responseId;
|
|
523
|
+
const title = `${entries.length} stored ${noun}`;
|
|
524
|
+
if (params.findText === undefined) {
|
|
525
|
+
const head = `responseId ${formatInputValue(responseId)} holds ${title}. Pass ${indexKey} to read one, or findText to search all of them.`;
|
|
526
|
+
const lines = entries.map((entry, index) => `${index}: ${entry.label} (${entry.content === null ? `error: ${entry.error}` : `${entry.content.length} chars`})`);
|
|
527
|
+
const notListed = (shown: number) => `${entries.length - shown} more not listed (${indexKey} ${shown}-${entries.length - 1}).`;
|
|
528
|
+
let text = [head, ...lines].join("\n");
|
|
529
|
+
if (text.length > maxChars) {
|
|
530
|
+
let shown = 0;
|
|
531
|
+
let length = head.length;
|
|
532
|
+
while (shown < lines.length && length + 1 + lines[shown].length + 1 + notListed(shown + 1).length <= maxChars) {
|
|
533
|
+
length += 1 + lines[shown].length;
|
|
534
|
+
shown++;
|
|
535
|
+
}
|
|
536
|
+
text = [head, ...lines.slice(0, shown), notListed(shown)].join("\n");
|
|
537
|
+
}
|
|
538
|
+
return {
|
|
539
|
+
content: [{ type: "text", text: capText(text, maxChars) }],
|
|
540
|
+
details: { responseId, title, contentLength: entries.reduce((total, entry) => total + (entry.content?.length ?? 0), 0) },
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
const findMode = params.findMode ?? "case-insensitive";
|
|
545
|
+
let queries: string[];
|
|
546
|
+
try {
|
|
547
|
+
queries = normalizeFindQueries(params.findText);
|
|
548
|
+
} catch (err) {
|
|
549
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
550
|
+
return {
|
|
551
|
+
content: [{ type: "text", text: `Unable to find ${formatInputValue(params.findText)} in responseId ${formatInputValue(responseId)}: ${error}. Check findText and use a supported findMode.` }],
|
|
552
|
+
details: { error, responseId },
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
const found = entries.map((entry) => entry.content === null ? null : findContent(entry.content, queries, findMode));
|
|
556
|
+
const sections = found.flatMap((result, index) => result && result.matchCount > 0
|
|
557
|
+
? [{ index, text: `## ${indexKey} ${index}: ${entries[index].label}\n\n${result.text}`, returnedMatches: result.returnedMatches }]
|
|
558
|
+
: []);
|
|
559
|
+
const noMatches = found.flatMap((result, index) => result?.matchCount === 0 ? [index] : []);
|
|
560
|
+
const failed = entries.flatMap((entry, index) => entry.content === null ? [`${index} (${entry.error})`] : []);
|
|
561
|
+
const notes: string[] = [];
|
|
562
|
+
if (noMatches.length > 0) notes.push(`No matches in ${indexKey} ${noMatches.join(", ")}.`);
|
|
563
|
+
if (failed.length > 0) notes.push(`Not searched (failed): ${indexKey} ${failed.join(", ")}.`);
|
|
564
|
+
const heading = `findText searched ${title} in responseId ${formatInputValue(responseId)}.`;
|
|
565
|
+
const omittedNotice = (omitted: number[]) => `Matches in ${indexKey} ${omitted.join(", ")} omitted to stay under ${maxChars} chars; repeat with ${indexKey} to read them.`;
|
|
566
|
+
const separator = "\n\n";
|
|
567
|
+
let shown = sections;
|
|
568
|
+
const omitted: number[] = [];
|
|
569
|
+
if ([heading, ...sections.map((section) => section.text), ...notes].join(separator).length > maxChars) {
|
|
570
|
+
// Reserve the notice's longest form, with every section omitted, so any subset still fits.
|
|
571
|
+
let budget = maxChars - [heading, ...notes, omittedNotice(sections.map((section) => section.index))].join(separator).length;
|
|
572
|
+
shown = [];
|
|
573
|
+
for (const section of sections) {
|
|
574
|
+
if (separator.length + section.text.length <= budget) {
|
|
575
|
+
shown.push(section);
|
|
576
|
+
budget -= separator.length + section.text.length;
|
|
577
|
+
} else omitted.push(section.index);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
const text = [heading, ...shown.map((section) => section.text), ...notes, ...(omitted.length > 0 ? [omittedNotice(omitted)] : [])].join(separator);
|
|
581
|
+
return {
|
|
582
|
+
content: [{ type: "text", text: capText(text, maxChars) }],
|
|
583
|
+
details: {
|
|
584
|
+
responseId,
|
|
585
|
+
title,
|
|
586
|
+
findMode,
|
|
587
|
+
matchCount: found.reduce((total, result) => total + (result?.matchCount ?? 0), 0),
|
|
588
|
+
returnedMatches: shown.reduce((total, section) => total + section.returnedMatches, 0),
|
|
589
|
+
...(failed.length === entries.length ? { error: "Every stored entry failed" } : {}),
|
|
590
|
+
},
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function boundSearchPresentation(
|
|
595
|
+
text: string,
|
|
596
|
+
guidance: string,
|
|
597
|
+
truncationGuidance: string,
|
|
598
|
+
maxChars: number,
|
|
599
|
+
): { text: string; truncated: boolean; originalChars: number; returnedChars: number; omittedChars: number } {
|
|
600
|
+
const fullText = `${text}${guidance}`;
|
|
601
|
+
if (fullText.length <= maxChars) {
|
|
602
|
+
return { text: fullText, truncated: false, originalChars: text.length, returnedChars: text.length, omittedChars: 0 };
|
|
603
|
+
}
|
|
604
|
+
const marker = `\n\n---\n[Output truncated.]${truncationGuidance}`;
|
|
605
|
+
// Reserve marker space so the complete model-visible response never exceeds the configured ceiling.
|
|
606
|
+
const prefixLength = maxChars - marker.length;
|
|
607
|
+
const bounded = `${text.slice(0, prefixLength)}${marker}`;
|
|
608
|
+
return {
|
|
609
|
+
text: bounded,
|
|
610
|
+
truncated: true,
|
|
611
|
+
originalChars: text.length,
|
|
612
|
+
returnedChars: prefixLength,
|
|
613
|
+
omittedChars: text.length - prefixLength,
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
export type SummaryWorkflow = "summary-review" | "auto-summary";
|
|
618
|
+
export type FetchedContentData = StoredSearchData & { type: "fetch"; urls: ExtractedContent[] };
|
|
619
|
+
|
|
620
|
+
export interface SearchReturnOptions {
|
|
621
|
+
queryList: string[];
|
|
622
|
+
results: QueryResultData[];
|
|
623
|
+
urls: string[];
|
|
624
|
+
includeContent: boolean;
|
|
625
|
+
inlineContent?: ExtractedContent[];
|
|
626
|
+
curated?: boolean;
|
|
627
|
+
curatedFrom?: number;
|
|
628
|
+
workflow?: SummaryWorkflow;
|
|
629
|
+
approvedSummary?: string;
|
|
630
|
+
summaryMeta?: SummaryMeta;
|
|
631
|
+
proxy?: string;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** Tool names and limits a host resolved once at startup. */
|
|
635
|
+
export interface WebToolCoreSettings {
|
|
636
|
+
toolNames: ToolNames;
|
|
637
|
+
enabledTools: Record<keyof ToolNames, boolean>;
|
|
638
|
+
/** Output ceiling for search results and stored-content pages. fetch_content rereads config per call. */
|
|
639
|
+
maxInlineContentChars: number;
|
|
640
|
+
fetchModes: FetchModeConfig;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
export interface PageAnswerRequest {
|
|
644
|
+
question: string;
|
|
645
|
+
pageText: string;
|
|
646
|
+
sourceUrl: string;
|
|
647
|
+
model?: string;
|
|
648
|
+
/** Video frames or a fetched image, sent to the answer model as image input. */
|
|
649
|
+
images?: Array<{ data: string; mimeType: string; label?: string }>;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/** Everything that differs between hosts. Pi supplies session persistence, background
|
|
653
|
+
* notifications, and page answers; the standalone host keeps results in memory only. */
|
|
654
|
+
export interface WebToolCoreHost {
|
|
655
|
+
settings: WebToolCoreSettings;
|
|
656
|
+
/** Store fetched page content under id so the retrieval tool can page through it. */
|
|
657
|
+
storeFetchedContent(id: string, data: FetchedContentData): void;
|
|
658
|
+
/** Called after search or research results are stored in memory. */
|
|
659
|
+
publishResult?(data: StoredSearchData): void;
|
|
660
|
+
/** Fetch includeContent pages the provider did not cover in the background and return
|
|
661
|
+
* their responseId. When omitted, web_search awaits the same fetch before returning. */
|
|
662
|
+
startBackgroundFetch?(urls: string[], proxy?: string, provided?: ExtractedContent[]): string | null;
|
|
663
|
+
/** Answers fetch_content mode "answer"; requires the host's model access. */
|
|
664
|
+
answerFromPage?(request: PageAnswerRequest, extensionContext: ExtensionContext | undefined, signal?: AbortSignal): Promise<{ text: string; usage?: Usage }>;
|
|
665
|
+
/** Extraction options every fetch in this host adds (for example direct-image policy). */
|
|
666
|
+
extractOptions?: Pick<ExtractOptions, "rejectDirectImages">;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
export type WebToolUpdate = (update: { content: Array<{ type: "text"; text: string }>; details: Record<string, unknown> }) => void;
|
|
670
|
+
|
|
671
|
+
/** Per-call inputs only Pi has: its live ExtensionContext and partial-result callback. */
|
|
672
|
+
export interface WebToolCallOptions {
|
|
673
|
+
extensionContext?: ExtensionContext;
|
|
674
|
+
onUpdate?: WebToolUpdate;
|
|
675
|
+
/** Lets Gemini-only routes ask the user to turn on browser cookie access. */
|
|
676
|
+
browserCookieConsent?: BrowserCookieConsent;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
export interface WebSearchCallOptions extends WebToolCallOptions {
|
|
680
|
+
/** Generates an auto-summary after searches complete; returning a tool result ends the call. */
|
|
681
|
+
summarize?(results: QueryResultData[]): Promise<WebToolResult | { approvedSummary: string; summaryMeta: SummaryMeta }>;
|
|
682
|
+
/** Wait for includeContent pages and store them with the result instead of fetching in the background. */
|
|
683
|
+
awaitContent?: boolean;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// Pi's TypeBox schemas type enums as plain strings; the core normalizes them.
|
|
687
|
+
export type WebSearchParams = Omit<WebSearchCallParams, "recencyFilter"> & { recencyFilter?: string; workflow?: string };
|
|
688
|
+
export type FetchContentToolParams = FetchContentCallParams & FetchContentParams;
|
|
689
|
+
export type SourceCheckParams = Omit<SourceCheckCallParams, "recencyFilter"> & { recencyFilter?: string };
|
|
690
|
+
|
|
691
|
+
export interface WebToolCoreInstance extends WebToolCore {
|
|
692
|
+
webSearch(params: WebSearchParams, signal?: AbortSignal, call?: WebSearchCallOptions): Promise<WebToolResult>;
|
|
693
|
+
fetchContent(params: FetchContentToolParams, signal?: AbortSignal, call?: WebToolCallOptions): Promise<WebToolResult>;
|
|
694
|
+
getSearchContent(params: RawGetSearchContentParams, signal?: AbortSignal): Promise<WebToolResult>;
|
|
695
|
+
sourceCheck(params: SourceCheckParams, signal?: AbortSignal, call?: WebToolCallOptions): Promise<WebToolResult>;
|
|
696
|
+
/** Formats and stores search results; the Pi curator reuses it for curated returns. */
|
|
697
|
+
buildSearchReturn(opts: SearchReturnOptions): WebToolResult;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** Names fetch guidance may point at: only tools registered this session. */
|
|
701
|
+
export function registeredFetchToolNames(settings: WebToolCoreSettings): NonNullable<ExtractOptions["toolNames"]> {
|
|
702
|
+
return {
|
|
703
|
+
...(settings.enabledTools.webSearch ? { webSearch: settings.toolNames.webSearch } : {}),
|
|
704
|
+
...(settings.enabledTools.fetchContent ? { fetchContent: settings.toolNames.fetchContent } : {}),
|
|
705
|
+
...(settings.enabledTools.getSearchContent ? { getSearchContent: settings.toolNames.getSearchContent } : {}),
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
export function storedContentSourceNames(settings: WebToolCoreSettings): string {
|
|
710
|
+
return joinToolNames([
|
|
711
|
+
...(settings.enabledTools.webSearch ? [settings.toolNames.webSearch] : []),
|
|
712
|
+
...(settings.enabledTools.sourceCheck ? [settings.toolNames.sourceCheck] : []),
|
|
713
|
+
...(settings.enabledTools.fetchContent ? [settings.toolNames.fetchContent] : []),
|
|
714
|
+
]);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/** Keeps a page end from splitting a surrogate pair: it moves back one code unit,
|
|
718
|
+
* or past the pair when moving back would leave the page empty. */
|
|
719
|
+
function pageEnd(content: string, offset: number, end: number): number {
|
|
720
|
+
if (end <= offset || end >= content.length) return end;
|
|
721
|
+
const high = content.charCodeAt(end - 1);
|
|
722
|
+
const low = content.charCodeAt(end);
|
|
723
|
+
if (high < 0xd800 || high > 0xdbff || low < 0xdc00 || low > 0xdfff) return end;
|
|
724
|
+
return end - 1 > offset ? end - 1 : end + 1;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** Slices content from offset and appends the next-slice instructions, shrinking
|
|
728
|
+
* the slice so the whole page, instructions included, stays within maxChars. */
|
|
729
|
+
function sliceWithContinuation(content: string, offset: number, limit: number, maxChars: number, continuationAt: (endOffset: number) => string): { endOffset: number; text: string } {
|
|
730
|
+
let endOffset = pageEnd(content, offset, offset + Math.min(limit, content.length - offset));
|
|
731
|
+
let continuation = "";
|
|
732
|
+
while (endOffset < content.length) {
|
|
733
|
+
continuation = continuationAt(endOffset);
|
|
734
|
+
const overflow = endOffset - offset + continuation.length - maxChars;
|
|
735
|
+
if (overflow <= 0) break;
|
|
736
|
+
endOffset = pageEnd(content, offset, endOffset - overflow);
|
|
737
|
+
}
|
|
738
|
+
return { endOffset, text: content.slice(offset, endOffset) + (endOffset < content.length ? continuation : "") };
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
export function createWebToolCore(host: WebToolCoreHost): WebToolCoreInstance {
|
|
742
|
+
const { settings } = host;
|
|
743
|
+
const toolNames = settings.toolNames;
|
|
744
|
+
const getSearchContentEnabled = settings.enabledTools.getSearchContent;
|
|
745
|
+
const fetchModeConfig = settings.fetchModes;
|
|
746
|
+
const registeredToolNames = registeredFetchToolNames(settings);
|
|
747
|
+
const storedContentSources = storedContentSourceNames(settings);
|
|
748
|
+
|
|
749
|
+
function fetchOptions(options: ExtractOptions | undefined, proxy?: string): ExtractOptions {
|
|
750
|
+
const merged = host.extractOptions ? { ...(options ?? {}), ...host.extractOptions } : options;
|
|
751
|
+
return withRegisteredFetchOptions(merged, registeredToolNames, proxy);
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
function storeFetchResult(responseId: string, data: FetchedContentData, authProfile?: AuthFetchProfile): boolean {
|
|
755
|
+
if (authProfile?.cache === "off") return false;
|
|
756
|
+
host.storeFetchedContent(responseId, data);
|
|
757
|
+
return true;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
function storeAndPublishSearch(results: QueryResultData[]): string {
|
|
761
|
+
const id = generateId();
|
|
762
|
+
const data: StoredSearchData = {
|
|
763
|
+
id, type: "search", timestamp: Date.now(), queries: results,
|
|
764
|
+
};
|
|
765
|
+
storeResult(id, data);
|
|
766
|
+
host.publishResult?.(data);
|
|
767
|
+
return id;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function buildSearchReturn(opts: SearchReturnOptions): WebToolResult {
|
|
771
|
+
const sc = opts.results.filter(r => !r.error).length;
|
|
772
|
+
const tr = opts.results.reduce((sum, r) => sum + r.results.length, 0);
|
|
773
|
+
|
|
774
|
+
const hasApprovedSummary = typeof opts.approvedSummary === "string" && opts.approvedSummary.trim().length > 0;
|
|
775
|
+
const maxInlineContentChars = settings.maxInlineContentChars;
|
|
776
|
+
let output = "";
|
|
777
|
+
if (hasApprovedSummary) {
|
|
778
|
+
output = opts.approvedSummary!.trim();
|
|
779
|
+
} else {
|
|
780
|
+
if (opts.curated) {
|
|
781
|
+
output += "[These results were manually curated by the user in the browser. Use them as-is — do not re-search or discard.]\n\n";
|
|
782
|
+
}
|
|
783
|
+
const providerNames = opts.results.map(result => {
|
|
784
|
+
const providers = result.providers ?? (result.provider ? [result.provider] : []);
|
|
785
|
+
return providers.join(", ") || "unknown";
|
|
786
|
+
});
|
|
787
|
+
output += opts.results.length === 1
|
|
788
|
+
? `**Provider:** ${providerNames[0]}\n\n`
|
|
789
|
+
: `**Providers used:** ${providerNames.map((name, index) => `Query ${index + 1}: ${name}`).join("; ")}\n\n`;
|
|
790
|
+
const duplicateQueries = opts.curated ? duplicateQuerySet(opts.results) : new Set<string>();
|
|
791
|
+
for (const { query, answer, results, error, provider } of opts.results) {
|
|
792
|
+
if (opts.queryList.length > 1) {
|
|
793
|
+
output += opts.curated
|
|
794
|
+
? formatQueryHeader(query, provider, duplicateQueries)
|
|
795
|
+
: `## Query: "${query}"\n\n`;
|
|
796
|
+
}
|
|
797
|
+
if (error) output += `Error: ${error}\n\n`;
|
|
798
|
+
else output += formatSearchSummary(results, answer) + "\n\n";
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const hasInlineReady = hasFullInlineCoverage(opts.urls, opts.inlineContent);
|
|
803
|
+
let fetchId: string | null = null;
|
|
804
|
+
if (hasInlineReady && opts.inlineContent) {
|
|
805
|
+
fetchId = generateId();
|
|
806
|
+
const data = {
|
|
807
|
+
id: fetchId,
|
|
808
|
+
type: "fetch",
|
|
809
|
+
timestamp: Date.now(),
|
|
810
|
+
urls: opts.inlineContent,
|
|
811
|
+
} satisfies FetchedContentData;
|
|
812
|
+
host.storeFetchedContent(fetchId, data);
|
|
813
|
+
} else if (opts.includeContent) {
|
|
814
|
+
fetchId = host.startBackgroundFetch?.(opts.urls, opts.proxy, opts.inlineContent) ?? null;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
const searchId = storeAndPublishSearch(opts.results);
|
|
818
|
+
const isBackgroundFetch = fetchId !== null && !hasInlineReady;
|
|
819
|
+
const unboundedPresentation = output.trim();
|
|
820
|
+
const buildGuidance = (forTruncation: boolean): string => {
|
|
821
|
+
let value = "";
|
|
822
|
+
if (hasInlineReady && opts.inlineContent && fetchId) {
|
|
823
|
+
value += `\n---\nFull content for ${opts.inlineContent.length} sources is ready as responseId "${fetchId}". `;
|
|
824
|
+
value += getSearchContentEnabled
|
|
825
|
+
? `Use ${toolNames.getSearchContent}({ responseId: "${fetchId}", urlIndex: 0, offset: 0, limit: ${maxInlineContentChars} }) to retrieve the first bounded page.`
|
|
826
|
+
: forTruncation ? `Enable ${toolNames.getSearchContent} to retrieve the full stored content.` : "";
|
|
827
|
+
} else if (isBackgroundFetch && fetchId) {
|
|
828
|
+
value += `\n---\nContent fetching in background as responseId "${fetchId}". Will notify when ready.`;
|
|
829
|
+
}
|
|
830
|
+
if (getSearchContentEnabled || forTruncation) {
|
|
831
|
+
value += `\n---\nFull search results are stored as responseId "${searchId}". `;
|
|
832
|
+
value += getSearchContentEnabled
|
|
833
|
+
? `Use ${toolNames.getSearchContent}({ responseId: "${searchId}", queryIndex: 0, offset: 0, limit: ${maxInlineContentChars} }) to retrieve the first bounded page${opts.results.length > 1 ? `; repeat with queryIndex 1 through ${opts.results.length - 1}` : ""}.`
|
|
834
|
+
: `Enable ${toolNames.getSearchContent} to retrieve the full stored results.`;
|
|
835
|
+
}
|
|
836
|
+
return value;
|
|
837
|
+
};
|
|
838
|
+
const presentation = hasApprovedSummary
|
|
839
|
+
? { text: unboundedPresentation, truncated: false, originalChars: unboundedPresentation.length, returnedChars: unboundedPresentation.length, omittedChars: 0 }
|
|
840
|
+
: boundSearchPresentation(unboundedPresentation, buildGuidance(false), buildGuidance(true), maxInlineContentChars);
|
|
841
|
+
|
|
842
|
+
const summaryGuidance = hasApprovedSummary ? buildGuidance(false) : "";
|
|
843
|
+
return {
|
|
844
|
+
content: [
|
|
845
|
+
{ type: "text", text: presentation.text },
|
|
846
|
+
...(summaryGuidance ? [{ type: "text" as const, text: summaryGuidance }] : []),
|
|
847
|
+
],
|
|
848
|
+
structuredContent: searchStructuredContent(searchId, fetchId, opts.results),
|
|
849
|
+
details: {
|
|
850
|
+
queries: opts.queryList,
|
|
851
|
+
queryCount: opts.queryList.length,
|
|
852
|
+
successfulQueries: sc,
|
|
853
|
+
totalResults: tr,
|
|
854
|
+
includeContent: opts.includeContent,
|
|
855
|
+
fetchId,
|
|
856
|
+
fetchUrls: isBackgroundFetch ? opts.urls : undefined,
|
|
857
|
+
searchId,
|
|
858
|
+
queryProviders: opts.results.map(result => ({
|
|
859
|
+
query: result.query,
|
|
860
|
+
providers: result.providers ?? (result.provider ? [result.provider] : []),
|
|
861
|
+
})),
|
|
862
|
+
truncated: presentation.truncated,
|
|
863
|
+
originalChars: presentation.originalChars,
|
|
864
|
+
returnedChars: presentation.returnedChars,
|
|
865
|
+
omittedChars: presentation.omittedChars,
|
|
866
|
+
...(opts.curated ? {
|
|
867
|
+
curated: true,
|
|
868
|
+
curatedFrom: opts.curatedFrom,
|
|
869
|
+
curatedQueries: opts.results.map(r => ({
|
|
870
|
+
query: r.query,
|
|
871
|
+
provider: r.provider || null,
|
|
872
|
+
answer: r.answer || null,
|
|
873
|
+
sources: r.results.map(s => ({ title: s.title, url: s.url })),
|
|
874
|
+
error: r.error,
|
|
875
|
+
})),
|
|
876
|
+
} : {}),
|
|
877
|
+
...((opts.workflow && hasApprovedSummary)
|
|
878
|
+
? {
|
|
879
|
+
summary: {
|
|
880
|
+
text: opts.approvedSummary!.trim(),
|
|
881
|
+
workflow: opts.workflow,
|
|
882
|
+
model: opts.summaryMeta?.model ?? null,
|
|
883
|
+
durationMs: opts.summaryMeta?.durationMs ?? 0,
|
|
884
|
+
tokenEstimate: opts.summaryMeta?.tokenEstimate ?? 0,
|
|
885
|
+
fallbackUsed: opts.summaryMeta?.fallbackUsed === true,
|
|
886
|
+
fallbackReason: opts.summaryMeta?.fallbackReason,
|
|
887
|
+
phase: opts.summaryMeta?.phase,
|
|
888
|
+
edited: opts.summaryMeta?.edited === true,
|
|
889
|
+
},
|
|
890
|
+
}
|
|
891
|
+
: {}),
|
|
892
|
+
},
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
async function webSearch(params: WebSearchParams, signal?: AbortSignal, call: WebSearchCallOptions = {}): Promise<WebToolResult> {
|
|
897
|
+
const model = validateSearchModelOverride(params.provider, params.model);
|
|
898
|
+
const { extensionContext: ctx, onUpdate, browserCookieConsent } = call;
|
|
899
|
+
return runWithProxy(typeof params.proxy === "string" ? params.proxy : undefined, async () => {
|
|
900
|
+
const rawQueryList: unknown[] = Array.isArray(params.queries)
|
|
901
|
+
? params.queries
|
|
902
|
+
: (params.query !== undefined ? expandQueryString(params.query) : []);
|
|
903
|
+
const queryList = normalizeQueryList(rawQueryList);
|
|
904
|
+
const recencyFilter = normalizeRecencyFilter(params.recencyFilter);
|
|
905
|
+
|
|
906
|
+
if (queryList.length === 0) {
|
|
907
|
+
return {
|
|
908
|
+
content: [{ type: "text", text: "Error: No query provided. Use 'query' or 'queries' parameter." }],
|
|
909
|
+
details: { error: "No query provided" },
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
let completedSearches = 0;
|
|
914
|
+
const allUrls: string[] = [];
|
|
915
|
+
const allInlineContent: ExtractedContent[] = [];
|
|
916
|
+
const resolvedProvider = resolveRequestedProvider(params.provider);
|
|
917
|
+
const providerFromConfig = (parseProviderArgument(params.provider) ?? "auto") === "auto";
|
|
918
|
+
|
|
919
|
+
const queryResponses = await runSearchQueries(queryList, async (query) => {
|
|
920
|
+
signal?.throwIfAborted();
|
|
921
|
+
onUpdate?.({
|
|
922
|
+
content: [{ type: "text", text: `Searching "${query}" (${completedSearches}/${queryList.length} complete)...` }],
|
|
923
|
+
details: { phase: "search", progress: completedSearches / queryList.length, currentQuery: query },
|
|
924
|
+
});
|
|
925
|
+
|
|
926
|
+
try {
|
|
927
|
+
const { answer, results, inlineContent, provider, providerResponses } = await search(query, {
|
|
928
|
+
provider: resolvedProvider,
|
|
929
|
+
model,
|
|
930
|
+
providerFromConfig,
|
|
931
|
+
numResults: params.numResults,
|
|
932
|
+
recencyFilter,
|
|
933
|
+
domainFilter: params.domainFilter,
|
|
934
|
+
objective: params.objective,
|
|
935
|
+
includeContent: params.includeContent,
|
|
936
|
+
category: params.category,
|
|
937
|
+
signal,
|
|
938
|
+
extensionContext: ctx,
|
|
939
|
+
browserCookieConsent,
|
|
940
|
+
});
|
|
941
|
+
|
|
942
|
+
const providers = providerResponses?.map(response => response.provider) ?? [provider];
|
|
943
|
+
return { result: { query, answer, results, error: null, provider, providers } satisfies QueryResultData, inlineContent };
|
|
944
|
+
} catch (err) {
|
|
945
|
+
if (signal?.aborted || isAbortError(err)) throw err;
|
|
946
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
947
|
+
const requestedProvider = toCuratorProvider(resolvedProvider);
|
|
948
|
+
return {
|
|
949
|
+
result: { query, answer: "", results: [], error: message, provider: requestedProvider } satisfies QueryResultData,
|
|
950
|
+
inlineContent: undefined,
|
|
951
|
+
};
|
|
952
|
+
} finally {
|
|
953
|
+
completedSearches++;
|
|
954
|
+
if (!signal?.aborted) {
|
|
955
|
+
onUpdate?.({
|
|
956
|
+
content: [{ type: "text", text: `Completed ${completedSearches}/${queryList.length} searches.` }],
|
|
957
|
+
details: { phase: "search", progress: completedSearches / queryList.length, currentQuery: query },
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
});
|
|
962
|
+
const searchResults = queryResponses.map(response => response.result);
|
|
963
|
+
for (const response of queryResponses) {
|
|
964
|
+
for (const result of response.result.results) {
|
|
965
|
+
if (!allUrls.includes(result.url)) allUrls.push(result.url);
|
|
966
|
+
}
|
|
967
|
+
if (response.inlineContent) allInlineContent.push(...response.inlineContent);
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
let approvedSummary: string | undefined;
|
|
971
|
+
let summaryMeta: SummaryMeta | undefined;
|
|
972
|
+
if (call.summarize) {
|
|
973
|
+
const summary = await call.summarize(searchResults);
|
|
974
|
+
if ("content" in summary) return summary;
|
|
975
|
+
approvedSummary = summary.approvedSummary;
|
|
976
|
+
summaryMeta = summary.summaryMeta;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
let inlineContent = allInlineContent.length > 0 ? allInlineContent : undefined;
|
|
980
|
+
if (params.includeContent && (call.awaitContent || !host.startBackgroundFetch) && allUrls.length > 0 && !hasFullInlineCoverage(allUrls, inlineContent)) {
|
|
981
|
+
// Hosts without background notifications, and calls that ask to, wait for the same page fetch instead.
|
|
982
|
+
const proxy = typeof params.proxy === "string" ? params.proxy : undefined;
|
|
983
|
+
const fetched = await fetchUncoveredContent(allUrls, inlineContent, urls => fetchAllContent(urls, signal, fetchOptions(undefined, proxy)));
|
|
984
|
+
signal?.throwIfAborted();
|
|
985
|
+
inlineContent = stripThumbnails(fetched);
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
return buildSearchReturn({
|
|
989
|
+
queryList,
|
|
990
|
+
results: searchResults,
|
|
991
|
+
urls: allUrls,
|
|
992
|
+
includeContent: params.includeContent ?? false,
|
|
993
|
+
inlineContent,
|
|
994
|
+
workflow: call.summarize ? "auto-summary" : undefined,
|
|
995
|
+
approvedSummary,
|
|
996
|
+
summaryMeta,
|
|
997
|
+
proxy: typeof params.proxy === "string" ? params.proxy : undefined,
|
|
998
|
+
});
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
async function sourceCheck(params: SourceCheckParams, signal?: AbortSignal, call: WebToolCallOptions = {}): Promise<WebToolResult> {
|
|
1003
|
+
const ctx = call.extensionContext;
|
|
1004
|
+
return runWithProxy(typeof params.proxy === "string" ? params.proxy : undefined, async () => {
|
|
1005
|
+
const claim = typeof params.claim === "string" ? params.claim.trim() : "";
|
|
1006
|
+
if (!claim) {
|
|
1007
|
+
return { content: [{ type: "text", text: "Error: 'claim' is required." }], details: { error: "Missing claim" } };
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
const requestedQueries = Array.isArray(params.queries)
|
|
1011
|
+
? params.queries.filter((query): query is string => typeof query === "string").map((query) => query.trim()).filter(Boolean)
|
|
1012
|
+
: [];
|
|
1013
|
+
const queries = (requestedQueries.length > 0 ? requestedQueries : [claim]).slice(0, 8);
|
|
1014
|
+
const numResults = typeof params.numResults === "number" && Number.isFinite(params.numResults)
|
|
1015
|
+
? Math.min(20, Math.max(1, Math.floor(params.numResults)))
|
|
1016
|
+
: 5;
|
|
1017
|
+
const domainFilter = Array.isArray(params.domainFilter)
|
|
1018
|
+
? params.domainFilter.filter((domain): domain is string => typeof domain === "string")
|
|
1019
|
+
: undefined;
|
|
1020
|
+
const recencyFilter = normalizeRecencyFilter(params.recencyFilter);
|
|
1021
|
+
const resultsByUrl = new Map<string, SearchResult>();
|
|
1022
|
+
const summaries: string[] = [];
|
|
1023
|
+
const errors: Array<{ query: string; error: string }> = [];
|
|
1024
|
+
let provider: string | undefined;
|
|
1025
|
+
|
|
1026
|
+
for (const query of queries) {
|
|
1027
|
+
if (signal?.aborted) break;
|
|
1028
|
+
try {
|
|
1029
|
+
const response = await search(query, {
|
|
1030
|
+
provider: resolveRequestedProvider(params.provider),
|
|
1031
|
+
providerFromConfig: (parseProviderArgument(params.provider) ?? "auto") === "auto",
|
|
1032
|
+
numResults,
|
|
1033
|
+
recencyFilter,
|
|
1034
|
+
domainFilter,
|
|
1035
|
+
signal,
|
|
1036
|
+
extensionContext: ctx,
|
|
1037
|
+
});
|
|
1038
|
+
if (signal?.aborted) break;
|
|
1039
|
+
provider ??= response.provider;
|
|
1040
|
+
if (response.answer) summaries.push(`${query}: ${response.answer}`);
|
|
1041
|
+
for (const result of response.results) {
|
|
1042
|
+
if (!resultsByUrl.has(result.url)) resultsByUrl.set(result.url, result);
|
|
1043
|
+
}
|
|
1044
|
+
} catch (err) {
|
|
1045
|
+
if (signal?.aborted || isAbortError(err)) break;
|
|
1046
|
+
errors.push({ query, error: err instanceof Error ? err.message : String(err) });
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
const results = [...resultsByUrl.values()].slice(0, 20).map((result, index) => ({ ...result, rank: index + 1 }));
|
|
1051
|
+
let fetched: ExtractedContent[] = [];
|
|
1052
|
+
if (params.fetchContent && results.length > 0) {
|
|
1053
|
+
const urls = results.slice(0, 5).map((result) => result.url);
|
|
1054
|
+
try {
|
|
1055
|
+
fetched = await fetchAllContent(urls, signal, fetchOptions(undefined, typeof params.proxy === "string" ? params.proxy : undefined));
|
|
1056
|
+
} catch (err) {
|
|
1057
|
+
if (signal?.aborted || isAbortError(err)) throw err;
|
|
1058
|
+
fetched = urls.map((url) => ({ url, title: "", content: "", error: err instanceof Error ? err.message : String(err) }));
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
const artifact = withClaimAssessment(buildResearchArtifact({
|
|
1062
|
+
query: claim,
|
|
1063
|
+
provider,
|
|
1064
|
+
summary: summaries.length > 0 ? summaries.join("\n\n") : undefined,
|
|
1065
|
+
results,
|
|
1066
|
+
fetched,
|
|
1067
|
+
recency: recencyFilter,
|
|
1068
|
+
domainFilter,
|
|
1069
|
+
}), [claim]);
|
|
1070
|
+
if (errors.length > 0) artifact.errors = errors;
|
|
1071
|
+
storeResearchArtifact(artifact);
|
|
1072
|
+
host.publishResult?.({
|
|
1073
|
+
id: artifact.id,
|
|
1074
|
+
type: "research",
|
|
1075
|
+
timestamp: artifact.timestamp,
|
|
1076
|
+
artifact,
|
|
1077
|
+
});
|
|
1078
|
+
return {
|
|
1079
|
+
content: [{ type: "text", text: formatSourceCheckResult(artifact, getSearchContentEnabled ? toolNames.getSearchContent : null) }],
|
|
1080
|
+
details: { responseId: artifact.id, artifact, sourceCount: artifact.sources.length, passageCount: artifact.passages.length, searchCount: queries.length },
|
|
1081
|
+
};
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
// Answer mode's model calls are reported as the result's usage, so Pi counts them in the session's totals.
|
|
1086
|
+
async function fetchContent(params: FetchContentToolParams, signal?: AbortSignal, call: WebToolCallOptions = {}): Promise<WebToolResult> {
|
|
1087
|
+
const answerUsages: Usage[] = [];
|
|
1088
|
+
const result = await fetchPages(params, signal, call, answerUsages);
|
|
1089
|
+
return answerUsages.length > 0 ? { ...result, usage: answerUsages.reduce(combineUsage) } : result;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
async function fetchPages(params: FetchContentToolParams, signal: AbortSignal | undefined, call: WebToolCallOptions, answerUsages: Usage[]): Promise<WebToolResult> {
|
|
1093
|
+
const { extensionContext: ctx, onUpdate } = call;
|
|
1094
|
+
let normalized: ReturnType<typeof normalizeFetchContentParams>;
|
|
1095
|
+
try {
|
|
1096
|
+
normalized = normalizeFetchContentParams(params);
|
|
1097
|
+
} catch (err) {
|
|
1098
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
1099
|
+
return { content: [{ type: "text", text: `Error: ${error}` }], details: { error } };
|
|
1100
|
+
}
|
|
1101
|
+
const { urlList, options } = normalized;
|
|
1102
|
+
const mode = options.mode ?? fetchModeConfig.defaultMode;
|
|
1103
|
+
if (!fetchModeConfig.allowedModes.includes(mode)) {
|
|
1104
|
+
const error = MODEL_FETCH_MODES.includes(mode) && getRetrievalOnlyPolicy().enabled
|
|
1105
|
+
? retrievalOnlyError(`Fetch mode "${mode}"`).message
|
|
1106
|
+
: `Fetch mode "${mode}" is disabled by fetch.allowedModes.`;
|
|
1107
|
+
return { content: [{ type: "text", text: `Error: ${error}` }], details: { error } };
|
|
1108
|
+
}
|
|
1109
|
+
// Aggregate all validation problems instead of failing on the first
|
|
1110
|
+
// one, and check the URL first: a missing URL is the root cause of
|
|
1111
|
+
// most retries, and naming the parameters that actually arrived helps
|
|
1112
|
+
// tell dropped tool-call arguments (provider issue) apart from
|
|
1113
|
+
// malformed ones (caller issue). Parameter-level normalization
|
|
1114
|
+
// problems (mode, redirects, auth, proxy) are collected too, so one
|
|
1115
|
+
// round-trip reports every fixable parameter at once.
|
|
1116
|
+
const problems: string[] = [];
|
|
1117
|
+
if (urlList.length === 0) {
|
|
1118
|
+
problems.push("url" in params || "urls" in params
|
|
1119
|
+
? `No usable URL provided (received parameters: ${describeReceivedParams(params)}). 'url' must be a non-empty string or 'urls' a non-empty array`
|
|
1120
|
+
: `No URL provided (received parameters: ${describeReceivedParams(params)}). Use the 'url' parameter, or 'urls' for parallel fetches`);
|
|
1121
|
+
}
|
|
1122
|
+
problems.push(...normalized.problems);
|
|
1123
|
+
if (mode === "answer" && !options.prompt) problems.push("mode answer requires prompt");
|
|
1124
|
+
if (mode === "raw" && (options.forceClone === true || options.timestamp || options.frames || options.prompt || options.model || options.answerModel)) {
|
|
1125
|
+
problems.push("mode raw cannot be combined with forceClone, prompt, timestamp, frames, model, or answerModel");
|
|
1126
|
+
}
|
|
1127
|
+
if (mode !== "answer" && options.answerModel) problems.push("answerModel requires mode answer");
|
|
1128
|
+
if (mode === "answer" && options.model) problems.push("use answerModel, not model, with mode answer");
|
|
1129
|
+
// Authenticated page text never goes to a hosted model.
|
|
1130
|
+
if ((mode === "answer" || mode === "extract") && options.auth !== undefined) problems.push(`auth cannot be combined with mode ${mode}`);
|
|
1131
|
+
if (mode !== "extract" && params.fields !== undefined) problems.push("fields requires mode extract");
|
|
1132
|
+
let extractFields: ReturnType<typeof parseExtractFields> | undefined;
|
|
1133
|
+
if (mode === "extract") {
|
|
1134
|
+
try {
|
|
1135
|
+
if (params.fields === undefined) throw new Error("mode extract requires fields");
|
|
1136
|
+
extractFields = parseExtractFields(params.fields);
|
|
1137
|
+
} catch (err) {
|
|
1138
|
+
problems.push(err instanceof Error ? err.message : String(err));
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
if (problems.length > 0) {
|
|
1142
|
+
const error = problems.join("; ");
|
|
1143
|
+
return { content: [{ type: "text", text: `Error: ${error}.` }], details: { error, problems } };
|
|
1144
|
+
}
|
|
1145
|
+
return runWithProxy(options.proxy, async () => {
|
|
1146
|
+
let authFetchProfile: AuthFetchProfile | undefined;
|
|
1147
|
+
if (options.auth !== undefined) {
|
|
1148
|
+
try {
|
|
1149
|
+
authFetchProfile = resolveAuthFetchProfile(options.auth);
|
|
1150
|
+
} catch (err) {
|
|
1151
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
1152
|
+
return { content: [{ type: "text", text: `Error: ${error}` }], details: { error } };
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
onUpdate?.({
|
|
1157
|
+
content: [{ type: "text", text: `Fetching ${urlList.length} URL(s)...` }],
|
|
1158
|
+
details: { phase: "fetch", progress: 0 },
|
|
1159
|
+
});
|
|
1160
|
+
|
|
1161
|
+
const { answerModel: _answerModel, auth: _auth, ...extractionOptions } = { ...options, mode };
|
|
1162
|
+
const { prompt: _prompt, ...answerExtractionOptions } = extractionOptions;
|
|
1163
|
+
const requestOptions = {
|
|
1164
|
+
...(mode === "answer" ? answerExtractionOptions : extractionOptions),
|
|
1165
|
+
...(authFetchProfile ? { authFetchProfile } : {}),
|
|
1166
|
+
...(call.browserCookieConsent ? { browserCookieConsent: call.browserCookieConsent } : {}),
|
|
1167
|
+
};
|
|
1168
|
+
const fetchResults = await fetchAllContent(urlList, signal, fetchOptions(requestOptions, options.proxy));
|
|
1169
|
+
// Image-as-payload results (direct images, video frames) set mimeType and/or frames. Answer mode sends
|
|
1170
|
+
// them to the answer model; extract rejects them. A text result that merely attaches a thumbnail
|
|
1171
|
+
// (YouTube analysis) is answered as text.
|
|
1172
|
+
const textResults = mode === "extract"
|
|
1173
|
+
? fetchResults.map(result => !result.error && (result.mimeType?.startsWith("image/") || result.frames?.length)
|
|
1174
|
+
? { ...result, error: "Field extraction requires textual fetched content" }
|
|
1175
|
+
: result)
|
|
1176
|
+
: fetchResults;
|
|
1177
|
+
const presentedResults = mode === "answer"
|
|
1178
|
+
? await Promise.all(textResults.map(async result => {
|
|
1179
|
+
if (result.error) return result;
|
|
1180
|
+
try {
|
|
1181
|
+
if (!host.answerFromPage) throw new Error("this host cannot answer from fetched pages");
|
|
1182
|
+
const images = result.frames?.length
|
|
1183
|
+
? result.frames.map(frame => ({ data: frame.data, mimeType: frame.mimeType, label: `Frame at ${frame.timestamp}` }))
|
|
1184
|
+
: result.mimeType?.startsWith("image/") && result.thumbnail
|
|
1185
|
+
? [{ ...result.thumbnail, label: result.title }]
|
|
1186
|
+
: undefined;
|
|
1187
|
+
const answer = await host.answerFromPage({
|
|
1188
|
+
question: options.prompt!,
|
|
1189
|
+
pageText: result.content,
|
|
1190
|
+
sourceUrl: result.url,
|
|
1191
|
+
...(options.answerModel ? { model: options.answerModel } : {}),
|
|
1192
|
+
...(images ? { images } : {}),
|
|
1193
|
+
}, ctx, signal);
|
|
1194
|
+
if (answer.usage) answerUsages.push(answer.usage);
|
|
1195
|
+
if (!images) return { ...result, content: answer.text };
|
|
1196
|
+
// The answer replaces the images; the agent does not also receive them.
|
|
1197
|
+
const { frames: _frames, thumbnail: _thumbnail, ...rest } = result;
|
|
1198
|
+
return { ...rest, content: answer.text };
|
|
1199
|
+
} catch (err) {
|
|
1200
|
+
return { ...result, error: `Page answer failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
1201
|
+
}
|
|
1202
|
+
}))
|
|
1203
|
+
: textResults;
|
|
1204
|
+
const extractLimit = pLimit(3);
|
|
1205
|
+
const extractions = extractFields
|
|
1206
|
+
? await Promise.all(presentedResults.map(result => result.error ? undefined : extractLimit(() => extractPageFields(result.content, extractFields!, { modelRegistry: ctx?.modelRegistry }, signal))))
|
|
1207
|
+
: undefined;
|
|
1208
|
+
const successful = presentedResults.filter((r) => !r.error).length;
|
|
1209
|
+
const totalChars = presentedResults.reduce((sum, r) => sum + r.content.length, 0);
|
|
1210
|
+
|
|
1211
|
+
const responseId = generateId();
|
|
1212
|
+
const data = {
|
|
1213
|
+
id: responseId,
|
|
1214
|
+
type: "fetch",
|
|
1215
|
+
timestamp: Date.now(),
|
|
1216
|
+
urls: stripThumbnails(fetchResults),
|
|
1217
|
+
} satisfies FetchedContentData;
|
|
1218
|
+
const storedContent = storeFetchResult(responseId, data, authFetchProfile);
|
|
1219
|
+
const structuredContent = fetchStructuredContent(storedContent ? responseId : null, presentedResults);
|
|
1220
|
+
|
|
1221
|
+
if (extractions) {
|
|
1222
|
+
structuredContent.urls.forEach((entry, index) => {
|
|
1223
|
+
if (extractions[index]) entry.extraction = extractions[index];
|
|
1224
|
+
});
|
|
1225
|
+
let output = "## Extracted fields\n";
|
|
1226
|
+
presentedResults.forEach((result, index) => {
|
|
1227
|
+
output += `\n### ${result.title || result.url}\n`;
|
|
1228
|
+
output += result.error ? `Error: ${result.error}\n` : formatPageExtraction(extractions[index]!);
|
|
1229
|
+
});
|
|
1230
|
+
const outputLimit = getMaxInlineContentChars();
|
|
1231
|
+
if (output.length > outputLimit) output = `${output.slice(0, outputLimit)}\n\n[Results cut at ${outputLimit} characters; ask for fewer fields or URLs.]\n`;
|
|
1232
|
+
// Extract rejects auth, so the pages are always stored.
|
|
1233
|
+
const anyUncertain = extractions.some((extraction) => extraction && "fields" in extraction && Object.values(extraction.fields).some((field) => field.status === "uncertain"));
|
|
1234
|
+
output += getSearchContentEnabled
|
|
1235
|
+
? `\n---\nThe fetched pages are stored as responseId "${responseId}". Use ${toolNames.getSearchContent}({ responseId: "${responseId}", urlIndex: 0 }) to read the first one; urlIndex follows the order above.${anyUncertain ? " To check an uncertain value, add findText with its guess." : ""}`
|
|
1236
|
+
: "\n---\nContent retrieval is not registered.";
|
|
1237
|
+
return {
|
|
1238
|
+
// A page that fetched but could not be extracted still counts as fetched: its content is stored.
|
|
1239
|
+
...(successful === 0 ? { isError: true } : {}),
|
|
1240
|
+
content: [{ type: "text", text: output }],
|
|
1241
|
+
structuredContent,
|
|
1242
|
+
details: {
|
|
1243
|
+
urls: urlList,
|
|
1244
|
+
urlCount: urlList.length,
|
|
1245
|
+
successful,
|
|
1246
|
+
mode,
|
|
1247
|
+
responseId,
|
|
1248
|
+
// The TUI summarizes a single URL from these, as for the other modes.
|
|
1249
|
+
...(urlList.length === 1 ? { title: presentedResults[0].title, totalChars: presentedResults[0].content.length, ...(presentedResults[0].error ? { error: presentedResults[0].error } : {}) } : {}),
|
|
1250
|
+
extractions: presentedResults.map((result, index) => ({ url: result.url, ...(result.error ? { error: result.error } : extractions[index]) })),
|
|
1251
|
+
},
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
if (urlList.length === 1) {
|
|
1256
|
+
const result = presentedResults[0];
|
|
1257
|
+
if (result.error) {
|
|
1258
|
+
return {
|
|
1259
|
+
isError: true,
|
|
1260
|
+
content: [{ type: "text", text: `Error: ${result.error}` }],
|
|
1261
|
+
structuredContent,
|
|
1262
|
+
details: { urls: urlList, urlCount: 1, successful: 0, error: result.error, ...(storedContent ? { responseId } : {}), prompt: params.prompt, timestamp: params.timestamp, frames: params.frames },
|
|
1263
|
+
};
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
const fullLength = result.content.length;
|
|
1267
|
+
const slice = initialContentSlice(result.content, getMaxInlineContentChars());
|
|
1268
|
+
const truncated = slice.endOffset < fullLength;
|
|
1269
|
+
let output = slice.text;
|
|
1270
|
+
|
|
1271
|
+
if (truncated) {
|
|
1272
|
+
output += `\n\n---\nShowing ${slice.endOffset} of ${fullLength} chars, ${slice.shownBytes} of ${slice.totalBytes} bytes, and ${slice.shownLines} of ${slice.totalLines} lines. `;
|
|
1273
|
+
if (mode === "answer") output += "Stored content is the original source, not the remaining answer. ";
|
|
1274
|
+
output += storedContent
|
|
1275
|
+
? getSearchContentEnabled
|
|
1276
|
+
? mode === "answer"
|
|
1277
|
+
? `Use ${toolNames.getSearchContent}({ responseId: "${responseId}", urlIndex: 0, offset: 0 }) to read the original source from the beginning.`
|
|
1278
|
+
: `Use ${toolNames.getSearchContent}({ responseId: "${responseId}", urlIndex: 0, offset: ${slice.endOffset} }) for the next slice.`
|
|
1279
|
+
: "Content retrieval is not registered."
|
|
1280
|
+
: "Authenticated fetch cache is off; repeat the fetch to read more.";
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
const content: WebToolContent[] = [];
|
|
1284
|
+
if (result.frames?.length) {
|
|
1285
|
+
for (const frame of result.frames) {
|
|
1286
|
+
content.push({ type: "image", data: frame.data, mimeType: frame.mimeType });
|
|
1287
|
+
content.push({ type: "text", text: `Frame at ${frame.timestamp}` });
|
|
1288
|
+
}
|
|
1289
|
+
} else if (result.thumbnail) {
|
|
1290
|
+
content.push({ type: "image", data: result.thumbnail.data, mimeType: result.thumbnail.mimeType });
|
|
1291
|
+
}
|
|
1292
|
+
content.push({ type: "text", text: output });
|
|
1293
|
+
if (!truncated && storedContent && getSearchContentEnabled) {
|
|
1294
|
+
const storedLabel = mode === "answer" ? "Original source content" : "Full content";
|
|
1295
|
+
content.push({
|
|
1296
|
+
type: "text",
|
|
1297
|
+
text: `\n---\n${storedLabel} is stored as responseId "${responseId}". Use ${toolNames.getSearchContent}({ responseId: "${responseId}", urlIndex: 0, offset: 0 }) to retrieve it.`,
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
const imageCount = (result.frames?.length ?? 0) + (result.thumbnail ? 1 : 0);
|
|
1302
|
+
return {
|
|
1303
|
+
content,
|
|
1304
|
+
structuredContent,
|
|
1305
|
+
details: {
|
|
1306
|
+
urls: urlList,
|
|
1307
|
+
urlCount: 1,
|
|
1308
|
+
successful: 1,
|
|
1309
|
+
totalChars: fullLength,
|
|
1310
|
+
title: result.title,
|
|
1311
|
+
...(storedContent ? { responseId } : {}),
|
|
1312
|
+
truncated,
|
|
1313
|
+
hasImage: imageCount > 0,
|
|
1314
|
+
imageCount,
|
|
1315
|
+
prompt: params.prompt,
|
|
1316
|
+
timestamp: params.timestamp,
|
|
1317
|
+
frames: params.frames,
|
|
1318
|
+
duration: result.duration,
|
|
1319
|
+
mode,
|
|
1320
|
+
mimeType: result.mimeType,
|
|
1321
|
+
status: result.status,
|
|
1322
|
+
totalBytes: slice.totalBytes,
|
|
1323
|
+
totalLines: slice.totalLines,
|
|
1324
|
+
shownBytes: slice.shownBytes,
|
|
1325
|
+
shownLines: slice.shownLines,
|
|
1326
|
+
},
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
// Answers are generated, not stored, so they must be shown here in full up to the output limit.
|
|
1331
|
+
let budget = mode === "answer" ? getMaxInlineContentChars() : 0;
|
|
1332
|
+
let output = mode === "answer" ? "## Page answers\n" : "## Fetched URLs\n\n";
|
|
1333
|
+
for (const { url, title, content, error } of presentedResults) {
|
|
1334
|
+
if (mode !== "answer") {
|
|
1335
|
+
output += error ? `- ${url}: Error - ${error}\n` : `- ${title || url} (${content.length} chars)\n`;
|
|
1336
|
+
} else if (error) {
|
|
1337
|
+
output += `\n### ${url}\nError: ${error}\n`;
|
|
1338
|
+
} else {
|
|
1339
|
+
const shown = content.slice(0, budget);
|
|
1340
|
+
budget -= shown.length;
|
|
1341
|
+
const marker = shown.length === content.length
|
|
1342
|
+
? ""
|
|
1343
|
+
: `\n[answer ${shown.length ? "truncated at the output limit;" : "omitted; earlier answers used the output limit,"} fetch fewer URLs per call for complete answers]`;
|
|
1344
|
+
output += `\n### ${title || url}\n${shown}${marker}\n`;
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
const retrievalHint = mode === "answer"
|
|
1348
|
+
? `Stored content is the original source pages, not the answers. Use ${toolNames.getSearchContent}({ responseId: "${responseId}", urlIndex: 0, offset: 0 }) to read the first source; urlIndex follows the order above.`
|
|
1349
|
+
: `Use ${toolNames.getSearchContent}({ responseId: "${responseId}", urlIndex: 0 }) to retrieve bounded content slices.`;
|
|
1350
|
+
output += storedContent
|
|
1351
|
+
? getSearchContentEnabled
|
|
1352
|
+
? `\n---\n${retrievalHint}`
|
|
1353
|
+
: "\n---\nContent retrieval is not registered."
|
|
1354
|
+
: "\n---\nAuthenticated fetch cache is off; repeat the fetch to read content.";
|
|
1355
|
+
|
|
1356
|
+
return {
|
|
1357
|
+
...(successful === 0 ? { isError: true } : {}),
|
|
1358
|
+
content: [{ type: "text", text: output }],
|
|
1359
|
+
structuredContent,
|
|
1360
|
+
details: { urls: urlList, urlCount: urlList.length, successful, totalChars, ...(storedContent ? { responseId } : {}) },
|
|
1361
|
+
};
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
async function getSearchContent(rawParams: RawGetSearchContentParams): Promise<WebToolResult> {
|
|
1366
|
+
const maxInlineContentChars = settings.maxInlineContentChars;
|
|
1367
|
+
const params = normalizeGetSearchContentParams(rawParams);
|
|
1368
|
+
if (params.findMode !== undefined && params.findText === undefined) {
|
|
1369
|
+
return {
|
|
1370
|
+
content: [{ type: "text", text: `findMode ${formatInputValue(params.findMode)} requires findText; provide findText or omit findMode.` }],
|
|
1371
|
+
details: { error: "findMode requires findText" },
|
|
1372
|
+
};
|
|
1373
|
+
}
|
|
1374
|
+
const data = getResult(params.responseId);
|
|
1375
|
+
if (!data) {
|
|
1376
|
+
return {
|
|
1377
|
+
content: [{ type: "text", text: `Error: No stored results for responseId ${formatInputValue(params.responseId)}. Use a responseId returned by ${storedContentSources}.` }],
|
|
1378
|
+
details: { error: "Not found", responseId: params.responseId },
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
if (data.type === "research") {
|
|
1383
|
+
const artifact = getResearchArtifact(params.responseId);
|
|
1384
|
+
if (!artifact) {
|
|
1385
|
+
return {
|
|
1386
|
+
content: [{ type: "text", text: `Error: stored research artifact for responseId ${formatInputValue(params.responseId)} was not found. Use a responseId returned by ${storedContentSources}.` }],
|
|
1387
|
+
details: { error: "Artifact not found", responseId: params.responseId },
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
const serialized = JSON.stringify(artifact, null, 2);
|
|
1391
|
+
if (params.findText !== undefined) {
|
|
1392
|
+
try {
|
|
1393
|
+
const found = findContent(serialized, normalizeFindQueries(params.findText), params.findMode ?? "case-insensitive");
|
|
1394
|
+
const { text, ...findDetails } = found;
|
|
1395
|
+
return {
|
|
1396
|
+
content: [{ type: "text", text }],
|
|
1397
|
+
details: { responseId: artifact.id, type: "research", contentLength: serialized.length, findMode: params.findMode ?? "case-insensitive", ...findDetails },
|
|
1398
|
+
};
|
|
1399
|
+
} catch (err) {
|
|
1400
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
1401
|
+
return {
|
|
1402
|
+
content: [{ type: "text", text: `Unable to find ${formatInputValue(params.findText)} in research artifact for responseId ${formatInputValue(params.responseId)}: ${error}. Check findText and use a supported findMode.` }],
|
|
1403
|
+
details: { error, responseId: params.responseId, type: "research" },
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
const offset = params.offset ?? 0;
|
|
1408
|
+
const limit = params.limit ?? maxInlineContentChars;
|
|
1409
|
+
if (!Number.isInteger(offset) || offset < 0) {
|
|
1410
|
+
return {
|
|
1411
|
+
content: [{ type: "text", text: `Invalid offset: received ${formatInputValue(offset)} for responseId ${formatInputValue(params.responseId)}; offset must be a non-negative integer. Use 0 or a larger integer.` }],
|
|
1412
|
+
details: { error: "Invalid offset", offset },
|
|
1413
|
+
};
|
|
1414
|
+
}
|
|
1415
|
+
if (!Number.isInteger(limit) || limit <= 0 || limit > maxInlineContentChars) {
|
|
1416
|
+
return {
|
|
1417
|
+
content: [{ type: "text", text: `Invalid limit: received ${formatInputValue(limit)} for responseId ${formatInputValue(params.responseId)}; limit must be an integer from 1 to ${maxInlineContentChars}. Use a value in that range.` }],
|
|
1418
|
+
details: { error: "Invalid limit", limit, maxLimit: maxInlineContentChars },
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
if (offset > serialized.length) {
|
|
1422
|
+
return {
|
|
1423
|
+
content: [{ type: "text", text: `Offset ${offset} is out of range for responseId ${formatInputValue(params.responseId)}. Received offset ${offset}; valid range is 0-${serialized.length}. Use an offset within that range.` }],
|
|
1424
|
+
details: { error: "Offset out of range", offset, contentLength: serialized.length },
|
|
1425
|
+
};
|
|
1426
|
+
}
|
|
1427
|
+
const { endOffset, text } = sliceWithContinuation(serialized, offset, limit, maxInlineContentChars, (end) =>
|
|
1428
|
+
`\n\n---\nShowing chars ${offset}-${end} of ${serialized.length}. Use ${toolNames.getSearchContent}({ responseId: "${artifact.id}", offset: ${end}, limit: ${limit} }) for the next slice.`);
|
|
1429
|
+
const hasMore = endOffset < serialized.length;
|
|
1430
|
+
return {
|
|
1431
|
+
content: [{ type: "text", text }],
|
|
1432
|
+
details: { responseId: artifact.id, type: "research", contentLength: serialized.length, offset, limit, returnedChars: endOffset - offset, nextOffset: hasMore ? endOffset : null, truncated: hasMore },
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
if (data.type === "search" && data.queries) {
|
|
1437
|
+
let queryData: QueryResultData | undefined;
|
|
1438
|
+
|
|
1439
|
+
if (params.query !== undefined) {
|
|
1440
|
+
queryData = data.queries.find((q) => q.query === params.query);
|
|
1441
|
+
if (!queryData) {
|
|
1442
|
+
const available = data.queries.map((q) => `"${q.query}"`).join(", ");
|
|
1443
|
+
return {
|
|
1444
|
+
content: [{ type: "text", text: `Query ${formatInputValue(params.query)} was not found for responseId ${formatInputValue(params.responseId)}. Received query=${formatInputValue(params.query)}. Available queries: ${available || "none"}. Use one of the available queries or queryIndex.` }],
|
|
1445
|
+
details: { error: "Query not found" },
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
} else if (params.queryIndex !== undefined) {
|
|
1449
|
+
queryData = data.queries[params.queryIndex];
|
|
1450
|
+
if (!queryData) {
|
|
1451
|
+
const available = data.queries.map((q, i) => `${i}: "${q.query}"`).join(", ");
|
|
1452
|
+
return {
|
|
1453
|
+
content: [{ type: "text", text: `Query index ${formatInputValue(params.queryIndex)} is out of range for responseId ${formatInputValue(params.responseId)}. Received queryIndex=${formatInputValue(params.queryIndex)}; valid indexes are 0-${data.queries.length - 1}. Available queries: ${available || "none"}. Use one of the available indexes.` }],
|
|
1454
|
+
details: { error: "Index out of range" },
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
} else if (data.queries.length === 1) {
|
|
1458
|
+
queryData = data.queries[0];
|
|
1459
|
+
} else if (data.queries.length > 1) {
|
|
1460
|
+
return readAllStoredEntries(params, "queryIndex", "queries", data.queries.map((q) => ({
|
|
1461
|
+
label: `"${q.query}"`,
|
|
1462
|
+
content: q.error ? null : formatFullResults(q),
|
|
1463
|
+
error: q.error,
|
|
1464
|
+
})), maxInlineContentChars);
|
|
1465
|
+
} else {
|
|
1466
|
+
return {
|
|
1467
|
+
content: [{ type: "text", text: `Specify query or queryIndex for responseId ${formatInputValue(params.responseId)}. Available queries: none.` }],
|
|
1468
|
+
details: { error: "No query specified" },
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
if (queryData.error) {
|
|
1473
|
+
return {
|
|
1474
|
+
content: [{ type: "text", text: `Error retrieving query ${formatInputValue(queryData.query)} from responseId ${formatInputValue(params.responseId)}: ${queryData.error}. Check the stored search result and retry with another query or queryIndex if needed.` }],
|
|
1475
|
+
details: { error: queryData.error, query: queryData.query },
|
|
1476
|
+
};
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
const fullResults = formatFullResults(queryData);
|
|
1480
|
+
if (params.findText !== undefined) {
|
|
1481
|
+
try {
|
|
1482
|
+
const found = findContent(fullResults, normalizeFindQueries(params.findText), params.findMode ?? "case-insensitive");
|
|
1483
|
+
const { text, ...findDetails } = found;
|
|
1484
|
+
return {
|
|
1485
|
+
content: [{ type: "text", text }],
|
|
1486
|
+
details: { responseId: params.responseId, query: queryData.query, resultCount: queryData.results.length, contentLength: fullResults.length, findMode: params.findMode ?? "case-insensitive", ...findDetails },
|
|
1487
|
+
};
|
|
1488
|
+
} catch (err) {
|
|
1489
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
1490
|
+
return {
|
|
1491
|
+
content: [{ type: "text", text: `Unable to find ${formatInputValue(params.findText)} in query ${formatInputValue(queryData.query)} for responseId ${formatInputValue(params.responseId)}: ${error}. Check findText and use a supported findMode.` }],
|
|
1492
|
+
details: { error, query: queryData.query },
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
const offset = params.offset ?? 0;
|
|
1498
|
+
const limit = params.limit ?? maxInlineContentChars;
|
|
1499
|
+
if (!Number.isInteger(offset) || offset < 0) {
|
|
1500
|
+
return {
|
|
1501
|
+
content: [{ type: "text", text: `Invalid offset: received ${formatInputValue(offset)} for query ${formatInputValue(queryData.query)}; offset must be a non-negative integer. Use 0 or a larger integer.` }],
|
|
1502
|
+
details: { error: "Invalid offset", offset },
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
if (!Number.isInteger(limit) || limit <= 0 || limit > maxInlineContentChars) {
|
|
1506
|
+
return {
|
|
1507
|
+
content: [{ type: "text", text: `Invalid limit: received ${formatInputValue(limit)} for query ${formatInputValue(queryData.query)}; limit must be an integer from 1 to ${maxInlineContentChars}. Use a value in that range.` }],
|
|
1508
|
+
details: { error: "Invalid limit", limit, maxLimit: maxInlineContentChars },
|
|
1509
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
if (offset > fullResults.length) {
|
|
1512
|
+
return {
|
|
1513
|
+
content: [{ type: "text", text: `Offset ${offset} is out of range for query ${formatInputValue(queryData.query)} in responseId ${formatInputValue(params.responseId)}. Received offset ${offset}; valid range is 0-${fullResults.length}. Use an offset within that range.` }],
|
|
1514
|
+
details: { error: "Offset out of range", offset, contentLength: fullResults.length },
|
|
1515
|
+
};
|
|
1516
|
+
}
|
|
1517
|
+
const queryIndex = data.queries.indexOf(queryData);
|
|
1518
|
+
const { endOffset, text } = sliceWithContinuation(fullResults, offset, limit, maxInlineContentChars, (end) =>
|
|
1519
|
+
`\n\n---\nShowing chars ${offset}-${end} of ${fullResults.length}. Use ${toolNames.getSearchContent}({ responseId: "${params.responseId}", queryIndex: ${queryIndex}, offset: ${end}, limit: ${limit} }) for the next slice.`);
|
|
1520
|
+
const returnedChars = endOffset - offset;
|
|
1521
|
+
const hasMore = endOffset < fullResults.length;
|
|
1522
|
+
return {
|
|
1523
|
+
content: [{ type: "text", text }],
|
|
1524
|
+
details: {
|
|
1525
|
+
responseId: params.responseId,
|
|
1526
|
+
query: queryData.query,
|
|
1527
|
+
resultCount: queryData.results.length,
|
|
1528
|
+
contentLength: fullResults.length,
|
|
1529
|
+
offset,
|
|
1530
|
+
limit,
|
|
1531
|
+
returnedChars,
|
|
1532
|
+
nextOffset: hasMore ? endOffset : null,
|
|
1533
|
+
truncated: hasMore,
|
|
1534
|
+
},
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
if (data.type === "fetch" && data.urls) {
|
|
1539
|
+
let urlData: ExtractedContent | undefined;
|
|
1540
|
+
let selectedUrlIndex = -1;
|
|
1541
|
+
|
|
1542
|
+
if (params.url !== undefined) {
|
|
1543
|
+
selectedUrlIndex = data.urls.findIndex((u) => u.url === params.url);
|
|
1544
|
+
urlData = data.urls[selectedUrlIndex];
|
|
1545
|
+
if (!urlData) {
|
|
1546
|
+
const available = data.urls.map((u) => u.url).join("\n ");
|
|
1547
|
+
return {
|
|
1548
|
+
content: [{ type: "text", text: `URL ${formatInputValue(params.url)} was not found for responseId ${formatInputValue(params.responseId)}. Received url=${formatInputValue(params.url)}. Available URLs:\n ${available || " none"}\nUse one of the available URLs or urlIndex.` }],
|
|
1549
|
+
details: { error: "URL not found" },
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
} else if (params.urlIndex !== undefined) {
|
|
1553
|
+
selectedUrlIndex = params.urlIndex;
|
|
1554
|
+
urlData = data.urls[selectedUrlIndex];
|
|
1555
|
+
if (!urlData) {
|
|
1556
|
+
const available = data.urls.map((u, i) => `${i}: ${u.url}`).join("\n ");
|
|
1557
|
+
return {
|
|
1558
|
+
content: [{ type: "text", text: `URL index ${formatInputValue(params.urlIndex)} is out of range for responseId ${formatInputValue(params.responseId)}. Received urlIndex=${formatInputValue(params.urlIndex)}; valid indexes are 0-${data.urls.length - 1}. Available URLs:\n ${available || " none"}\nUse one of the available indexes.` }],
|
|
1559
|
+
details: { error: "Index out of range" },
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
} else if (data.urls.length === 1) {
|
|
1563
|
+
// Single stored URL: default to it so calls that omit url and urlIndex
|
|
1564
|
+
// (common with findText on single-URL fetches) succeed without a retry.
|
|
1565
|
+
selectedUrlIndex = 0;
|
|
1566
|
+
urlData = data.urls[0];
|
|
1567
|
+
} else if (data.urls.length > 1) {
|
|
1568
|
+
return readAllStoredEntries(params, "urlIndex", "URLs", data.urls.map((u) => ({
|
|
1569
|
+
label: u.title && u.title !== u.url ? `${u.title} — ${u.url}` : u.url,
|
|
1570
|
+
content: u.error ? null : u.content,
|
|
1571
|
+
error: u.error,
|
|
1572
|
+
})), maxInlineContentChars);
|
|
1573
|
+
} else {
|
|
1574
|
+
return {
|
|
1575
|
+
content: [{ type: "text", text: `Specify url or urlIndex for responseId ${formatInputValue(params.responseId)}. Available URLs:\n none` }],
|
|
1576
|
+
details: { error: "No URL specified" },
|
|
1577
|
+
};
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
if (urlData.error) {
|
|
1581
|
+
return {
|
|
1582
|
+
content: [{ type: "text", text: `Error retrieving URL ${formatInputValue(urlData.url)} from responseId ${formatInputValue(params.responseId)}: ${urlData.error}. Check the stored fetch result and retry with another URL or urlIndex if needed.` }],
|
|
1583
|
+
details: { error: urlData.error, url: urlData.url },
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
if (params.findText !== undefined) {
|
|
1588
|
+
try {
|
|
1589
|
+
const found = findContent(urlData.content, normalizeFindQueries(params.findText), params.findMode ?? "case-insensitive");
|
|
1590
|
+
const { text, ...findDetails } = found;
|
|
1591
|
+
return {
|
|
1592
|
+
content: [{ type: "text", text: `# ${urlData.title || urlData.url}\n\n${text}` }],
|
|
1593
|
+
details: { url: urlData.url, title: urlData.title, contentLength: urlData.content.length, findMode: params.findMode ?? "case-insensitive", ...findDetails },
|
|
1594
|
+
};
|
|
1595
|
+
} catch (err) {
|
|
1596
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
1597
|
+
return {
|
|
1598
|
+
content: [{ type: "text", text: `Unable to find ${formatInputValue(params.findText)} in URL ${formatInputValue(urlData.url)} for responseId ${formatInputValue(params.responseId)}: ${error}. Check findText and use a supported findMode.` }],
|
|
1599
|
+
details: { error, url: urlData.url },
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
const offset = params.offset ?? 0;
|
|
1605
|
+
const limit = params.limit ?? maxInlineContentChars;
|
|
1606
|
+
if (!Number.isInteger(offset) || offset < 0) {
|
|
1607
|
+
return {
|
|
1608
|
+
content: [{ type: "text", text: `Invalid offset: received ${formatInputValue(offset)} for URL ${formatInputValue(urlData.url)}; offset must be a non-negative integer. Use 0 or a larger integer.` }],
|
|
1609
|
+
details: { error: "Invalid offset", offset },
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
if (!Number.isInteger(limit) || limit <= 0 || limit > maxInlineContentChars) {
|
|
1613
|
+
return {
|
|
1614
|
+
content: [{ type: "text", text: `Invalid limit: received ${formatInputValue(limit)} for URL ${formatInputValue(urlData.url)}; limit must be an integer from 1 to ${maxInlineContentChars}. Use a value in that range.` }],
|
|
1615
|
+
details: { error: "Invalid limit", limit, maxLimit: maxInlineContentChars },
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
if (offset > urlData.content.length) {
|
|
1619
|
+
return {
|
|
1620
|
+
content: [{ type: "text", text: `Offset ${offset} is out of range for URL ${formatInputValue(urlData.url)} in responseId ${formatInputValue(params.responseId)}. Received offset ${offset}; valid range is 0-${urlData.content.length}. Use an offset within that range.` }],
|
|
1621
|
+
details: { error: "Offset out of range", offset, contentLength: urlData.content.length },
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
const endOffset = pageEnd(urlData.content, offset, Math.min(offset + limit, urlData.content.length));
|
|
1626
|
+
const contentSlice = urlData.content.slice(offset, endOffset);
|
|
1627
|
+
const hasMore = endOffset < urlData.content.length;
|
|
1628
|
+
let text = `# ${urlData.title || urlData.url}\n\n${contentSlice}`;
|
|
1629
|
+
if (hasMore || offset > 0) {
|
|
1630
|
+
text += `\n\n---\nShowing chars ${offset}-${endOffset} of ${urlData.content.length}.`;
|
|
1631
|
+
if (hasMore) {
|
|
1632
|
+
text += ` Use ${toolNames.getSearchContent}({ responseId: "${params.responseId}", urlIndex: ${selectedUrlIndex}, offset: ${endOffset}, limit: ${limit} }) for the next slice.`;
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
return {
|
|
1637
|
+
content: [{ type: "text", text }],
|
|
1638
|
+
details: {
|
|
1639
|
+
url: urlData.url,
|
|
1640
|
+
title: urlData.title,
|
|
1641
|
+
contentLength: urlData.content.length,
|
|
1642
|
+
offset,
|
|
1643
|
+
limit,
|
|
1644
|
+
returnedChars: contentSlice.length,
|
|
1645
|
+
nextOffset: hasMore ? endOffset : null,
|
|
1646
|
+
truncated: hasMore,
|
|
1647
|
+
},
|
|
1648
|
+
};
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
return {
|
|
1652
|
+
content: [{ type: "text", text: `Invalid stored data for responseId ${formatInputValue(params.responseId)}: received type ${formatInputValue(data.type)}. Use a responseId returned by ${storedContentSources}.` }],
|
|
1653
|
+
details: { error: "Invalid data" },
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
return {
|
|
1658
|
+
webSearch,
|
|
1659
|
+
fetchContent,
|
|
1660
|
+
getSearchContent,
|
|
1661
|
+
sourceCheck,
|
|
1662
|
+
buildSearchReturn,
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
const MAX_STORED_RESULTS = 50;
|
|
1667
|
+
const STANDALONE_DIRECT_IMAGE_ERROR = "Direct image fetch is not supported over MCP; fetch_content returns text there. Fetch images from the Pi extension instead.";
|
|
1668
|
+
|
|
1669
|
+
export interface StandaloneWebToolCore extends WebToolCore {
|
|
1670
|
+
/** Default names of the tools web-search.json enables; hosts list only these. */
|
|
1671
|
+
enabledToolNames: string[];
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
function standaloneError(error: string): WebToolResult {
|
|
1675
|
+
return { content: [{ type: "text", text: `Error: ${error}` }], details: { error }, isError: true };
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
// A copy of Pi's core/usage-totals.ts combineUsage, which Pi doesn't export, so the totals match Pi's.
|
|
1679
|
+
function combineUsage(first: Usage, second: Usage): Usage {
|
|
1680
|
+
return {
|
|
1681
|
+
input: first.input + second.input,
|
|
1682
|
+
output: first.output + second.output,
|
|
1683
|
+
cacheRead: first.cacheRead + second.cacheRead,
|
|
1684
|
+
cacheWrite: first.cacheWrite + second.cacheWrite,
|
|
1685
|
+
...(first.cacheWrite1h !== undefined || second.cacheWrite1h !== undefined
|
|
1686
|
+
? { cacheWrite1h: (first.cacheWrite1h ?? 0) + (second.cacheWrite1h ?? 0) }
|
|
1687
|
+
: {}),
|
|
1688
|
+
...(first.reasoning !== undefined || second.reasoning !== undefined
|
|
1689
|
+
? { reasoning: (first.reasoning ?? 0) + (second.reasoning ?? 0) }
|
|
1690
|
+
: {}),
|
|
1691
|
+
totalTokens: first.totalTokens + second.totalTokens,
|
|
1692
|
+
cost: {
|
|
1693
|
+
input: first.cost.input + second.cost.input,
|
|
1694
|
+
output: first.cost.output + second.cost.output,
|
|
1695
|
+
cacheRead: first.cost.cacheRead + second.cost.cacheRead,
|
|
1696
|
+
cacheWrite: first.cost.cacheWrite + second.cost.cacheWrite,
|
|
1697
|
+
total: first.cost.total + second.cost.total,
|
|
1698
|
+
},
|
|
1699
|
+
};
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
// Marks a final tool result as failed (`isError: true`) for both the Pi tools
|
|
1703
|
+
// and the MCP server. A result with details.error is an error, and so is a call
|
|
1704
|
+
// where nothing requested succeeded: every web_search query, every fetch_content
|
|
1705
|
+
// URL, or every source_check search failed. A working search with zero matches
|
|
1706
|
+
// is not.
|
|
1707
|
+
export function markToolError<T extends Omit<WebToolResult, "structuredContent">>(result: T): T {
|
|
1708
|
+
const { error, queryCount, successfulQueries, urlCount, successful, searchCount, artifact } = result.details;
|
|
1709
|
+
const nothingSucceeded = (typeof queryCount === "number" && queryCount > 0 && successfulQueries === 0)
|
|
1710
|
+
|| (typeof urlCount === "number" && urlCount > 0 && successful === 0)
|
|
1711
|
+
|| (typeof searchCount === "number" && searchCount > 0 && (artifact as ResearchArtifact).errors?.length === searchCount);
|
|
1712
|
+
return error !== undefined || nothingSucceeded ? { ...result, isError: true } : result;
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
// Explicit requests for providers that need Pi's model registry or login state
|
|
1716
|
+
// fail here instead of silently falling back. Automatic selection already skips
|
|
1717
|
+
// them without a Pi context and picks among the providers usable here.
|
|
1718
|
+
async function standaloneProviderRejection(requested: unknown): Promise<string | undefined> {
|
|
1719
|
+
let selection: SearchProviderSelection;
|
|
1720
|
+
try {
|
|
1721
|
+
selection = resolveRequestedProvider(requested);
|
|
1722
|
+
} catch {
|
|
1723
|
+
return undefined; // The core reports the same validation error.
|
|
1724
|
+
}
|
|
1725
|
+
const explicit: string[] = Array.isArray(selection) ? selection : [selection];
|
|
1726
|
+
if (explicit.includes("kimi")) {
|
|
1727
|
+
return "Kimi search is not supported over MCP: it authenticates only through Pi's /login kimi-coding. Choose another provider, or search from Pi.";
|
|
1728
|
+
}
|
|
1729
|
+
if (explicit.includes("openai")) {
|
|
1730
|
+
let available: boolean;
|
|
1731
|
+
try {
|
|
1732
|
+
available = await isOpenAISearchAvailable();
|
|
1733
|
+
} catch {
|
|
1734
|
+
return undefined; // The core reports the same configuration error.
|
|
1735
|
+
}
|
|
1736
|
+
if (!available) {
|
|
1737
|
+
return `OpenAI search over MCP needs an API key: set openaiApiKey in ${WEB_SEARCH_CONFIG_PATH} or OPENAI_API_KEY. ChatGPT/Codex sign-in, openaiUseProviderBaseUrl, and Pi model credentials work only inside Pi.`;
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
return undefined;
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
function standaloneFetchRejection(params: FetchContentCallParams, fetchModes: FetchModeConfig): string | undefined {
|
|
1744
|
+
// The policy names the real reason; the MCP limits below would only say "not supported here".
|
|
1745
|
+
if (MODEL_FETCH_MODES.includes(params.mode as FetchMode) && getRetrievalOnlyPolicy().enabled) {
|
|
1746
|
+
return retrievalOnlyError(`Fetch mode "${params.mode}"`).message;
|
|
1747
|
+
}
|
|
1748
|
+
if (params.mode === "answer") {
|
|
1749
|
+
return "fetch_content mode \"answer\" is not supported over MCP: page answers use Pi's models. Use mode \"readable\" or \"raw\".";
|
|
1750
|
+
}
|
|
1751
|
+
if (params.mode === undefined && fetchModes.defaultMode === "answer") {
|
|
1752
|
+
return `fetch.defaultMode in ${WEB_SEARCH_CONFIG_PATH} is "answer", which is not supported over MCP. Pass mode "readable" or "raw".`;
|
|
1753
|
+
}
|
|
1754
|
+
return undefined;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/** Core for hosts without Pi: no extension context, curator, or summaries; results
|
|
1758
|
+
* live in a bounded in-memory store; includeContent waits for the page fetch. */
|
|
1759
|
+
export function createStandaloneWebToolCore(): StandaloneWebToolCore {
|
|
1760
|
+
const config = loadConfig();
|
|
1761
|
+
getRetrievalOnlyPolicy(config); // Fixes the policy at load, and fails here when it is misconfigured.
|
|
1762
|
+
const settings: WebToolCoreSettings = {
|
|
1763
|
+
toolNames: { ...DEFAULT_TOOL_NAMES },
|
|
1764
|
+
enabledTools: {
|
|
1765
|
+
webSearch: isToolEnabled(config, "webSearch"),
|
|
1766
|
+
sourceCheck: isToolEnabled(config, "sourceCheck"),
|
|
1767
|
+
fetchContent: isToolEnabled(config, "fetchContent"),
|
|
1768
|
+
getSearchContent: isToolEnabled(config, "getSearchContent"),
|
|
1769
|
+
},
|
|
1770
|
+
maxInlineContentChars: getMaxInlineContentChars(config),
|
|
1771
|
+
fetchModes: resolveFetchModeConfig(config),
|
|
1772
|
+
};
|
|
1773
|
+
const storedIds: string[] = [];
|
|
1774
|
+
const remember = (id: string) => {
|
|
1775
|
+
storedIds.push(id);
|
|
1776
|
+
while (storedIds.length > MAX_STORED_RESULTS) deleteResult(storedIds.shift()!);
|
|
1777
|
+
};
|
|
1778
|
+
const core = createWebToolCore({
|
|
1779
|
+
settings,
|
|
1780
|
+
storeFetchedContent(id, data) {
|
|
1781
|
+
storeResult(id, data);
|
|
1782
|
+
remember(id);
|
|
1783
|
+
},
|
|
1784
|
+
publishResult(data) {
|
|
1785
|
+
remember(data.id);
|
|
1786
|
+
},
|
|
1787
|
+
extractOptions: { rejectDirectImages: STANDALONE_DIRECT_IMAGE_ERROR },
|
|
1788
|
+
});
|
|
1789
|
+
|
|
1790
|
+
return {
|
|
1791
|
+
enabledToolNames: (Object.keys(DEFAULT_TOOL_NAMES) as (keyof ToolNames)[])
|
|
1792
|
+
.filter((key) => settings.enabledTools[key])
|
|
1793
|
+
.map((key) => DEFAULT_TOOL_NAMES[key]),
|
|
1794
|
+
async webSearch(params, signal) {
|
|
1795
|
+
const rejection = await standaloneProviderRejection(params.provider);
|
|
1796
|
+
return rejection ? standaloneError(rejection) : markToolError(await core.webSearch(params, signal));
|
|
1797
|
+
},
|
|
1798
|
+
async fetchContent(params, signal) {
|
|
1799
|
+
const rejection = standaloneFetchRejection(params, settings.fetchModes);
|
|
1800
|
+
return rejection ? standaloneError(rejection) : markToolError(await core.fetchContent(params, signal));
|
|
1801
|
+
},
|
|
1802
|
+
async getSearchContent(params, signal) {
|
|
1803
|
+
return markToolError(await core.getSearchContent(params, signal));
|
|
1804
|
+
},
|
|
1805
|
+
async sourceCheck(params, signal) {
|
|
1806
|
+
const rejection = await standaloneProviderRejection(params.provider);
|
|
1807
|
+
return rejection ? standaloneError(rejection) : markToolError(await core.sourceCheck(params, signal));
|
|
1808
|
+
},
|
|
1809
|
+
};
|
|
1810
|
+
}
|