@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/index.ts
ADDED
|
@@ -0,0 +1,2819 @@
|
|
|
1
|
+
import type { AgentToolResult, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Box, Text, truncateToWidth, type KeyId } from "@earendil-works/pi-tui";
|
|
3
|
+
import { Type, type TOptional, type TString, type TUnsafe } from "typebox";
|
|
4
|
+
import type { ExtractedContent } from "./extract.ts";
|
|
5
|
+
import { normalizeFetchContentParams } from "./fetch-params.ts";
|
|
6
|
+
import { answerFromPage } from "./page-query.ts";
|
|
7
|
+
import { rewriteSearchQuery } from "./query-rewrite.ts";
|
|
8
|
+
import { createPiSessionResults } from "./pi-session-results.ts";
|
|
9
|
+
import { ALL_SEARCH_PROVIDERS, getAllowedSearchProviders, getAvailableCustomSearchProviders, getConfiguredSearchRouting, parseProviderArgument, RESOLVED_SEARCH_PROVIDERS, search, type AttributedSearchResponse, type BuiltinSearchProvider, type ProviderAvailability, type SearchProvider, type SearchProviderSelection, type ResolvedSearchProvider } from "./gemini-search.ts";
|
|
10
|
+
export type { ProviderAvailability } from "./gemini-search.ts";
|
|
11
|
+
import { formatSeconds, getWebSearchConfigDir, resolveCuratorNetworkConfig, runWithProxy } from "./utils.ts";
|
|
12
|
+
import { getRetrievalOnlyPolicy, RETRIEVAL_ONLY_DESCRIPTION_SUFFIX, retrievalOnlyError } from "./retrieval-only.ts";
|
|
13
|
+
import {
|
|
14
|
+
deleteHeldResult,
|
|
15
|
+
generateId,
|
|
16
|
+
getAllResults,
|
|
17
|
+
storeFetchedContentResult,
|
|
18
|
+
type QueryResultData,
|
|
19
|
+
type StoredSearchData,
|
|
20
|
+
} from "./storage.ts";
|
|
21
|
+
import { activityMonitor, type ActivityEntry } from "./activity.ts";
|
|
22
|
+
import type { CuratorSearchEntry, CuratorServerHandle, IndexedCuratorSearchEntry } from "./curator-server.ts";
|
|
23
|
+
import {
|
|
24
|
+
buildDeterministicSummary,
|
|
25
|
+
generateSummaryDraft,
|
|
26
|
+
SUMMARY_GENERATION_DEADLINE_MS,
|
|
27
|
+
type SummaryGenerationContext,
|
|
28
|
+
type SummaryMeta,
|
|
29
|
+
} from "./summary-review.ts";
|
|
30
|
+
import { randomUUID } from "node:crypto";
|
|
31
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
32
|
+
import { createRequire } from "node:module";
|
|
33
|
+
import { platform } from "node:os";
|
|
34
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
35
|
+
import { join } from "node:path";
|
|
36
|
+
import { isPerplexityAvailable } from "./perplexity.ts";
|
|
37
|
+
import { isExaAvailable } from "./exa.ts";
|
|
38
|
+
import { isGeminiApiAvailable } from "./gemini-api.ts";
|
|
39
|
+
import { browserCookieAccessHint, getActiveGoogleEmail, getGeminiWebAvailabilityDiagnostic, getGeminiWebAvailabilityDiagnosticDetails, isGeminiWebAvailable } from "./gemini-web.ts";
|
|
40
|
+
import { clearGeminiWebConfigCache, getBrowserCookieSelectionFromConfig, grantBrowserCookieAccessForSession, isBrowserCookieAccessAllowed, revokeBrowserCookieAccessForSession, type BrowserCookieConsent } from "./gemini-web-config.ts";
|
|
41
|
+
import { detectBrowserProfiles } from "./chrome-cookies.ts";
|
|
42
|
+
import { isBraveAvailable } from "./brave.ts";
|
|
43
|
+
import { isCurrentModelHostedSearchEligible, isOpenAISearchAvailable, isOpenAISubscriptionModelSelected } from "./openai-search.ts";
|
|
44
|
+
import { isParallelAvailable } from "./parallel.ts";
|
|
45
|
+
import { isParallelMcpAvailable } from "./parallel-mcp.ts";
|
|
46
|
+
import { parseStringifiedArrays } from "./tool-arguments.ts";
|
|
47
|
+
import { isTinyFishAvailable } from "./tinyfish.ts";
|
|
48
|
+
import { isSearchinfinityAvailable } from "./searchinfinity.ts";
|
|
49
|
+
import { isQueritAvailable } from "./querit.ts";
|
|
50
|
+
import { isTavilyAvailable } from "./tavily.ts";
|
|
51
|
+
import { isTabstackAvailable } from "./tabstack.ts";
|
|
52
|
+
import { isYouAvailable } from "./you.ts";
|
|
53
|
+
import { isFirecrawlAvailable } from "./firecrawl.ts";
|
|
54
|
+
import { isJinaSearchAvailable } from "./jina-search.ts";
|
|
55
|
+
import { isKagiAvailable } from "./kagi.ts";
|
|
56
|
+
import { isBochaAvailable } from "./bocha.ts";
|
|
57
|
+
import { isOllamaAvailable } from "./ollama.ts";
|
|
58
|
+
import { isSearXNGAvailable } from "./searxng.ts";
|
|
59
|
+
import { isDegoogAvailable } from "./degoog.ts";
|
|
60
|
+
import { isDuckDuckGoAvailable } from "./duckduckgo.ts";
|
|
61
|
+
import { isAnySearchAvailable } from "./anysearch.ts";
|
|
62
|
+
import { isXaiSearchAvailable } from "./xai-search.ts";
|
|
63
|
+
import { isMistralAvailable } from "./mistral-search.ts";
|
|
64
|
+
import { isKimiSearchAvailable } from "./kimi-search.ts";
|
|
65
|
+
import { isKeenableAvailable } from "./keenable.ts";
|
|
66
|
+
import { isCeramicAvailable } from "./ceramic.ts";
|
|
67
|
+
import { isLinkupAvailable } from "./linkup.ts";
|
|
68
|
+
import { isNineRouterAvailable } from "./ninerouter.ts";
|
|
69
|
+
import { isCloudflareSearchAvailable } from "./cloudflare-search.ts";
|
|
70
|
+
import { isDeepSeekAvailable } from "./deepseek.ts";
|
|
71
|
+
import { isBaizhiAvailable } from "./baizhi.ts";
|
|
72
|
+
import { isZaiAvailable } from "./zai.ts";
|
|
73
|
+
import { isValyuAvailable } from "./valyu.ts";
|
|
74
|
+
import { buildSearchErrorPlan, type SearchErrorDetails, type SearchErrorPlan } from "./render-search-error.ts";
|
|
75
|
+
import { findModelWithProviderRouting, isModelInScope, resolveHelperModelSelector } from "./summary-model-scope.ts";
|
|
76
|
+
import { registerCuratorRunLifecycle, resolveWebSearchWorkflow, type WebSearchWorkflow } from "./curator-run.ts";
|
|
77
|
+
import { registerWebToolActivation } from "./tool-activation.ts";
|
|
78
|
+
import { showUpgradeNotice } from "./upgrade-notice.ts";
|
|
79
|
+
import {
|
|
80
|
+
createWebToolCore,
|
|
81
|
+
DEFAULT_TOOL_NAMES,
|
|
82
|
+
expandQueryString,
|
|
83
|
+
fetchAllContent,
|
|
84
|
+
fetchUncoveredContent,
|
|
85
|
+
getMaxInlineContentChars,
|
|
86
|
+
isToolEnabled,
|
|
87
|
+
loadConfig,
|
|
88
|
+
markToolError,
|
|
89
|
+
normalizeProviderInput,
|
|
90
|
+
normalizeQueryList,
|
|
91
|
+
normalizeRecencyFilter,
|
|
92
|
+
parseConfigRoot,
|
|
93
|
+
registeredFetchToolNames,
|
|
94
|
+
resolveFetchModeConfig,
|
|
95
|
+
resolveRequestedProvider,
|
|
96
|
+
runSearchQueries,
|
|
97
|
+
storedContentSourceNames,
|
|
98
|
+
stripThumbnails,
|
|
99
|
+
toCuratorProvider,
|
|
100
|
+
WEB_SEARCH_CONFIG_PATH,
|
|
101
|
+
withRegisteredFetchOptions,
|
|
102
|
+
type FetchedContentData,
|
|
103
|
+
type FetchMode,
|
|
104
|
+
type SearchReturnOptions,
|
|
105
|
+
type SummaryWorkflow,
|
|
106
|
+
type ToolNames,
|
|
107
|
+
type WebSearchCallOptions,
|
|
108
|
+
type WebSearchConfig,
|
|
109
|
+
} from "./web-tool-core.ts";
|
|
110
|
+
|
|
111
|
+
// Match pi-ai's StringEnum without loading its compat barrel during registration.
|
|
112
|
+
function StringEnum<T extends string[]>(values: T, options?: { description?: string; default?: T[number] }) {
|
|
113
|
+
return Type.Unsafe<T[number]>({
|
|
114
|
+
type: "string",
|
|
115
|
+
enum: values,
|
|
116
|
+
...(options?.description && { description: options.description }),
|
|
117
|
+
...(options?.default && { default: options.default }),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
type ExtensionTheme = ExtensionContext["ui"]["theme"];
|
|
122
|
+
|
|
123
|
+
// structuredContent shapes that codemode scripts receive (web-tool-contract.ts),
|
|
124
|
+
// on success and on isError results.
|
|
125
|
+
const nullableString = (description: string) => Type.Union([Type.String(), Type.Null()], { description });
|
|
126
|
+
const webSearchOutputSchema = Type.Object({
|
|
127
|
+
responseId: Type.String({ description: "Id of the stored search results" }),
|
|
128
|
+
fetchId: nullableString("Stored page content id when includeContent fetched or started fetching content, else null"),
|
|
129
|
+
queries: Type.Array(Type.Object({
|
|
130
|
+
query: Type.String(),
|
|
131
|
+
answer: Type.String({ description: "Provider answer text, empty when the provider returned only results" }),
|
|
132
|
+
error: nullableString("Why this query failed, null on success"),
|
|
133
|
+
provider: Type.Optional(Type.String()),
|
|
134
|
+
providers: Type.Optional(Type.Array(Type.String())),
|
|
135
|
+
results: Type.Array(Type.Object({ title: Type.String(), url: Type.String(), snippet: Type.String() })),
|
|
136
|
+
})),
|
|
137
|
+
});
|
|
138
|
+
const fetchContentOutputSchema = Type.Object({
|
|
139
|
+
responseId: nullableString("Id of the stored content, null when nothing was stored"),
|
|
140
|
+
urls: Type.Array(Type.Object({
|
|
141
|
+
url: Type.String(),
|
|
142
|
+
title: Type.String(),
|
|
143
|
+
content: Type.String({ description: "Full extracted content, not limited by the inline character cap" }),
|
|
144
|
+
error: nullableString("Why this URL failed, null on success"),
|
|
145
|
+
mimeType: Type.Optional(Type.String()),
|
|
146
|
+
status: Type.Optional(Type.Number()),
|
|
147
|
+
duration: Type.Optional(Type.Number()),
|
|
148
|
+
extraction: Type.Optional(Type.Union([
|
|
149
|
+
Type.Object({
|
|
150
|
+
fields: Type.Record(Type.String(), Type.Object({
|
|
151
|
+
status: Type.Union([Type.Literal("extracted"), Type.Literal("uncertain"), Type.Literal("null")], { description: "null means not on the page" }),
|
|
152
|
+
value: Type.Optional(Type.Unknown({ description: "Typed value when extracted" })),
|
|
153
|
+
guess: Type.Optional(Type.Unknown({ description: "Unconfirmed value when uncertain" })),
|
|
154
|
+
confidence: Type.Optional(Type.Number()),
|
|
155
|
+
line: Type.Optional(Type.String({ description: "Page line the text or number value was found on" })),
|
|
156
|
+
notFound: Type.Optional(Type.Boolean({ description: "Uncertain because the text is not on the page" })),
|
|
157
|
+
})),
|
|
158
|
+
cut: Type.Boolean({ description: "Only the first part of the page was read" }),
|
|
159
|
+
}),
|
|
160
|
+
Type.Object({ error: Type.String({ description: "Why extraction failed for this fetched page" }) }),
|
|
161
|
+
], { description: "Extract mode only, for each fetched URL" })),
|
|
162
|
+
})),
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
/** Shared collapsed/expanded renderer for an error/cancel plan produced by
|
|
166
|
+
* buildSearchErrorPlan(). Used by every tool renderResult's error branch so
|
|
167
|
+
* Ctrl+O (app.tools.expand) reveals diagnostics instead of a dead-end single line. */
|
|
168
|
+
function renderSearchErrorPlan(plan: SearchErrorPlan, expanded: boolean, theme: ExtensionTheme) {
|
|
169
|
+
if (expanded) {
|
|
170
|
+
return new Text(plan.expanded.map((l, i) => i === 0 ? theme.fg("error", l) : theme.fg("toolOutput", l)).join("\n"), 0, 0);
|
|
171
|
+
}
|
|
172
|
+
const box = new Box(1, 0, (t) => theme.bg("toolErrorBg", t));
|
|
173
|
+
box.addChild(new Text(theme.fg("error", plan.expanded[0]), 0, 0));
|
|
174
|
+
for (const line of plan.collapsed) {
|
|
175
|
+
box.addChild(new Text(theme.fg("dim", line), 0, 0));
|
|
176
|
+
}
|
|
177
|
+
if (plan.expandHint) {
|
|
178
|
+
box.addChild(new Text(theme.fg("muted", plan.expandHint), 0, 0));
|
|
179
|
+
}
|
|
180
|
+
return box;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
type CuratorWorkflow = "summary-review";
|
|
184
|
+
export type CuratorProvider = SearchProvider;
|
|
185
|
+
|
|
186
|
+
interface CuratorBootstrap {
|
|
187
|
+
availableProviders: ProviderAvailability;
|
|
188
|
+
defaultProvider: SearchProvider;
|
|
189
|
+
timeoutSeconds: number;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function saveConfig(updates: Partial<WebSearchConfig>): void {
|
|
193
|
+
let config: Record<string, unknown> = {};
|
|
194
|
+
if (existsSync(WEB_SEARCH_CONFIG_PATH)) {
|
|
195
|
+
config = parseConfigRoot(readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8"));
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
Object.assign(config, updates);
|
|
199
|
+
const dir = getWebSearchConfigDir();
|
|
200
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
201
|
+
writeFileSync(WEB_SEARCH_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n");
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const TOOL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
205
|
+
const DEFAULT_SHORTCUTS = { curate: "ctrl+shift+s", activity: "ctrl+shift+w" } satisfies Record<string, KeyId>;
|
|
206
|
+
const DEFAULT_CURATOR_TIMEOUT_SECONDS = 20;
|
|
207
|
+
const DEFAULT_REMOTE_CURATOR_TIMEOUT_SECONDS = 60;
|
|
208
|
+
const MAX_CURATOR_TIMEOUT_SECONDS = 600;
|
|
209
|
+
const MAX_SUMMARY_GENERATION_DEADLINE_MS = 600_000;
|
|
210
|
+
const FETCH_MODE_DESCRIPTIONS: Record<FetchMode, string> = {
|
|
211
|
+
readable: "main text as markdown",
|
|
212
|
+
raw: "exact text body, direct HTTP only; no video or clone options",
|
|
213
|
+
answer: "answer a prompt from fetched content only; no auth",
|
|
214
|
+
extract: "read typed values named in fields; no auth",
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
// Keep primary query indexes stable for curator slots, then interleave additional
|
|
218
|
+
// provider entries deterministically instead of assigning by completion order.
|
|
219
|
+
function curatorResultIndex(queryIndex: number, entryIndex: number, queryCount: number): number {
|
|
220
|
+
return entryIndex * queryCount + queryIndex;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function curatorResultIndexCapacity(queryCount: number): number {
|
|
224
|
+
// Custom providers in a provider list add entries beyond the built-in count.
|
|
225
|
+
return queryCount * Math.max(RESOLVED_SEARCH_PROVIDERS.length, getAllowedSearchProviders().length);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function isCommandEnabled(config: WebSearchConfig, name: "websearch" | "curator" | "search" | "google-account"): boolean {
|
|
229
|
+
return config.commands?.[name]?.enabled !== false;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function resolveToolNames(config: WebSearchConfig): ToolNames {
|
|
233
|
+
if (config.toolNames !== undefined && (!config.toolNames || typeof config.toolNames !== "object" || Array.isArray(config.toolNames))) {
|
|
234
|
+
throw new Error(`toolNames in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
|
|
235
|
+
}
|
|
236
|
+
const names = { ...DEFAULT_TOOL_NAMES };
|
|
237
|
+
for (const key of Object.keys(DEFAULT_TOOL_NAMES) as Array<keyof ToolNames>) {
|
|
238
|
+
const value = config.toolNames?.[key];
|
|
239
|
+
if (value === undefined) continue;
|
|
240
|
+
if (typeof value !== "string") throw new Error(`toolNames.${key} in ${WEB_SEARCH_CONFIG_PATH} must be a string`);
|
|
241
|
+
const trimmed = value.trim();
|
|
242
|
+
if (!TOOL_NAME_PATTERN.test(trimmed)) {
|
|
243
|
+
throw new Error(`toolNames.${key} in ${WEB_SEARCH_CONFIG_PATH} must start with a letter and contain only letters, numbers, underscores, or hyphens`);
|
|
244
|
+
}
|
|
245
|
+
names[key] = trimmed;
|
|
246
|
+
}
|
|
247
|
+
const registeredKeys = (Object.keys(DEFAULT_TOOL_NAMES) as Array<keyof ToolNames>)
|
|
248
|
+
.filter(key => isToolEnabled(config, key));
|
|
249
|
+
const seen = new Map<string, keyof ToolNames>();
|
|
250
|
+
for (const key of registeredKeys) {
|
|
251
|
+
const name = names[key];
|
|
252
|
+
if (name === "web_enable") throw new Error(`toolNames.${key} in ${WEB_SEARCH_CONFIG_PATH} uses reserved loader name web_enable`);
|
|
253
|
+
const previous = seen.get(name);
|
|
254
|
+
if (previous) throw new Error(`toolNames.${key} duplicates toolNames.${previous} in ${WEB_SEARCH_CONFIG_PATH}`);
|
|
255
|
+
seen.set(name, key);
|
|
256
|
+
}
|
|
257
|
+
return names;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function loadConfigForExtensionInit(): WebSearchConfig {
|
|
261
|
+
try {
|
|
262
|
+
return loadConfig();
|
|
263
|
+
} catch (err) {
|
|
264
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
265
|
+
console.error(`[pi-web-access] ${message}`);
|
|
266
|
+
return {};
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function resolveCuratorSearchProvider(requested: unknown, current: SearchProviderSelection): SearchProviderSelection {
|
|
271
|
+
const normalized = normalizeProviderInput(requested);
|
|
272
|
+
if (!normalized || normalized === "auto") return current;
|
|
273
|
+
return normalized === "all" && Array.isArray(current) ? current : normalized;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function normalizeCuratorTimeoutSeconds(value: unknown): number | undefined {
|
|
277
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
|
|
278
|
+
const normalized = Math.floor(value);
|
|
279
|
+
if (normalized < 1) return undefined;
|
|
280
|
+
return Math.min(normalized, MAX_CURATOR_TIMEOUT_SECONDS);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function getCuratorTimeoutSeconds(): number {
|
|
284
|
+
const source = loadConfig();
|
|
285
|
+
const explicit = normalizeCuratorTimeoutSeconds(source.curatorTimeoutSeconds);
|
|
286
|
+
if (explicit !== undefined) return explicit;
|
|
287
|
+
// Remote users must notice and click a printed link, so allow more idle time.
|
|
288
|
+
return resolveCuratorNetworkConfig().enabled ? DEFAULT_REMOTE_CURATOR_TIMEOUT_SECONDS : DEFAULT_CURATOR_TIMEOUT_SECONDS;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export function getSummaryGenerationDeadlineMs(): number {
|
|
292
|
+
const value = loadConfig().summaryGenerationDeadlineMs;
|
|
293
|
+
if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
|
|
294
|
+
return SUMMARY_GENERATION_DEADLINE_MS;
|
|
295
|
+
}
|
|
296
|
+
return Math.min(value, MAX_SUMMARY_GENERATION_DEADLINE_MS);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function getSummaryInstructions(): string | undefined {
|
|
300
|
+
const value = loadConfig().summaryInstructions;
|
|
301
|
+
if (typeof value !== "string") return undefined;
|
|
302
|
+
const trimmed = value.trim();
|
|
303
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function readHelperModelKey(key: "summaryModel" | "queryRewriteModel"): string | undefined {
|
|
307
|
+
const value: unknown = loadConfig()[key];
|
|
308
|
+
if (value === undefined) return undefined;
|
|
309
|
+
const message = `${key} in ${WEB_SEARCH_CONFIG_PATH} must be "current", "current:<level>", or "provider/model-id[:<level>]"`;
|
|
310
|
+
if (typeof value !== "string") throw new Error(message);
|
|
311
|
+
try {
|
|
312
|
+
resolveHelperModelSelector(value, key);
|
|
313
|
+
} catch {
|
|
314
|
+
throw new Error(message);
|
|
315
|
+
}
|
|
316
|
+
return value.trim();
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function shouldAutoOpenCuratorBrowser(config: WebSearchConfig): boolean {
|
|
320
|
+
if (config.autoOpenBrowser === false) return false;
|
|
321
|
+
if (resolveCuratorNetworkConfig().enabled && config.autoOpenBrowser !== true) return false;
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async function getProviderAvailability(ctx: ExtensionContext): Promise<ProviderAvailability> {
|
|
326
|
+
const allowedProviders = new Set(getAllowedSearchProviders());
|
|
327
|
+
const geminiWebAvail = allowedProviders.has("gemini") ? await getOptionalGeminiWebAvailability() : null;
|
|
328
|
+
const geminiApiAvail = allowedProviders.has("gemini") && isGeminiApiAvailable();
|
|
329
|
+
const providers = {
|
|
330
|
+
openai: allowedProviders.has("openai") && await isOpenAISearchAvailable(ctx),
|
|
331
|
+
brave: allowedProviders.has("brave") && isBraveAvailable(),
|
|
332
|
+
parallel: allowedProviders.has("parallel") && isParallelAvailable(),
|
|
333
|
+
"parallel-mcp": allowedProviders.has("parallel-mcp") && isParallelMcpAvailable(),
|
|
334
|
+
tinyfish: allowedProviders.has("tinyfish") && isTinyFishAvailable(),
|
|
335
|
+
searchinfinity: allowedProviders.has("searchinfinity") && isSearchinfinityAvailable(),
|
|
336
|
+
querit: allowedProviders.has("querit") && isQueritAvailable(),
|
|
337
|
+
tavily: allowedProviders.has("tavily") && isTavilyAvailable(),
|
|
338
|
+
tabstack: allowedProviders.has("tabstack") && isTabstackAvailable(),
|
|
339
|
+
you: allowedProviders.has("you") && isYouAvailable(),
|
|
340
|
+
firecrawl: allowedProviders.has("firecrawl") && isFirecrawlAvailable(),
|
|
341
|
+
jina: allowedProviders.has("jina") && isJinaSearchAvailable(),
|
|
342
|
+
kagi: allowedProviders.has("kagi") && isKagiAvailable(),
|
|
343
|
+
bocha: allowedProviders.has("bocha") && isBochaAvailable(),
|
|
344
|
+
ollama: allowedProviders.has("ollama") && isOllamaAvailable(),
|
|
345
|
+
searxng: allowedProviders.has("searxng") && isSearXNGAvailable(),
|
|
346
|
+
degoog: allowedProviders.has("degoog") && isDegoogAvailable(),
|
|
347
|
+
duckduckgo: allowedProviders.has("duckduckgo") && isDuckDuckGoAvailable(),
|
|
348
|
+
perplexity: allowedProviders.has("perplexity") && isPerplexityAvailable(),
|
|
349
|
+
exa: allowedProviders.has("exa") && isExaAvailable(),
|
|
350
|
+
gemini: geminiApiAvail || !!geminiWebAvail,
|
|
351
|
+
kimi: allowedProviders.has("kimi") && await isKimiSearchAvailable(ctx),
|
|
352
|
+
anysearch: allowedProviders.has("anysearch") && isAnySearchAvailable(),
|
|
353
|
+
xai: allowedProviders.has("xai") && await isXaiSearchAvailable(ctx),
|
|
354
|
+
mistral: allowedProviders.has("mistral") && isMistralAvailable(),
|
|
355
|
+
baizhi: allowedProviders.has("baizhi") && isBaizhiAvailable(),
|
|
356
|
+
zai: allowedProviders.has("zai") && isZaiAvailable(),
|
|
357
|
+
valyu: allowedProviders.has("valyu") && isValyuAvailable(),
|
|
358
|
+
keenable: allowedProviders.has("keenable") && isKeenableAvailable(),
|
|
359
|
+
ceramic: allowedProviders.has("ceramic") && isCeramicAvailable(),
|
|
360
|
+
linkup: allowedProviders.has("linkup") && isLinkupAvailable(),
|
|
361
|
+
ninerouter: allowedProviders.has("ninerouter") && isNineRouterAvailable(),
|
|
362
|
+
cloudflare: allowedProviders.has("cloudflare") && isCloudflareSearchAvailable(),
|
|
363
|
+
deepseek: allowedProviders.has("deepseek") && isDeepSeekAvailable(),
|
|
364
|
+
};
|
|
365
|
+
return {
|
|
366
|
+
all: ALL_SEARCH_PROVIDERS.some(provider => provider === "gemini" ? geminiApiAvail : providers[provider]),
|
|
367
|
+
customProviders: getAvailableCustomSearchProviders(),
|
|
368
|
+
...providers,
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
async function getOptionalGeminiWebAvailability() {
|
|
373
|
+
try {
|
|
374
|
+
return await isGeminiWebAvailable();
|
|
375
|
+
} catch {
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function shouldPreferOpenAI(options: Pick<PendingCurate, "numResults" | "recencyFilter"> | undefined, preferOpenAICodexDefault: boolean): boolean {
|
|
381
|
+
if (options?.recencyFilter) return false;
|
|
382
|
+
if (typeof options?.numResults === "number" && Number.isFinite(options.numResults) && Math.floor(options.numResults) !== 5) {
|
|
383
|
+
return false;
|
|
384
|
+
}
|
|
385
|
+
return preferOpenAICodexDefault;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async function loadCuratorBootstrap(
|
|
389
|
+
requestedProvider: unknown,
|
|
390
|
+
ctx: ExtensionContext,
|
|
391
|
+
options?: Pick<PendingCurate, "numResults" | "recencyFilter">,
|
|
392
|
+
): Promise<CuratorBootstrap> {
|
|
393
|
+
const provider = resolveRequestedProvider(requestedProvider);
|
|
394
|
+
const availableProviders = await getProviderAvailability(ctx);
|
|
395
|
+
if (Array.isArray(provider)) availableProviders.all = true;
|
|
396
|
+
return {
|
|
397
|
+
availableProviders,
|
|
398
|
+
defaultProvider: resolveCuratorDefaultProvider(provider, availableProviders, ctx, options),
|
|
399
|
+
timeoutSeconds: getCuratorTimeoutSeconds(),
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export function resolveCuratorDefaultProvider(
|
|
404
|
+
provider: SearchProviderSelection,
|
|
405
|
+
available: ProviderAvailability,
|
|
406
|
+
ctx?: Parameters<typeof isOpenAISubscriptionModelSelected>[0],
|
|
407
|
+
options?: Pick<PendingCurate, "numResults" | "recencyFilter">,
|
|
408
|
+
): SearchProvider {
|
|
409
|
+
return resolveProvider(provider, available, options, isOpenAISubscriptionModelSelected(ctx), ctx);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function firstAvailableProvider(available: ProviderAvailability, preferOpenAI: boolean, fallback: ResolvedSearchProvider): ResolvedSearchProvider | "auto" {
|
|
413
|
+
if (available.searxng) return "searxng";
|
|
414
|
+
if (preferOpenAI && available.openai) return "openai";
|
|
415
|
+
if (available.exa) return "exa";
|
|
416
|
+
for (const provider of ALL_SEARCH_PROVIDERS) {
|
|
417
|
+
if (provider === "ollama" && available.bocha) return "bocha";
|
|
418
|
+
if (available[provider]) return provider;
|
|
419
|
+
}
|
|
420
|
+
const allowed = getAllowedSearchProviders();
|
|
421
|
+
return allowed.includes(fallback) ? fallback : "auto";
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function resolveProvider(
|
|
425
|
+
provider: SearchProviderSelection,
|
|
426
|
+
available: ProviderAvailability,
|
|
427
|
+
options?: Pick<PendingCurate, "numResults" | "recencyFilter">,
|
|
428
|
+
preferOpenAICodexDefault = false,
|
|
429
|
+
ctx?: Pick<ExtensionContext, "model">,
|
|
430
|
+
): SearchProvider {
|
|
431
|
+
if (Array.isArray(provider)) return "all";
|
|
432
|
+
const preferOpenAI = shouldPreferOpenAI(options, preferOpenAICodexDefault);
|
|
433
|
+
|
|
434
|
+
if (provider === "auto") {
|
|
435
|
+
const routing = getConfiguredSearchRouting();
|
|
436
|
+
if (routing) {
|
|
437
|
+
for (const candidate of routing.providers) {
|
|
438
|
+
if (candidate === "openai" && routing.useCurrentModel === true && !isCurrentModelHostedSearchEligible(ctx)) continue;
|
|
439
|
+
if (available[candidate as BuiltinSearchProvider] || available.customProviders?.includes(candidate)) return candidate;
|
|
440
|
+
}
|
|
441
|
+
return routing.providers.find(candidate => candidate !== "openai" || routing.useCurrentModel !== true || isCurrentModelHostedSearchEligible(ctx)) ?? routing.providers[0];
|
|
442
|
+
}
|
|
443
|
+
return firstAvailableProvider(available, preferOpenAI, "exa");
|
|
444
|
+
}
|
|
445
|
+
if (provider === "all") {
|
|
446
|
+
return available.all ? "all" : firstAvailableProvider(available, preferOpenAI, "exa");
|
|
447
|
+
}
|
|
448
|
+
if (ALL_SEARCH_PROVIDERS.includes(provider as BuiltinSearchProvider) && !available[provider as BuiltinSearchProvider]) {
|
|
449
|
+
return firstAvailableProvider(available, provider === "openai" ? false : preferOpenAI, provider);
|
|
450
|
+
}
|
|
451
|
+
return provider;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
let widgetVisible = false;
|
|
455
|
+
let widgetUnsubscribe: (() => void) | null = null;
|
|
456
|
+
const pendingCurates = new Map<string, PendingCurate>();
|
|
457
|
+
const activeCurators = new Map<string, CuratorServerHandle>();
|
|
458
|
+
const glimpseWins = new Map<string, GlimpseWindow>();
|
|
459
|
+
|
|
460
|
+
interface PendingCurate {
|
|
461
|
+
phase: "searching" | "curating";
|
|
462
|
+
workflow: CuratorWorkflow;
|
|
463
|
+
summaryContext: SummaryGenerationContext;
|
|
464
|
+
searchResults: Map<number, QueryResultData>;
|
|
465
|
+
resultSlots: Map<number, number>;
|
|
466
|
+
allInlineContent: ExtractedContent[];
|
|
467
|
+
queryList: string[];
|
|
468
|
+
includeContent: boolean;
|
|
469
|
+
numResults?: number;
|
|
470
|
+
recencyFilter?: "day" | "week" | "month" | "year";
|
|
471
|
+
domainFilter?: string[];
|
|
472
|
+
category?: string;
|
|
473
|
+
objective?: string;
|
|
474
|
+
availableProviders: ProviderAvailability;
|
|
475
|
+
defaultProvider: SearchProvider;
|
|
476
|
+
searchProvider: SearchProviderSelection;
|
|
477
|
+
// The provider resolved from config when the call named none; searches still using it may fall back to searchRouting.
|
|
478
|
+
configDefaultProvider?: SearchProviderSelection;
|
|
479
|
+
summaryModels: Array<{ value: string; label: string }>;
|
|
480
|
+
defaultSummaryModel: string | null;
|
|
481
|
+
timeoutSeconds: number;
|
|
482
|
+
proxy?: string;
|
|
483
|
+
curatorUrl?: string;
|
|
484
|
+
onUpdate: ((update: { content: Array<{ type: string; text: string }>; details?: Record<string, unknown> }) => void) | undefined;
|
|
485
|
+
signal: AbortSignal | undefined;
|
|
486
|
+
abortSearches: () => void;
|
|
487
|
+
finish: (value: AgentToolResult<Record<string, unknown>>) => void;
|
|
488
|
+
cancel: (reason?: "user" | "stale") => void;
|
|
489
|
+
browserPromise?: Promise<void>;
|
|
490
|
+
browserOpenError?: string;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function closeCurator(callId?: string): void {
|
|
494
|
+
if (callId !== undefined) {
|
|
495
|
+
const win = glimpseWins.get(callId);
|
|
496
|
+
glimpseWins.delete(callId);
|
|
497
|
+
try { win?.close(); } catch {}
|
|
498
|
+
pendingCurates.get(callId)?.cancel("stale");
|
|
499
|
+
pendingCurates.delete(callId);
|
|
500
|
+
const curator = activeCurators.get(callId);
|
|
501
|
+
activeCurators.delete(callId);
|
|
502
|
+
try { curator?.close(); } catch {}
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
for (const win of glimpseWins.values()) {
|
|
507
|
+
try { win.close(); } catch {}
|
|
508
|
+
}
|
|
509
|
+
glimpseWins.clear();
|
|
510
|
+
for (const pc of pendingCurates.values()) {
|
|
511
|
+
try { pc.cancel("stale"); } catch {}
|
|
512
|
+
}
|
|
513
|
+
pendingCurates.clear();
|
|
514
|
+
for (const curator of activeCurators.values()) {
|
|
515
|
+
try { curator.close(); } catch {}
|
|
516
|
+
}
|
|
517
|
+
activeCurators.clear();
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
async function openInBrowser(pi: ExtensionAPI, url: string): Promise<void> {
|
|
521
|
+
const plat = platform();
|
|
522
|
+
if (plat !== "darwin" && plat !== "win32") {
|
|
523
|
+
await new Promise<void>((resolve, reject) => {
|
|
524
|
+
const child = spawn("xdg-open", [url], { detached: true, stdio: "ignore" });
|
|
525
|
+
const timer = setTimeout(resolve, 100);
|
|
526
|
+
child.once("error", (err) => {
|
|
527
|
+
clearTimeout(timer);
|
|
528
|
+
reject(err);
|
|
529
|
+
});
|
|
530
|
+
child.once("exit", (code) => {
|
|
531
|
+
clearTimeout(timer);
|
|
532
|
+
if (code === 0) resolve();
|
|
533
|
+
else reject(new Error(`Failed to open browser (exit code ${code ?? "unknown"})`));
|
|
534
|
+
});
|
|
535
|
+
child.unref();
|
|
536
|
+
});
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
const result = plat === "darwin"
|
|
540
|
+
? await pi.exec("open", [url])
|
|
541
|
+
: await pi.exec("cmd", ["/c", "start", "", url]);
|
|
542
|
+
if (result.code !== 0) {
|
|
543
|
+
throw new Error(result.stderr || `Failed to open browser (exit code ${result.code})`);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
interface GlimpseWindow {
|
|
548
|
+
on(event: "closed", handler: () => void): void;
|
|
549
|
+
on(event: "message", handler: (data: unknown) => void): void;
|
|
550
|
+
on(event: "ready", handler: (info: { screen?: { visibleHeight?: number } }) => void): void;
|
|
551
|
+
close(): void;
|
|
552
|
+
_write(obj: Record<string, unknown>): void;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
let glimpseOpen: ((html: string, opts: Record<string, unknown>) => GlimpseWindow) | null | undefined;
|
|
556
|
+
|
|
557
|
+
function findGlimpseMjs(): string | null {
|
|
558
|
+
try {
|
|
559
|
+
const req = createRequire(import.meta.url);
|
|
560
|
+
return req.resolve("glimpseui");
|
|
561
|
+
} catch {
|
|
562
|
+
// Optional dependency.
|
|
563
|
+
}
|
|
564
|
+
try {
|
|
565
|
+
const globalRoot = execFileSync("npm", ["root", "-g"], { encoding: "utf-8" }).trim();
|
|
566
|
+
const entry = join(globalRoot, "glimpseui", "src", "glimpse.mjs");
|
|
567
|
+
if (existsSync(entry)) return entry;
|
|
568
|
+
} catch {
|
|
569
|
+
// npm may be unavailable.
|
|
570
|
+
}
|
|
571
|
+
return null;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
async function getGlimpseOpen() {
|
|
575
|
+
if (glimpseOpen !== undefined) return glimpseOpen;
|
|
576
|
+
const resolved = findGlimpseMjs();
|
|
577
|
+
if (resolved) {
|
|
578
|
+
try {
|
|
579
|
+
glimpseOpen = (await import(resolved)).open;
|
|
580
|
+
return glimpseOpen;
|
|
581
|
+
} catch {}
|
|
582
|
+
}
|
|
583
|
+
glimpseOpen = null;
|
|
584
|
+
return glimpseOpen;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function openInGlimpse(
|
|
588
|
+
open: (html: string, opts: Record<string, unknown>) => GlimpseWindow,
|
|
589
|
+
url: string,
|
|
590
|
+
title: string,
|
|
591
|
+
): GlimpseWindow {
|
|
592
|
+
const shellHTML = `<!DOCTYPE html>
|
|
593
|
+
<html>
|
|
594
|
+
<head><meta charset="UTF-8"><title>${title}</title></head>
|
|
595
|
+
<body style="margin:0; background:#1a1a2e;">
|
|
596
|
+
<script>window.location.replace(${JSON.stringify(url)});</script>
|
|
597
|
+
</body>
|
|
598
|
+
</html>`;
|
|
599
|
+
const win = open(shellHTML, {
|
|
600
|
+
width: 800,
|
|
601
|
+
height: 900,
|
|
602
|
+
title,
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
let maxHeight = 1200;
|
|
606
|
+
win.on("ready", (info) => {
|
|
607
|
+
const visibleHeight = info?.screen?.visibleHeight;
|
|
608
|
+
if (typeof visibleHeight === "number" && visibleHeight > 0) {
|
|
609
|
+
maxHeight = Math.floor(visibleHeight * 0.85);
|
|
610
|
+
}
|
|
611
|
+
});
|
|
612
|
+
win.on("message", (data) => {
|
|
613
|
+
if (!data || typeof data !== "object") return;
|
|
614
|
+
const msg = data as Record<string, unknown>;
|
|
615
|
+
if (msg.type !== "resize" || typeof msg.height !== "number") return;
|
|
616
|
+
const clamped = Math.max(400, Math.min(Math.round(msg.height), maxHeight));
|
|
617
|
+
win._write({ type: "resize", width: 800, height: clamped });
|
|
618
|
+
});
|
|
619
|
+
|
|
620
|
+
return win;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
function extractDomain(url: string): string {
|
|
624
|
+
try { return new URL(url).hostname; }
|
|
625
|
+
catch { return url; }
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function toCuratorSearchEntries(response: AttributedSearchResponse): CuratorSearchEntry[] {
|
|
629
|
+
const providerResponses = response.provider === "all" && response.providerResponses?.length
|
|
630
|
+
? response.providerResponses
|
|
631
|
+
: [response];
|
|
632
|
+
const entries: CuratorSearchEntry[] = providerResponses.map(result => ({
|
|
633
|
+
answer: result.answer,
|
|
634
|
+
results: result.results.map(source => ({ ...source, domain: extractDomain(source.url) })),
|
|
635
|
+
provider: result.provider,
|
|
636
|
+
}));
|
|
637
|
+
for (const failure of response.providerErrors ?? []) {
|
|
638
|
+
entries.push({
|
|
639
|
+
answer: "",
|
|
640
|
+
results: [],
|
|
641
|
+
provider: failure.provider,
|
|
642
|
+
error: failure.error,
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
return entries;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function indexedCuratorEntryToQueryResult(entry: IndexedCuratorSearchEntry): QueryResultData {
|
|
649
|
+
return {
|
|
650
|
+
query: entry.query,
|
|
651
|
+
answer: entry.answer,
|
|
652
|
+
results: entry.results.map(source => ({
|
|
653
|
+
title: source.title,
|
|
654
|
+
url: source.url,
|
|
655
|
+
snippet: source.snippet ?? "",
|
|
656
|
+
})),
|
|
657
|
+
error: entry.error ?? null,
|
|
658
|
+
provider: entry.provider,
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function updateWidget(ctx: ExtensionContext): void {
|
|
663
|
+
const theme = ctx.ui.theme;
|
|
664
|
+
const entries = activityMonitor.getEntries();
|
|
665
|
+
const lines: string[] = [];
|
|
666
|
+
|
|
667
|
+
lines.push(theme.fg("accent", "─── Web Search Activity " + "─".repeat(36)));
|
|
668
|
+
|
|
669
|
+
if (entries.length === 0) {
|
|
670
|
+
lines.push(theme.fg("muted", " No activity yet"));
|
|
671
|
+
} else {
|
|
672
|
+
for (const e of entries) {
|
|
673
|
+
lines.push(" " + formatEntryLine(e, theme));
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
lines.push(theme.fg("accent", "─".repeat(60)));
|
|
678
|
+
|
|
679
|
+
const rateInfo = activityMonitor.getRateLimitInfo();
|
|
680
|
+
const resetMs = rateInfo.oldestTimestamp ? Math.max(0, rateInfo.oldestTimestamp + rateInfo.windowMs - Date.now()) : 0;
|
|
681
|
+
const resetSec = Math.ceil(resetMs / 1000);
|
|
682
|
+
lines.push(
|
|
683
|
+
theme.fg("muted", `Rate: ${rateInfo.used}/${rateInfo.max}`) +
|
|
684
|
+
(resetMs > 0 ? theme.fg("dim", ` (resets in ${resetSec}s)`) : ""),
|
|
685
|
+
);
|
|
686
|
+
|
|
687
|
+
ctx.ui.setWidget("web-activity", lines);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function formatEntryLine(
|
|
691
|
+
entry: ActivityEntry,
|
|
692
|
+
theme: ExtensionTheme,
|
|
693
|
+
): string {
|
|
694
|
+
const typeStr = entry.type === "api" ? "API" : "GET";
|
|
695
|
+
const target =
|
|
696
|
+
entry.type === "api"
|
|
697
|
+
? `"${truncateToWidth(entry.query || "", 28, "")}"`
|
|
698
|
+
: truncateToWidth(entry.url?.replace(/^https?:\/\//, "") || "", 30, "");
|
|
699
|
+
|
|
700
|
+
const duration = entry.endTime
|
|
701
|
+
? `${((entry.endTime - entry.startTime) / 1000).toFixed(1)}s`
|
|
702
|
+
: `${((Date.now() - entry.startTime) / 1000).toFixed(1)}s`;
|
|
703
|
+
|
|
704
|
+
let statusStr: string;
|
|
705
|
+
let indicator: string;
|
|
706
|
+
if (entry.error) {
|
|
707
|
+
statusStr = "err";
|
|
708
|
+
indicator = theme.fg("error", "✗");
|
|
709
|
+
} else if (entry.status === null) {
|
|
710
|
+
statusStr = "...";
|
|
711
|
+
indicator = theme.fg("warning", "⋯");
|
|
712
|
+
} else if (entry.status === 0) {
|
|
713
|
+
statusStr = "abort";
|
|
714
|
+
indicator = theme.fg("muted", "○");
|
|
715
|
+
} else {
|
|
716
|
+
statusStr = String(entry.status);
|
|
717
|
+
indicator = entry.status >= 200 && entry.status < 300 ? theme.fg("success", "✓") : theme.fg("error", "✗");
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
return `${typeStr.padEnd(4)} ${target.padEnd(32)} ${statusStr.padStart(5)} ${duration.padStart(5)} ${indicator}`;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function refreshUi(ctx: ExtensionContext): void {
|
|
724
|
+
closeCurator();
|
|
725
|
+
// Unsubscribe before clear() to avoid callback with stale ctx
|
|
726
|
+
widgetUnsubscribe?.();
|
|
727
|
+
widgetUnsubscribe = null;
|
|
728
|
+
activityMonitor.clear();
|
|
729
|
+
if (widgetVisible) {
|
|
730
|
+
// Re-subscribe with new ctx
|
|
731
|
+
widgetUnsubscribe = activityMonitor.onUpdate(() => updateWidget(ctx));
|
|
732
|
+
updateWidget(ctx);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
export default function (pi: ExtensionAPI) {
|
|
737
|
+
const initConfig = loadConfigForExtensionInit();
|
|
738
|
+
// Fixes the process-wide policy, so definitions and every later check agree. Outside
|
|
739
|
+
// loadConfigForExtensionInit, which logs config errors instead of throwing: a bad policy value
|
|
740
|
+
// must stop the extension. An unparseable config leaves {} here (env only); every model route
|
|
741
|
+
// re-reads that config and fails while it stays broken, and a fixed config applies on restart.
|
|
742
|
+
const retrievalOnly = getRetrievalOnlyPolicy(initConfig);
|
|
743
|
+
const retrievalOnlySuffix = retrievalOnly.enabled ? RETRIEVAL_ONLY_DESCRIPTION_SUFFIX : "";
|
|
744
|
+
const fetchModeConfig = resolveFetchModeConfig(initConfig);
|
|
745
|
+
const toolActivation = initConfig.toolActivation ?? "auto";
|
|
746
|
+
if (toolActivation !== "auto" && toolActivation !== "dynamic" && toolActivation !== "eager" && toolActivation !== "none") {
|
|
747
|
+
throw new Error(`toolActivation in ${WEB_SEARCH_CONFIG_PATH} must be "auto", "dynamic", "eager", or "none"`);
|
|
748
|
+
}
|
|
749
|
+
const toolExposure = initConfig.toolExposure ?? "direct";
|
|
750
|
+
if (toolExposure !== "direct" && toolExposure !== "deferred") {
|
|
751
|
+
throw new Error(`toolExposure in ${WEB_SEARCH_CONFIG_PATH} must be "direct" or "deferred"`);
|
|
752
|
+
}
|
|
753
|
+
if (toolExposure === "deferred" && toolActivation === "eager") {
|
|
754
|
+
throw new Error(`toolExposure "deferred" in ${WEB_SEARCH_CONFIG_PATH} cannot be combined with toolActivation "eager"`);
|
|
755
|
+
}
|
|
756
|
+
if (toolActivation === "none" && toolExposure !== "deferred") {
|
|
757
|
+
throw new Error(`toolActivation "none" in ${WEB_SEARCH_CONFIG_PATH} requires toolExposure "deferred"`);
|
|
758
|
+
}
|
|
759
|
+
const allowedSearchProviders = initConfig.webSearch?.allowedProviders === undefined ? RESOLVED_SEARCH_PROVIDERS : getAllowedSearchProviders();
|
|
760
|
+
const modelProviders = retrievalOnly.enabled ? [] : allowedSearchProviders.filter(provider => provider === "openai" || provider === "xai" || provider === "mistral" || provider === "gemini");
|
|
761
|
+
// Depends on config only, never on credentials, so definitions stay byte-stable across environments.
|
|
762
|
+
const providerDescription = `auto, all, a name, or comma-separated names; omit for the configured default.${initConfig.webSearch?.allowedProviders === undefined ? "" : ` Allowed: ${allowedSearchProviders.join(", ")}.`}`;
|
|
763
|
+
const curatorRunState = registerCuratorRunLifecycle(pi);
|
|
764
|
+
const toolNames = resolveToolNames(initConfig);
|
|
765
|
+
const webSearchEnabled = isToolEnabled(initConfig, "webSearch");
|
|
766
|
+
const sourceCheckEnabled = isToolEnabled(initConfig, "sourceCheck");
|
|
767
|
+
const fetchContentEnabled = isToolEnabled(initConfig, "fetchContent");
|
|
768
|
+
const getSearchContentEnabled = isToolEnabled(initConfig, "getSearchContent");
|
|
769
|
+
const coreSettings = {
|
|
770
|
+
toolNames,
|
|
771
|
+
enabledTools: {
|
|
772
|
+
webSearch: webSearchEnabled,
|
|
773
|
+
sourceCheck: sourceCheckEnabled,
|
|
774
|
+
fetchContent: fetchContentEnabled,
|
|
775
|
+
getSearchContent: getSearchContentEnabled,
|
|
776
|
+
},
|
|
777
|
+
maxInlineContentChars: getMaxInlineContentChars(initConfig),
|
|
778
|
+
fetchModes: fetchModeConfig,
|
|
779
|
+
};
|
|
780
|
+
// Names as registered this session, so fetch failure guidance never points
|
|
781
|
+
// at tools that are disabled or were renamed after init.
|
|
782
|
+
const registeredToolNames = registeredFetchToolNames(coreSettings);
|
|
783
|
+
const storedContentSources = storedContentSourceNames(coreSettings);
|
|
784
|
+
const fetchContentStorageNote = getSearchContentEnabled
|
|
785
|
+
? `Full content is stored for retrieval with ${toolNames.getSearchContent}.`
|
|
786
|
+
: "Full content is stored, but the retrieval tool is not registered.";
|
|
787
|
+
const fetchModeDescription = fetchModeConfig.allowedModes
|
|
788
|
+
.map(mode => `${mode}${mode === fetchModeConfig.defaultMode ? " (default)" : ""}: ${FETCH_MODE_DESCRIPTIONS[mode]}`)
|
|
789
|
+
.join("; ");
|
|
790
|
+
const curateKey = initConfig.shortcuts?.curate || DEFAULT_SHORTCUTS.curate;
|
|
791
|
+
const activityKey = initConfig.shortcuts?.activity || DEFAULT_SHORTCUTS.activity;
|
|
792
|
+
|
|
793
|
+
// Session state is this instance's. Pi runs one instance and switches its session; a host
|
|
794
|
+
// that serves several sessions at once runs one instance per session, and one session
|
|
795
|
+
// starting or ending must not clear another's results or abort its fetches.
|
|
796
|
+
const sessionResults = createPiSessionResults(pi);
|
|
797
|
+
const { ownedResults } = sessionResults;
|
|
798
|
+
const pendingFetches = new Map<string, AbortController>();
|
|
799
|
+
let sessionActive = false;
|
|
800
|
+
|
|
801
|
+
function abortPendingFetches(): void {
|
|
802
|
+
for (const controller of pendingFetches.values()) {
|
|
803
|
+
controller.abort();
|
|
804
|
+
}
|
|
805
|
+
pendingFetches.clear();
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
function publish(data: StoredSearchData): void {
|
|
809
|
+
sessionResults.publish(data);
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
function endSession(): void {
|
|
813
|
+
sessionActive = false;
|
|
814
|
+
abortPendingFetches();
|
|
815
|
+
sessionResults.close();
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
function startSession(ctx: ExtensionContext): void {
|
|
819
|
+
sessionActive = false;
|
|
820
|
+
abortPendingFetches();
|
|
821
|
+
sessionResults.start(ctx);
|
|
822
|
+
sessionActive = true;
|
|
823
|
+
refreshUi(ctx);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
function startBackgroundFetch(urls: string[], proxy?: string, provided?: ExtractedContent[]): string | null {
|
|
827
|
+
if (urls.length === 0) return null;
|
|
828
|
+
const fetchId = generateId();
|
|
829
|
+
const controller = new AbortController();
|
|
830
|
+
pendingFetches.set(fetchId, controller);
|
|
831
|
+
Promise.resolve()
|
|
832
|
+
.then(() => fetchUncoveredContent(urls, provided, missing => runWithProxy(proxy, () => fetchAllContent(missing, controller.signal, withRegisteredFetchOptions(undefined, registeredToolNames, proxy)))))
|
|
833
|
+
.then((fetched) => {
|
|
834
|
+
if (!sessionActive || !pendingFetches.has(fetchId)) return;
|
|
835
|
+
const data = {
|
|
836
|
+
id: fetchId,
|
|
837
|
+
type: "fetch",
|
|
838
|
+
timestamp: Date.now(),
|
|
839
|
+
urls: stripThumbnails(fetched),
|
|
840
|
+
} satisfies FetchedContentData;
|
|
841
|
+
publish(storeFetchedContentResult(fetchId, data));
|
|
842
|
+
const ok = fetched.filter(f => !f.error).length;
|
|
843
|
+
const availabilityStatus = ok === fetched.length ? "full" : ok > 0 ? "partial" : "none";
|
|
844
|
+
const availability = availabilityStatus === "full"
|
|
845
|
+
? "Full page content now available."
|
|
846
|
+
: availabilityStatus === "partial"
|
|
847
|
+
? "Partial page content now available."
|
|
848
|
+
: "No page content was fetched. Stored fetch diagnostics are available.";
|
|
849
|
+
pi.sendMessage(
|
|
850
|
+
{
|
|
851
|
+
customType: "web-search-content-ready",
|
|
852
|
+
content: `Content fetched for ${ok}/${fetched.length} URLs [${fetchId}]. ${availability}`,
|
|
853
|
+
display: true,
|
|
854
|
+
details: {
|
|
855
|
+
fetchId,
|
|
856
|
+
successfulUrls: ok,
|
|
857
|
+
totalUrls: fetched.length,
|
|
858
|
+
availability: availabilityStatus,
|
|
859
|
+
},
|
|
860
|
+
},
|
|
861
|
+
{ triggerTurn: true },
|
|
862
|
+
);
|
|
863
|
+
})
|
|
864
|
+
.catch((err) => {
|
|
865
|
+
if (!sessionActive || !pendingFetches.has(fetchId)) return;
|
|
866
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
867
|
+
const isAbort = (err instanceof Error && err.name === "AbortError") || message.toLowerCase().includes("abort");
|
|
868
|
+
if (!isAbort) {
|
|
869
|
+
pi.sendMessage(
|
|
870
|
+
{
|
|
871
|
+
customType: "web-search-error",
|
|
872
|
+
content: `Content fetch failed [${fetchId}]: ${message}`,
|
|
873
|
+
display: true,
|
|
874
|
+
},
|
|
875
|
+
{ triggerTurn: false },
|
|
876
|
+
);
|
|
877
|
+
}
|
|
878
|
+
})
|
|
879
|
+
.finally(() => { pendingFetches.delete(fetchId); });
|
|
880
|
+
return fetchId;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
const core = createWebToolCore({
|
|
884
|
+
settings: coreSettings,
|
|
885
|
+
storeFetchedContent(id, data) {
|
|
886
|
+
publish(storeFetchedContentResult(id, data));
|
|
887
|
+
},
|
|
888
|
+
publishResult(data) {
|
|
889
|
+
publish(data);
|
|
890
|
+
},
|
|
891
|
+
startBackgroundFetch,
|
|
892
|
+
answerFromPage: (request, ctx, signal) => answerFromPage(request, ctx!, signal),
|
|
893
|
+
});
|
|
894
|
+
const buildSearchReturn = core.buildSearchReturn;
|
|
895
|
+
|
|
896
|
+
function normalizeSummaryMeta(meta: SummaryMeta | undefined, summaryText: string): SummaryMeta {
|
|
897
|
+
const normalizedText = summaryText.trim();
|
|
898
|
+
if (!meta) {
|
|
899
|
+
return {
|
|
900
|
+
model: null,
|
|
901
|
+
durationMs: 0,
|
|
902
|
+
tokenEstimate: normalizedText.length > 0 ? Math.max(1, Math.ceil(normalizedText.length / 4)) : 0,
|
|
903
|
+
fallbackUsed: false,
|
|
904
|
+
edited: false,
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
return {
|
|
909
|
+
model: meta.model,
|
|
910
|
+
durationMs: Number.isFinite(meta.durationMs) && meta.durationMs >= 0 ? meta.durationMs : 0,
|
|
911
|
+
tokenEstimate: Number.isFinite(meta.tokenEstimate) && meta.tokenEstimate >= 0
|
|
912
|
+
? meta.tokenEstimate
|
|
913
|
+
: (normalizedText.length > 0 ? Math.max(1, Math.ceil(normalizedText.length / 4)) : 0),
|
|
914
|
+
fallbackUsed: meta.fallbackUsed === true,
|
|
915
|
+
fallbackReason: meta.fallbackReason,
|
|
916
|
+
phase: meta.phase,
|
|
917
|
+
edited: meta.edited === true,
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
function buildCurationCancelledReturn(
|
|
922
|
+
reason: "user" | "stale",
|
|
923
|
+
partial?: {
|
|
924
|
+
queries?: QueryResultData[];
|
|
925
|
+
queryCount?: number;
|
|
926
|
+
browserConnected?: boolean;
|
|
927
|
+
lastHeartbeatAgeMs?: number | null;
|
|
928
|
+
curatorUrl?: string;
|
|
929
|
+
browserOpenError?: string;
|
|
930
|
+
},
|
|
931
|
+
): AgentToolResult<Record<string, unknown>> {
|
|
932
|
+
const message = `Search curation cancelled (${reason}).`;
|
|
933
|
+
const cancelledQueries = partial?.queries?.length
|
|
934
|
+
? partial.queries.map(q => ({
|
|
935
|
+
query: q.query,
|
|
936
|
+
provider: q.provider ?? null,
|
|
937
|
+
error: q.error,
|
|
938
|
+
resultCount: q.results?.length ?? 0,
|
|
939
|
+
}))
|
|
940
|
+
: undefined;
|
|
941
|
+
const extraLines: string[] = [];
|
|
942
|
+
if (partial?.curatorUrl) extraLines.push(`curator: ${partial.curatorUrl}`);
|
|
943
|
+
if (partial?.browserOpenError) extraLines.push(`browser open error: ${partial.browserOpenError}`);
|
|
944
|
+
return {
|
|
945
|
+
content: [{ type: "text", text: message }],
|
|
946
|
+
details: {
|
|
947
|
+
error: message,
|
|
948
|
+
cancelled: true,
|
|
949
|
+
cancelReason: reason,
|
|
950
|
+
browserConnected: partial?.browserConnected,
|
|
951
|
+
lastHeartbeatAgeMs: partial?.lastHeartbeatAgeMs,
|
|
952
|
+
queryCount: partial?.queryCount,
|
|
953
|
+
cancelledQueries,
|
|
954
|
+
extraLines: extraLines.length > 0 ? extraLines : undefined,
|
|
955
|
+
},
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
async function generateSummaryForSelectedIndices(
|
|
960
|
+
selectedQueryIndices: number[],
|
|
961
|
+
resultsByIndex: Map<number, QueryResultData>,
|
|
962
|
+
summaryContext: SummaryGenerationContext,
|
|
963
|
+
signal?: AbortSignal,
|
|
964
|
+
modelOverride?: string,
|
|
965
|
+
feedback?: string,
|
|
966
|
+
): Promise<{ summary: string; meta: SummaryMeta }> {
|
|
967
|
+
if (retrievalOnly.enabled) throw retrievalOnlyError("Summary generation", retrievalOnly);
|
|
968
|
+
const selectedResults: QueryResultData[] = [];
|
|
969
|
+
for (const qi of selectedQueryIndices) {
|
|
970
|
+
const result = resultsByIndex.get(qi);
|
|
971
|
+
if (result) selectedResults.push(result);
|
|
972
|
+
}
|
|
973
|
+
if (selectedResults.length === 0) {
|
|
974
|
+
throw new Error("No selected results available for summary generation");
|
|
975
|
+
}
|
|
976
|
+
const configuredSummaryModel = readHelperModelKey("summaryModel");
|
|
977
|
+
try {
|
|
978
|
+
return await generateSummaryDraft(
|
|
979
|
+
selectedResults,
|
|
980
|
+
summaryContext,
|
|
981
|
+
signal,
|
|
982
|
+
modelOverride?.trim() || configuredSummaryModel,
|
|
983
|
+
feedback,
|
|
984
|
+
undefined,
|
|
985
|
+
getSummaryGenerationDeadlineMs(),
|
|
986
|
+
getSummaryInstructions(),
|
|
987
|
+
{ preferredFallback: configuredSummaryModel === undefined },
|
|
988
|
+
);
|
|
989
|
+
} catch (err) {
|
|
990
|
+
const isEmptyResponse = err instanceof Error && err.message.includes("Summary model returned empty response");
|
|
991
|
+
if (!isEmptyResponse) throw err;
|
|
992
|
+
const deterministic = buildDeterministicSummary(selectedResults);
|
|
993
|
+
return {
|
|
994
|
+
summary: deterministic.summary,
|
|
995
|
+
meta: {
|
|
996
|
+
...deterministic.meta,
|
|
997
|
+
fallbackReason: "summary-model-empty-response",
|
|
998
|
+
},
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
async function loadSummaryModelChoices(
|
|
1004
|
+
summaryContext: SummaryGenerationContext,
|
|
1005
|
+
): Promise<{ summaryModels: Array<{ value: string; label: string }>; defaultSummaryModel: string | null; preferredFallback: boolean }> {
|
|
1006
|
+
if (retrievalOnly.enabled) return { summaryModels: [], defaultSummaryModel: null, preferredFallback: false };
|
|
1007
|
+
const summaryModels: Array<{ value: string; label: string }> = [];
|
|
1008
|
+
const seen = new Set<string>();
|
|
1009
|
+
const availableValues = new Set<string>();
|
|
1010
|
+
|
|
1011
|
+
const addModel = (value: string) => {
|
|
1012
|
+
if (seen.has(value)) return;
|
|
1013
|
+
seen.add(value);
|
|
1014
|
+
summaryModels.push({ value, label: value });
|
|
1015
|
+
};
|
|
1016
|
+
|
|
1017
|
+
for (const model of summaryContext.modelRegistry.getAvailable()) {
|
|
1018
|
+
if (!isModelInScope(model, summaryContext.scopedModels)) continue;
|
|
1019
|
+
availableValues.add(`${model.provider}/${model.id}`);
|
|
1020
|
+
addModel(`${model.provider}/${model.id}`);
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
if (summaryContext.model && isModelInScope(summaryContext.model, summaryContext.scopedModels)) {
|
|
1024
|
+
addModel(`${summaryContext.model.provider}/${summaryContext.model.id}`);
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
const configuredSummaryModel = readHelperModelKey("summaryModel");
|
|
1028
|
+
const preferredDefaults = [
|
|
1029
|
+
{ provider: "anthropic", id: "claude-haiku-4-5" },
|
|
1030
|
+
{ provider: "openai-codex", id: "gpt-5.6-luna" },
|
|
1031
|
+
{ provider: "openai-codex", id: "gpt-5.6-terra" },
|
|
1032
|
+
{ provider: "google", id: "gemini-3.6-flash" },
|
|
1033
|
+
{ provider: "openai", id: "gpt-5-mini" },
|
|
1034
|
+
{ provider: "deepseek", id: "deepseek-v4-flash" },
|
|
1035
|
+
];
|
|
1036
|
+
|
|
1037
|
+
let defaultSummaryModel: string | null = null;
|
|
1038
|
+
if (configuredSummaryModel !== undefined) {
|
|
1039
|
+
const spec = resolveHelperModelSelector(configuredSummaryModel, "summary model", summaryContext.model);
|
|
1040
|
+
// With no concrete value to show, list nothing so the curator sends Auto (the configured selector).
|
|
1041
|
+
if (!spec) return { summaryModels: [], defaultSummaryModel: configuredSummaryModel, preferredFallback: false };
|
|
1042
|
+
// The curator groups choices by provider, so `current` must be concrete. Unavailable models stay listed so failures are visible.
|
|
1043
|
+
defaultSummaryModel = `${spec.provider}/${spec.id}${spec.thinkingLevel ? `:${spec.thinkingLevel}` : ""}`;
|
|
1044
|
+
addModel(defaultSummaryModel);
|
|
1045
|
+
} else {
|
|
1046
|
+
for (const preferred of preferredDefaults) {
|
|
1047
|
+
const model = findModelWithProviderRouting(summaryContext.modelRegistry, preferred.provider, preferred.id);
|
|
1048
|
+
const value = model ? `${model.provider}/${model.id}` : null;
|
|
1049
|
+
if (value && availableValues.has(value)) {
|
|
1050
|
+
defaultSummaryModel = value;
|
|
1051
|
+
break;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return { summaryModels, defaultSummaryModel, preferredFallback: configuredSummaryModel === undefined };
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
function resolveSummaryForSubmit(
|
|
1059
|
+
payload: { selectedQueryIndices: number[]; summary?: string; summaryMeta?: SummaryMeta },
|
|
1060
|
+
resultsByIndex: Map<number, QueryResultData>,
|
|
1061
|
+
): { approvedSummary: string; summaryMeta: SummaryMeta } {
|
|
1062
|
+
const submittedSummary = typeof payload.summary === "string" ? payload.summary.trim() : "";
|
|
1063
|
+
if (submittedSummary.length > 0) {
|
|
1064
|
+
return {
|
|
1065
|
+
approvedSummary: submittedSummary,
|
|
1066
|
+
summaryMeta: normalizeSummaryMeta(payload.summaryMeta, submittedSummary),
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
const selected = filterByQueryIndices(payload.selectedQueryIndices, resultsByIndex).results;
|
|
1071
|
+
const fallbackResults = selected.length > 0 ? selected : orderedSearchResults(resultsByIndex);
|
|
1072
|
+
const deterministic = buildDeterministicSummary(fallbackResults);
|
|
1073
|
+
return {
|
|
1074
|
+
approvedSummary: deterministic.summary,
|
|
1075
|
+
summaryMeta: deterministic.meta,
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
function filterByQueryIndices(selectedQueryIndices: number[], results: Map<number, QueryResultData>) {
|
|
1080
|
+
const filteredResults: QueryResultData[] = [];
|
|
1081
|
+
const filteredUrls: string[] = [];
|
|
1082
|
+
for (const qi of selectedQueryIndices) {
|
|
1083
|
+
const r = results.get(qi);
|
|
1084
|
+
if (r) {
|
|
1085
|
+
filteredResults.push(r);
|
|
1086
|
+
for (const res of r.results) {
|
|
1087
|
+
if (!filteredUrls.includes(res.url)) filteredUrls.push(res.url);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
return { results: filteredResults, urls: filteredUrls };
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
function orderedSearchResults(resultsByIndex: Map<number, QueryResultData>): QueryResultData[] {
|
|
1095
|
+
return [...resultsByIndex.entries()]
|
|
1096
|
+
.sort(([leftIndex], [rightIndex]) => leftIndex - rightIndex)
|
|
1097
|
+
.map(([, result]) => result);
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function collectAllResultsAndUrls(resultsByIndex: Map<number, QueryResultData>) {
|
|
1101
|
+
const results = orderedSearchResults(resultsByIndex);
|
|
1102
|
+
const urls: string[] = [];
|
|
1103
|
+
for (const result of results) {
|
|
1104
|
+
for (const source of result.results) {
|
|
1105
|
+
if (!urls.includes(source.url)) urls.push(source.url);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
return { results, urls };
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
async function openCuratorBrowser(callId: string, pc: PendingCurate, ctx: ExtensionContext, searchesComplete = true): Promise<void> {
|
|
1112
|
+
if (pendingCurates.get(callId) !== pc) return;
|
|
1113
|
+
let handle: CuratorServerHandle | null = null;
|
|
1114
|
+
const sendCuratorFallbackUpdate = (message: string) => {
|
|
1115
|
+
if (!handle) return;
|
|
1116
|
+
pc.onUpdate?.({
|
|
1117
|
+
content: [{ type: "text", text: `${message}\nOpen manually: ${handle.url}` }],
|
|
1118
|
+
details: {
|
|
1119
|
+
phase: "curator-fallback",
|
|
1120
|
+
progress: searchesComplete ? 1 : 0.5,
|
|
1121
|
+
curatorUrl: handle.url,
|
|
1122
|
+
timeoutSeconds: pc.timeoutSeconds,
|
|
1123
|
+
shortcut: curateKey,
|
|
1124
|
+
browserOpenError: pc.browserOpenError,
|
|
1125
|
+
},
|
|
1126
|
+
});
|
|
1127
|
+
};
|
|
1128
|
+
try {
|
|
1129
|
+
pc.phase = "curating";
|
|
1130
|
+
|
|
1131
|
+
const searchAbort = new AbortController();
|
|
1132
|
+
const addSearchSignal = pc.signal
|
|
1133
|
+
? AbortSignal.any([pc.signal, searchAbort.signal])
|
|
1134
|
+
: searchAbort.signal;
|
|
1135
|
+
|
|
1136
|
+
const sessionToken = randomUUID();
|
|
1137
|
+
const { startCuratorServer } = await import("./curator-server.ts");
|
|
1138
|
+
handle = await startCuratorServer(
|
|
1139
|
+
{
|
|
1140
|
+
queries: pc.queryList,
|
|
1141
|
+
initialResultIndexCapacity: curatorResultIndexCapacity(pc.queryList.length),
|
|
1142
|
+
sessionToken,
|
|
1143
|
+
timeout: pc.timeoutSeconds,
|
|
1144
|
+
availableProviders: pc.availableProviders,
|
|
1145
|
+
defaultProvider: pc.defaultProvider,
|
|
1146
|
+
searchProvider: toCuratorProvider(pc.searchProvider) ?? "auto",
|
|
1147
|
+
summaryModels: pc.summaryModels,
|
|
1148
|
+
defaultSummaryModel: pc.defaultSummaryModel,
|
|
1149
|
+
},
|
|
1150
|
+
{
|
|
1151
|
+
async onSummarize(selectedQueryIndices, summarizeSignal, model, feedback) {
|
|
1152
|
+
return runWithProxy(pc.proxy, async () => {
|
|
1153
|
+
if (pendingCurates.get(callId) !== pc) throw new Error("Curator session is no longer active.");
|
|
1154
|
+
pc.onUpdate?.({
|
|
1155
|
+
content: [{ type: "text", text: "Generating summary draft..." }],
|
|
1156
|
+
details: { phase: "generating-summary", progress: 0.9, curatorUrl: pc.curatorUrl, timeoutSeconds: pc.timeoutSeconds, shortcut: curateKey },
|
|
1157
|
+
});
|
|
1158
|
+
const draft = await generateSummaryForSelectedIndices(
|
|
1159
|
+
selectedQueryIndices,
|
|
1160
|
+
pc.searchResults,
|
|
1161
|
+
pc.summaryContext,
|
|
1162
|
+
summarizeSignal,
|
|
1163
|
+
model,
|
|
1164
|
+
feedback,
|
|
1165
|
+
);
|
|
1166
|
+
if (pendingCurates.get(callId) !== pc) throw new Error("Curator session is no longer active.");
|
|
1167
|
+
pc.onUpdate?.({
|
|
1168
|
+
content: [{ type: "text", text: "Summary draft ready — waiting for approval..." }],
|
|
1169
|
+
details: { phase: "waiting-for-approval", progress: 1, curatorUrl: pc.curatorUrl, timeoutSeconds: pc.timeoutSeconds, shortcut: curateKey },
|
|
1170
|
+
});
|
|
1171
|
+
return draft;
|
|
1172
|
+
});
|
|
1173
|
+
},
|
|
1174
|
+
onSubmit(payload) {
|
|
1175
|
+
if (pendingCurates.get(callId) !== pc) return;
|
|
1176
|
+
if (payload.autoApproveRemainingSearches) curatorRunState.approveRemainingSearches();
|
|
1177
|
+
searchAbort.abort();
|
|
1178
|
+
const filtered = payload.selectedQueryIndices.length > 0
|
|
1179
|
+
? filterByQueryIndices(payload.selectedQueryIndices, pc.searchResults)
|
|
1180
|
+
: collectAllResultsAndUrls(pc.searchResults);
|
|
1181
|
+
const filteredInline = pc.allInlineContent.filter(c => filtered.urls.includes(c.url));
|
|
1182
|
+
const base: SearchReturnOptions = {
|
|
1183
|
+
queryList: filtered.results.map(r => r.query),
|
|
1184
|
+
results: filtered.results,
|
|
1185
|
+
urls: filtered.urls,
|
|
1186
|
+
includeContent: pc.includeContent,
|
|
1187
|
+
inlineContent: filteredInline.length > 0 ? filteredInline : undefined,
|
|
1188
|
+
curated: true,
|
|
1189
|
+
curatedFrom: pc.searchResults.size,
|
|
1190
|
+
proxy: pc.proxy,
|
|
1191
|
+
};
|
|
1192
|
+
if (!payload.rawResults) {
|
|
1193
|
+
const resolvedSummary = resolveSummaryForSubmit(payload, pc.searchResults);
|
|
1194
|
+
base.workflow = pc.workflow;
|
|
1195
|
+
base.approvedSummary = resolvedSummary.approvedSummary;
|
|
1196
|
+
base.summaryMeta = resolvedSummary.summaryMeta;
|
|
1197
|
+
}
|
|
1198
|
+
pc.finish(buildSearchReturn(base));
|
|
1199
|
+
closeCurator(callId);
|
|
1200
|
+
},
|
|
1201
|
+
onCancel(reason) {
|
|
1202
|
+
if (pendingCurates.get(callId) !== pc) return;
|
|
1203
|
+
searchAbort.abort();
|
|
1204
|
+
if (reason === "timeout") {
|
|
1205
|
+
const resolvedSummary = resolveSummaryForSubmit({ selectedQueryIndices: [], summary: undefined, summaryMeta: undefined }, pc.searchResults);
|
|
1206
|
+
const all = collectAllResultsAndUrls(pc.searchResults);
|
|
1207
|
+
const filteredInline = pc.allInlineContent.filter(c => all.urls.includes(c.url));
|
|
1208
|
+
pc.finish(buildSearchReturn({
|
|
1209
|
+
queryList: all.results.map(r => r.query),
|
|
1210
|
+
results: all.results,
|
|
1211
|
+
urls: all.urls,
|
|
1212
|
+
includeContent: pc.includeContent,
|
|
1213
|
+
inlineContent: filteredInline.length > 0 ? filteredInline : undefined,
|
|
1214
|
+
curated: true,
|
|
1215
|
+
curatedFrom: pc.searchResults.size,
|
|
1216
|
+
workflow: pc.workflow,
|
|
1217
|
+
approvedSummary: resolvedSummary.approvedSummary,
|
|
1218
|
+
summaryMeta: resolvedSummary.summaryMeta,
|
|
1219
|
+
proxy: pc.proxy,
|
|
1220
|
+
}));
|
|
1221
|
+
} else {
|
|
1222
|
+
const conn = activeCurators.get(callId)?.getConnectionState();
|
|
1223
|
+
pc.finish(buildCurationCancelledReturn(reason, {
|
|
1224
|
+
queries: orderedSearchResults(pc.searchResults),
|
|
1225
|
+
queryCount: pc.queryList.length,
|
|
1226
|
+
browserConnected: conn?.browserConnected,
|
|
1227
|
+
lastHeartbeatAgeMs: conn?.lastHeartbeatAgeMs,
|
|
1228
|
+
curatorUrl: pc.curatorUrl,
|
|
1229
|
+
browserOpenError: pc.browserOpenError,
|
|
1230
|
+
}));
|
|
1231
|
+
}
|
|
1232
|
+
closeCurator(callId);
|
|
1233
|
+
},
|
|
1234
|
+
onProviderChange(provider) {
|
|
1235
|
+
if (pendingCurates.get(callId) !== pc) return;
|
|
1236
|
+
const normalized = normalizeProviderInput(provider);
|
|
1237
|
+
if (!normalized || normalized === "auto" || Array.isArray(normalized)) return;
|
|
1238
|
+
pc.defaultProvider = normalized;
|
|
1239
|
+
pc.searchProvider = normalized;
|
|
1240
|
+
try {
|
|
1241
|
+
saveConfig({ provider: normalized });
|
|
1242
|
+
} catch (err) {
|
|
1243
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1244
|
+
console.error(`Failed to persist default provider: ${message}`);
|
|
1245
|
+
}
|
|
1246
|
+
},
|
|
1247
|
+
async onAddSearch(query, provider) {
|
|
1248
|
+
return runWithProxy(pc.proxy, async () => {
|
|
1249
|
+
if (pendingCurates.get(callId) !== pc) throw new Error("Curator session is no longer active.");
|
|
1250
|
+
const requestedProvider = resolveCuratorSearchProvider(provider, pc.searchProvider);
|
|
1251
|
+
const response = await search(query, {
|
|
1252
|
+
provider: requestedProvider,
|
|
1253
|
+
providerFromConfig: requestedProvider === pc.configDefaultProvider,
|
|
1254
|
+
numResults: pc.numResults,
|
|
1255
|
+
recencyFilter: pc.recencyFilter,
|
|
1256
|
+
domainFilter: pc.domainFilter,
|
|
1257
|
+
objective: pc.objective,
|
|
1258
|
+
includeContent: pc.includeContent,
|
|
1259
|
+
category: pc.category,
|
|
1260
|
+
signal: addSearchSignal,
|
|
1261
|
+
extensionContext: ctx,
|
|
1262
|
+
});
|
|
1263
|
+
if (pendingCurates.get(callId) !== pc) throw new Error("Curator session is no longer active.");
|
|
1264
|
+
if (response.inlineContent) pc.allInlineContent.push(...response.inlineContent);
|
|
1265
|
+
return toCuratorSearchEntries(response);
|
|
1266
|
+
});
|
|
1267
|
+
},
|
|
1268
|
+
onAddSearchResults(entries) {
|
|
1269
|
+
if (pendingCurates.get(callId) !== pc) return;
|
|
1270
|
+
for (const entry of entries) {
|
|
1271
|
+
pc.searchResults.set(entry.queryIndex, indexedCuratorEntryToQueryResult(entry));
|
|
1272
|
+
}
|
|
1273
|
+
},
|
|
1274
|
+
async onRewriteQuery(query, rewriteSignal) {
|
|
1275
|
+
return runWithProxy(pc.proxy, async () => {
|
|
1276
|
+
if (pendingCurates.get(callId) !== pc) throw new Error("Curator session is no longer active.");
|
|
1277
|
+
return rewriteSearchQuery(query, pc.summaryContext, rewriteSignal, readHelperModelKey("queryRewriteModel"));
|
|
1278
|
+
});
|
|
1279
|
+
},
|
|
1280
|
+
},
|
|
1281
|
+
);
|
|
1282
|
+
|
|
1283
|
+
if (pendingCurates.get(callId) !== pc) {
|
|
1284
|
+
handle.close();
|
|
1285
|
+
return;
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
activeCurators.set(callId, handle);
|
|
1289
|
+
pc.curatorUrl = handle.url;
|
|
1290
|
+
|
|
1291
|
+
for (const [qi, data] of pc.searchResults) {
|
|
1292
|
+
const slotIndex = pc.resultSlots.get(qi);
|
|
1293
|
+
if (data.error) {
|
|
1294
|
+
handle.pushError(qi, data.error, data.provider, { query: data.query, slotIndex });
|
|
1295
|
+
} else {
|
|
1296
|
+
handle.pushResult(qi, {
|
|
1297
|
+
answer: data.answer,
|
|
1298
|
+
results: data.results.map(r => ({ ...r, domain: extractDomain(r.url) })),
|
|
1299
|
+
provider: data.provider || pc.defaultProvider,
|
|
1300
|
+
query: data.query,
|
|
1301
|
+
slotIndex,
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
if (searchesComplete) handle.searchesDone();
|
|
1306
|
+
|
|
1307
|
+
pc.onUpdate?.({
|
|
1308
|
+
content: [{ type: "text", text: searchesComplete ? "Waiting for summary approval in browser..." : "Searches streaming to browser..." }],
|
|
1309
|
+
details: {
|
|
1310
|
+
phase: "curating",
|
|
1311
|
+
progress: searchesComplete ? 1 : 0.5,
|
|
1312
|
+
curatorUrl: handle.url,
|
|
1313
|
+
timeoutSeconds: pc.timeoutSeconds,
|
|
1314
|
+
shortcut: curateKey,
|
|
1315
|
+
},
|
|
1316
|
+
});
|
|
1317
|
+
|
|
1318
|
+
if (!shouldAutoOpenCuratorBrowser(loadConfig())) {
|
|
1319
|
+
sendCuratorFallbackUpdate("Search curator is running. Open the curator URL manually.");
|
|
1320
|
+
return;
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
const open = platform() === "darwin" ? await getGlimpseOpen() : null;
|
|
1324
|
+
if (open) {
|
|
1325
|
+
try {
|
|
1326
|
+
const win = openInGlimpse(open, handle.url, "Search Curator");
|
|
1327
|
+
glimpseWins.set(callId, win);
|
|
1328
|
+
win.on("closed", () => {
|
|
1329
|
+
if (glimpseWins.get(callId) === win) {
|
|
1330
|
+
glimpseWins.delete(callId);
|
|
1331
|
+
closeCurator(callId);
|
|
1332
|
+
}
|
|
1333
|
+
});
|
|
1334
|
+
return;
|
|
1335
|
+
} catch (err) {
|
|
1336
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1337
|
+
console.error(`Failed to open Glimpse curator window: ${message}`);
|
|
1338
|
+
glimpseWins.delete(callId);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
await openInBrowser(pi, handle.url);
|
|
1342
|
+
} catch (err) {
|
|
1343
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1344
|
+
console.error(`Failed to open curator UI: ${message}`);
|
|
1345
|
+
if (handle && activeCurators.get(callId) === handle && pendingCurates.get(callId) === pc) {
|
|
1346
|
+
pc.browserOpenError = message;
|
|
1347
|
+
sendCuratorFallbackUpdate("Search curator is running, but the browser did not open automatically.");
|
|
1348
|
+
} else if (pendingCurates.get(callId) === pc || (handle && activeCurators.get(callId) === handle)) {
|
|
1349
|
+
closeCurator(callId);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
pi.registerShortcut(curateKey, {
|
|
1355
|
+
description: "Review search results",
|
|
1356
|
+
handler: async (ctx) => {
|
|
1357
|
+
const entries = [...pendingCurates.entries()];
|
|
1358
|
+
if (entries.length === 0) return;
|
|
1359
|
+
const [callId, pc] = entries[entries.length - 1];
|
|
1360
|
+
|
|
1361
|
+
if (pc.phase === "searching") {
|
|
1362
|
+
pc.browserPromise = openCuratorBrowser(callId, pc, ctx, false);
|
|
1363
|
+
ctx.ui.notify("Opening curator — remaining searches will stream in", "info");
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
},
|
|
1367
|
+
});
|
|
1368
|
+
|
|
1369
|
+
pi.registerShortcut(activityKey, {
|
|
1370
|
+
description: "Toggle web search activity",
|
|
1371
|
+
handler: async (ctx) => {
|
|
1372
|
+
widgetVisible = !widgetVisible;
|
|
1373
|
+
if (widgetVisible) {
|
|
1374
|
+
widgetUnsubscribe = activityMonitor.onUpdate(() => updateWidget(ctx));
|
|
1375
|
+
updateWidget(ctx);
|
|
1376
|
+
} else {
|
|
1377
|
+
widgetUnsubscribe?.();
|
|
1378
|
+
widgetUnsubscribe = null;
|
|
1379
|
+
ctx.ui.setWidget("web-activity", undefined);
|
|
1380
|
+
}
|
|
1381
|
+
},
|
|
1382
|
+
});
|
|
1383
|
+
|
|
1384
|
+
// web_search calls a tool made, such as a codemode script, reach the tool_call
|
|
1385
|
+
// handlers before execute with parentToolCallId set; execute consumes the id.
|
|
1386
|
+
// Ids of calls a later handler blocked are dropped when the session changes.
|
|
1387
|
+
const nestedSearchCallIds = new Set<string>();
|
|
1388
|
+
if (webSearchEnabled) pi.on("tool_call", (event) => {
|
|
1389
|
+
if (event.parentToolCallId && event.toolName === toolNames.webSearch) nestedSearchCallIds.add(event.toolCallId);
|
|
1390
|
+
});
|
|
1391
|
+
|
|
1392
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1393
|
+
nestedSearchCallIds.clear();
|
|
1394
|
+
startSession(ctx);
|
|
1395
|
+
void showUpgradeNotice(ctx).catch((error) => console.error("Failed to show the pi-web-access upgrade notice:", error));
|
|
1396
|
+
});
|
|
1397
|
+
pi.on("session_tree", async (_event, ctx) => { nestedSearchCallIds.clear(); startSession(ctx); });
|
|
1398
|
+
|
|
1399
|
+
pi.on("session_shutdown", () => {
|
|
1400
|
+
nestedSearchCallIds.clear();
|
|
1401
|
+
endSession();
|
|
1402
|
+
closeCurator();
|
|
1403
|
+
// Unsubscribe before clear() to avoid callback with stale ctx
|
|
1404
|
+
widgetUnsubscribe?.();
|
|
1405
|
+
widgetUnsubscribe = null;
|
|
1406
|
+
activityMonitor.clear();
|
|
1407
|
+
widgetVisible = false;
|
|
1408
|
+
});
|
|
1409
|
+
|
|
1410
|
+
if (webSearchEnabled) pi.registerTool({
|
|
1411
|
+
name: toolNames.webSearch,
|
|
1412
|
+
label: "Web Search",
|
|
1413
|
+
prepareArguments: (args) => parseStringifiedArrays(args, ["queries", "domainFilter"]) as never,
|
|
1414
|
+
description:
|
|
1415
|
+
`Search the web for sources or answers.${getSearchContentEnabled ? ` Full results are stored for ${toolNames.getSearchContent} by responseId.` : ""} Prefer 2-4 varied queries.${retrievalOnlySuffix}`,
|
|
1416
|
+
promptSnippet:
|
|
1417
|
+
"Web research. Prefer {queries:[...]} with 2-4 varied angles; omit provider unless overriding the default.",
|
|
1418
|
+
parameters: Type.Object({
|
|
1419
|
+
query: Type.Optional(Type.String()),
|
|
1420
|
+
queries: Type.Optional(Type.Array(Type.String(), { description: "Run concurrently (up to three at a time); vary the angle" })),
|
|
1421
|
+
objective: Type.Optional(Type.String({ description: "Goal; Exa API, Parallel" })),
|
|
1422
|
+
numResults: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Default 5" })),
|
|
1423
|
+
includeContent: Type.Optional(Type.Boolean({ description: "Also fetch full page content" })),
|
|
1424
|
+
recencyFilter: Type.Optional(StringEnum(["day", "week", "month", "year"])),
|
|
1425
|
+
domainFilter: Type.Optional(Type.Array(Type.String(), { description: "Prefix - to exclude" })),
|
|
1426
|
+
category: Type.Optional(Type.String({ description: "Exa only, e.g. news" })),
|
|
1427
|
+
...(modelProviders.length > 0 ? { model: Type.Optional(Type.String({ description: `Model ID; needs provider ${modelProviders.join(", ")}` })) } : {}) as { model: TOptional<TString> },
|
|
1428
|
+
provider: Type.Optional(Type.String({ description: providerDescription })),
|
|
1429
|
+
// Both non-default workflows write a summary with a model, so the policy leaves nothing to choose.
|
|
1430
|
+
...(retrievalOnly.enabled ? {} : {
|
|
1431
|
+
workflow: Type.Optional(
|
|
1432
|
+
StringEnum(["none", "summary-review", "auto-summary"], {
|
|
1433
|
+
description: "Default none; summary-review opens the curator",
|
|
1434
|
+
}),
|
|
1435
|
+
),
|
|
1436
|
+
}) as { workflow: TOptional<TUnsafe<"none" | "summary-review" | "auto-summary">> },
|
|
1437
|
+
proxy: Type.Optional(Type.String({ description: "Proxy URL; omit by default; \"\" forces direct" })),
|
|
1438
|
+
}),
|
|
1439
|
+
outputSchema: webSearchOutputSchema,
|
|
1440
|
+
exposure: toolExposure,
|
|
1441
|
+
|
|
1442
|
+
async execute(callId, params, signal, onUpdate, ctx) {
|
|
1443
|
+
// Nested calls neither open the curator unless asked nor fetch content in the background.
|
|
1444
|
+
const nested = nestedSearchCallIds.delete(callId);
|
|
1445
|
+
return markToolError(await runWithProxy(typeof params.proxy === "string" ? params.proxy : undefined, async () => {
|
|
1446
|
+
const rawQueryList: unknown[] = Array.isArray(params.queries)
|
|
1447
|
+
? params.queries
|
|
1448
|
+
: (params.query !== undefined ? expandQueryString(params.query) : []);
|
|
1449
|
+
const queryList = normalizeQueryList(rawQueryList);
|
|
1450
|
+
// A saved default only adds a summary on top of the search, so the policy drops it; an explicit request is refused.
|
|
1451
|
+
const configWorkflow = retrievalOnly.enabled ? undefined : loadConfigForExtensionInit().workflow;
|
|
1452
|
+
// Checked before resolving, which turns summary-review into none when there is no UI.
|
|
1453
|
+
const requestedWorkflow = typeof params.workflow === "string" ? params.workflow.trim().toLowerCase() : "";
|
|
1454
|
+
if (retrievalOnly.enabled && (requestedWorkflow === "summary-review" || requestedWorkflow === "auto-summary")) {
|
|
1455
|
+
const error = retrievalOnlyError(`Workflow "${requestedWorkflow}"`, retrievalOnly).message;
|
|
1456
|
+
return { content: [{ type: "text", text: `Error: ${error}` }], details: { error } };
|
|
1457
|
+
}
|
|
1458
|
+
const workflow = nested && params.workflow === undefined
|
|
1459
|
+
? "none"
|
|
1460
|
+
: curatorRunState.resolve(params.workflow, configWorkflow, ctx?.hasUI !== false);
|
|
1461
|
+
const shouldCurate = workflow === "summary-review";
|
|
1462
|
+
const recencyFilter = normalizeRecencyFilter(params.recencyFilter);
|
|
1463
|
+
|
|
1464
|
+
if (queryList.length === 0) {
|
|
1465
|
+
return {
|
|
1466
|
+
content: [{ type: "text", text: "Error: No query provided. Use 'query' or 'queries' parameter." }],
|
|
1467
|
+
details: { error: "No query provided" },
|
|
1468
|
+
};
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
if (shouldCurate && !ctx) {
|
|
1472
|
+
return {
|
|
1473
|
+
content: [{ type: "text", text: "Error: Curation requires an active extension context." }],
|
|
1474
|
+
details: { error: "Missing extension context" },
|
|
1475
|
+
};
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
if (shouldCurate && params.model?.trim()) {
|
|
1479
|
+
return {
|
|
1480
|
+
content: [{ type: "text", text: "Error: model cannot be used with workflow \"summary-review\". Pass workflow \"none\" or \"auto-summary\" to search with a specific model." }],
|
|
1481
|
+
details: { error: "model is not supported with summary-review" },
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
if (shouldCurate) {
|
|
1486
|
+
closeCurator(callId);
|
|
1487
|
+
|
|
1488
|
+
let resolvePromise: (value: AgentToolResult<Record<string, unknown>>) => void = () => {};
|
|
1489
|
+
const promise = new Promise<AgentToolResult<Record<string, unknown>>>((resolve) => {
|
|
1490
|
+
resolvePromise = resolve;
|
|
1491
|
+
});
|
|
1492
|
+
const includeContent = params.includeContent ?? false;
|
|
1493
|
+
const searchResults = new Map<number, QueryResultData>();
|
|
1494
|
+
const resultSlots = new Map<number, number>();
|
|
1495
|
+
const allInlineContent: ExtractedContent[] = [];
|
|
1496
|
+
const searchAbort = new AbortController();
|
|
1497
|
+
const searchSignal = signal
|
|
1498
|
+
? AbortSignal.any([signal, searchAbort.signal])
|
|
1499
|
+
: searchAbort.signal;
|
|
1500
|
+
let cancelled = false;
|
|
1501
|
+
|
|
1502
|
+
const requestedProvider = resolveRequestedProvider(params.provider);
|
|
1503
|
+
const providerFromConfig = (parseProviderArgument(params.provider) ?? "auto") === "auto";
|
|
1504
|
+
const bootstrap = await loadCuratorBootstrap(requestedProvider, ctx, {
|
|
1505
|
+
numResults: params.numResults,
|
|
1506
|
+
recencyFilter,
|
|
1507
|
+
});
|
|
1508
|
+
const availableProviders = bootstrap.availableProviders;
|
|
1509
|
+
const defaultProvider = bootstrap.defaultProvider;
|
|
1510
|
+
const searchProvider = requestedProvider;
|
|
1511
|
+
const curatorTimeoutSeconds = bootstrap.timeoutSeconds;
|
|
1512
|
+
const curatorWorkflow: CuratorWorkflow = "summary-review";
|
|
1513
|
+
|
|
1514
|
+
const summaryContext: SummaryGenerationContext = {
|
|
1515
|
+
model: ctx.model,
|
|
1516
|
+
modelRegistry: ctx.modelRegistry,
|
|
1517
|
+
sessionManager: ctx.sessionManager,
|
|
1518
|
+
scopedModels: ctx.scopedModels,
|
|
1519
|
+
};
|
|
1520
|
+
const summaryModelChoices = await loadSummaryModelChoices(summaryContext);
|
|
1521
|
+
|
|
1522
|
+
const pc: PendingCurate = {
|
|
1523
|
+
phase: "searching",
|
|
1524
|
+
workflow: curatorWorkflow,
|
|
1525
|
+
summaryContext,
|
|
1526
|
+
searchResults,
|
|
1527
|
+
resultSlots,
|
|
1528
|
+
allInlineContent,
|
|
1529
|
+
queryList,
|
|
1530
|
+
includeContent,
|
|
1531
|
+
numResults: params.numResults,
|
|
1532
|
+
recencyFilter,
|
|
1533
|
+
domainFilter: params.domainFilter,
|
|
1534
|
+
category: params.category,
|
|
1535
|
+
objective: params.objective,
|
|
1536
|
+
availableProviders,
|
|
1537
|
+
defaultProvider,
|
|
1538
|
+
searchProvider,
|
|
1539
|
+
configDefaultProvider: providerFromConfig ? searchProvider : undefined,
|
|
1540
|
+
summaryModels: summaryModelChoices.summaryModels,
|
|
1541
|
+
defaultSummaryModel: summaryModelChoices.defaultSummaryModel,
|
|
1542
|
+
timeoutSeconds: curatorTimeoutSeconds,
|
|
1543
|
+
proxy: typeof params.proxy === "string" ? params.proxy : undefined,
|
|
1544
|
+
onUpdate: onUpdate as PendingCurate["onUpdate"],
|
|
1545
|
+
signal,
|
|
1546
|
+
abortSearches: () => {
|
|
1547
|
+
if (!searchAbort.signal.aborted) searchAbort.abort();
|
|
1548
|
+
},
|
|
1549
|
+
finish: () => {},
|
|
1550
|
+
cancel: () => {},
|
|
1551
|
+
};
|
|
1552
|
+
|
|
1553
|
+
const finish = (value: AgentToolResult<Record<string, unknown>>) => {
|
|
1554
|
+
if (cancelled) return;
|
|
1555
|
+
cancelled = true;
|
|
1556
|
+
pc.abortSearches();
|
|
1557
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1558
|
+
pendingCurates.delete(callId);
|
|
1559
|
+
resolvePromise(value);
|
|
1560
|
+
};
|
|
1561
|
+
|
|
1562
|
+
const cancel = (reason: "user" | "stale" = "stale") => {
|
|
1563
|
+
if (cancelled) return;
|
|
1564
|
+
const conn = activeCurators.get(callId)?.getConnectionState();
|
|
1565
|
+
finish(buildCurationCancelledReturn(reason, {
|
|
1566
|
+
queries: orderedSearchResults(searchResults),
|
|
1567
|
+
queryCount: queryList.length,
|
|
1568
|
+
browserConnected: conn?.browserConnected,
|
|
1569
|
+
lastHeartbeatAgeMs: conn?.lastHeartbeatAgeMs,
|
|
1570
|
+
curatorUrl: pc.curatorUrl,
|
|
1571
|
+
browserOpenError: pc.browserOpenError,
|
|
1572
|
+
}));
|
|
1573
|
+
};
|
|
1574
|
+
|
|
1575
|
+
pc.finish = finish;
|
|
1576
|
+
pc.cancel = cancel;
|
|
1577
|
+
|
|
1578
|
+
const onAbort = () => closeCurator(callId);
|
|
1579
|
+
pendingCurates.set(callId, pc);
|
|
1580
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1581
|
+
pc.browserPromise = openCuratorBrowser(callId, pc, ctx, false);
|
|
1582
|
+
|
|
1583
|
+
let completedSearches = 0;
|
|
1584
|
+
await runSearchQueries(queryList, async (query, qi) => {
|
|
1585
|
+
if (signal?.aborted || cancelled || searchAbort.signal.aborted) return;
|
|
1586
|
+
onUpdate?.({
|
|
1587
|
+
content: [{ type: "text", text: `Searching "${query}" (${completedSearches}/${queryList.length} complete)...` }],
|
|
1588
|
+
details: { phase: "searching", progress: completedSearches / queryList.length, currentQuery: query },
|
|
1589
|
+
});
|
|
1590
|
+
const requestedProvider = pc.searchProvider;
|
|
1591
|
+
try {
|
|
1592
|
+
const response = await search(query, {
|
|
1593
|
+
provider: requestedProvider,
|
|
1594
|
+
// A provider picked in the curator UI replaces this value and stays strict.
|
|
1595
|
+
providerFromConfig: requestedProvider === pc.configDefaultProvider,
|
|
1596
|
+
numResults: params.numResults,
|
|
1597
|
+
recencyFilter,
|
|
1598
|
+
domainFilter: params.domainFilter,
|
|
1599
|
+
objective: params.objective,
|
|
1600
|
+
includeContent: params.includeContent,
|
|
1601
|
+
category: params.category,
|
|
1602
|
+
signal: searchSignal,
|
|
1603
|
+
extensionContext: ctx,
|
|
1604
|
+
});
|
|
1605
|
+
if (signal?.aborted || cancelled || searchAbort.signal.aborted) return;
|
|
1606
|
+
if (response.inlineContent) allInlineContent.push(...response.inlineContent);
|
|
1607
|
+
const entries = toCuratorSearchEntries(response);
|
|
1608
|
+
const curator = activeCurators.get(callId);
|
|
1609
|
+
for (let entryIndex = 0; entryIndex < entries.length; entryIndex++) {
|
|
1610
|
+
const entry = entries[entryIndex];
|
|
1611
|
+
const resultIndex = curatorResultIndex(qi, entryIndex, queryList.length);
|
|
1612
|
+
const indexedEntry: IndexedCuratorSearchEntry = {
|
|
1613
|
+
...entry,
|
|
1614
|
+
queryIndex: resultIndex,
|
|
1615
|
+
query,
|
|
1616
|
+
};
|
|
1617
|
+
searchResults.set(resultIndex, indexedCuratorEntryToQueryResult(indexedEntry));
|
|
1618
|
+
resultSlots.set(resultIndex, qi);
|
|
1619
|
+
if (curator) {
|
|
1620
|
+
if (entry.error) {
|
|
1621
|
+
curator.pushError(resultIndex, entry.error, entry.provider, { query, slotIndex: qi });
|
|
1622
|
+
} else {
|
|
1623
|
+
curator.pushResult(resultIndex, { ...entry, query, slotIndex: qi });
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
} catch (err) {
|
|
1628
|
+
if (signal?.aborted || cancelled || searchAbort.signal.aborted) return;
|
|
1629
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1630
|
+
const failedProvider = toCuratorProvider(requestedProvider);
|
|
1631
|
+
searchResults.set(qi, { query, answer: "", results: [], error: message, provider: failedProvider });
|
|
1632
|
+
resultSlots.set(qi, qi);
|
|
1633
|
+
const curator = activeCurators.get(callId);
|
|
1634
|
+
if (curator) {
|
|
1635
|
+
curator.pushError(qi, message, failedProvider, { query, slotIndex: qi });
|
|
1636
|
+
}
|
|
1637
|
+
} finally {
|
|
1638
|
+
completedSearches++;
|
|
1639
|
+
if (!signal?.aborted && !cancelled && !searchAbort.signal.aborted) {
|
|
1640
|
+
onUpdate?.({
|
|
1641
|
+
content: [{ type: "text", text: `Completed ${completedSearches}/${queryList.length} searches.` }],
|
|
1642
|
+
details: { phase: "searching", progress: completedSearches / queryList.length, currentQuery: query },
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
});
|
|
1647
|
+
|
|
1648
|
+
if (signal?.aborted || cancelled || searchAbort.signal.aborted) {
|
|
1649
|
+
cancel();
|
|
1650
|
+
return promise;
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
await pc.browserPromise;
|
|
1654
|
+
const curator = activeCurators.get(callId);
|
|
1655
|
+
if (curator && !cancelled) {
|
|
1656
|
+
curator.searchesDone();
|
|
1657
|
+
if (pc.browserOpenError) {
|
|
1658
|
+
pc.onUpdate?.({
|
|
1659
|
+
content: [{ type: "text", text: `All searches complete. Open the curator manually: ${pc.curatorUrl}` }],
|
|
1660
|
+
details: {
|
|
1661
|
+
phase: "curator-fallback",
|
|
1662
|
+
progress: 1,
|
|
1663
|
+
curatorUrl: pc.curatorUrl,
|
|
1664
|
+
timeoutSeconds: pc.timeoutSeconds,
|
|
1665
|
+
shortcut: curateKey,
|
|
1666
|
+
browserOpenError: pc.browserOpenError,
|
|
1667
|
+
},
|
|
1668
|
+
});
|
|
1669
|
+
} else {
|
|
1670
|
+
pc.onUpdate?.({
|
|
1671
|
+
content: [{ type: "text", text: "All searches complete — waiting for summary approval in browser..." }],
|
|
1672
|
+
details: {
|
|
1673
|
+
phase: "curating",
|
|
1674
|
+
progress: 1,
|
|
1675
|
+
curatorUrl: pc.curatorUrl,
|
|
1676
|
+
timeoutSeconds: pc.timeoutSeconds,
|
|
1677
|
+
shortcut: curateKey,
|
|
1678
|
+
},
|
|
1679
|
+
});
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
return promise;
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
let summarize: WebSearchCallOptions["summarize"];
|
|
1687
|
+
if (workflow === "auto-summary") {
|
|
1688
|
+
summarize = async (searchResults) => {
|
|
1689
|
+
if (!ctx) {
|
|
1690
|
+
return {
|
|
1691
|
+
content: [{ type: "text", text: "Error: Auto-summary requires an active extension context." }],
|
|
1692
|
+
details: { error: "Missing extension context" },
|
|
1693
|
+
};
|
|
1694
|
+
}
|
|
1695
|
+
onUpdate?.({
|
|
1696
|
+
content: [{ type: "text", text: "Generating summary..." }],
|
|
1697
|
+
details: { phase: "generating-summary", progress: 1 },
|
|
1698
|
+
});
|
|
1699
|
+
const summaryContext: SummaryGenerationContext = {
|
|
1700
|
+
model: ctx.model,
|
|
1701
|
+
modelRegistry: ctx.modelRegistry,
|
|
1702
|
+
sessionManager: ctx.sessionManager,
|
|
1703
|
+
scopedModels: ctx.scopedModels,
|
|
1704
|
+
};
|
|
1705
|
+
const summaryModelChoices = await loadSummaryModelChoices(summaryContext);
|
|
1706
|
+
const generated = await generateSummaryDraft(
|
|
1707
|
+
searchResults,
|
|
1708
|
+
summaryContext,
|
|
1709
|
+
signal,
|
|
1710
|
+
summaryModelChoices.defaultSummaryModel ?? undefined,
|
|
1711
|
+
undefined,
|
|
1712
|
+
undefined,
|
|
1713
|
+
getSummaryGenerationDeadlineMs(),
|
|
1714
|
+
getSummaryInstructions(),
|
|
1715
|
+
{ preferredFallback: summaryModelChoices.preferredFallback },
|
|
1716
|
+
);
|
|
1717
|
+
return { approvedSummary: generated.summary, summaryMeta: generated.meta };
|
|
1718
|
+
};
|
|
1719
|
+
}
|
|
1720
|
+
return core.webSearch(params, signal, { extensionContext: ctx, onUpdate, summarize, awaitContent: nested, browserCookieConsent: browserCookieConsent(ctx) });
|
|
1721
|
+
}));
|
|
1722
|
+
},
|
|
1723
|
+
|
|
1724
|
+
renderCall(args, theme) {
|
|
1725
|
+
const input = args as { query?: unknown; queries?: unknown };
|
|
1726
|
+
const rawQueryList: unknown[] = Array.isArray(input.queries)
|
|
1727
|
+
? input.queries
|
|
1728
|
+
: (input.query !== undefined ? expandQueryString(input.query) : []);
|
|
1729
|
+
const queryList = normalizeQueryList(rawQueryList);
|
|
1730
|
+
if (queryList.length === 0) {
|
|
1731
|
+
return new Text(theme.fg("toolTitle", theme.bold("search ")) + theme.fg("error", "(no query)"), 0, 0);
|
|
1732
|
+
}
|
|
1733
|
+
if (queryList.length === 1) {
|
|
1734
|
+
const q = queryList[0];
|
|
1735
|
+
return new Text(theme.fg("toolTitle", theme.bold("search ")) + theme.fg("accent", `"${q}"`), 0, 0);
|
|
1736
|
+
}
|
|
1737
|
+
const lines = [theme.fg("toolTitle", theme.bold("search ")) + theme.fg("accent", `${queryList.length} queries`)];
|
|
1738
|
+
for (const q of queryList.slice(0, 5)) {
|
|
1739
|
+
lines.push(theme.fg("muted", ` "${q}"`));
|
|
1740
|
+
}
|
|
1741
|
+
if (queryList.length > 5) {
|
|
1742
|
+
lines.push(theme.fg("muted", ` ... and ${queryList.length - 5} more`));
|
|
1743
|
+
}
|
|
1744
|
+
return new Text(lines.join("\n"), 0, 0);
|
|
1745
|
+
},
|
|
1746
|
+
|
|
1747
|
+
renderResult(result, { expanded, isPartial }, theme) {
|
|
1748
|
+
type QueryDetail = {
|
|
1749
|
+
query: string;
|
|
1750
|
+
provider: string | null;
|
|
1751
|
+
answer: string | null;
|
|
1752
|
+
sources: Array<{ title: string; url: string }>;
|
|
1753
|
+
error: string | null;
|
|
1754
|
+
};
|
|
1755
|
+
const details = result.details as {
|
|
1756
|
+
queryCount?: number;
|
|
1757
|
+
successfulQueries?: number;
|
|
1758
|
+
totalResults?: number;
|
|
1759
|
+
error?: string;
|
|
1760
|
+
fetchId?: string;
|
|
1761
|
+
fetchUrls?: string[];
|
|
1762
|
+
phase?: string;
|
|
1763
|
+
progress?: number;
|
|
1764
|
+
currentQuery?: string;
|
|
1765
|
+
curated?: boolean;
|
|
1766
|
+
curatedFrom?: number;
|
|
1767
|
+
curatedQueries?: QueryDetail[];
|
|
1768
|
+
cancelled?: boolean;
|
|
1769
|
+
cancelReason?: string;
|
|
1770
|
+
browserConnected?: boolean;
|
|
1771
|
+
lastHeartbeatAgeMs?: number | null;
|
|
1772
|
+
cancelledQueries?: import("./render-search-error.ts").CancelledQueryDetail[];
|
|
1773
|
+
curatorUrl?: string;
|
|
1774
|
+
browserOpenError?: string;
|
|
1775
|
+
timeoutSeconds?: number;
|
|
1776
|
+
shortcut?: string;
|
|
1777
|
+
summary?: {
|
|
1778
|
+
text: string;
|
|
1779
|
+
workflow: SummaryWorkflow;
|
|
1780
|
+
model: string | null;
|
|
1781
|
+
durationMs: number;
|
|
1782
|
+
tokenEstimate: number;
|
|
1783
|
+
fallbackUsed: boolean;
|
|
1784
|
+
fallbackReason?: string;
|
|
1785
|
+
phase?: "summary-model" | "deterministic-fallback";
|
|
1786
|
+
edited?: boolean;
|
|
1787
|
+
};
|
|
1788
|
+
};
|
|
1789
|
+
|
|
1790
|
+
if (isPartial) {
|
|
1791
|
+
if (details?.phase === "curator-fallback") {
|
|
1792
|
+
const lines = [theme.fg("warning", "Open the search curator manually:")];
|
|
1793
|
+
if (details?.curatorUrl) lines.push(theme.fg("muted", ` ${details.curatorUrl}`));
|
|
1794
|
+
if (details?.browserOpenError) lines.push(theme.fg("dim", ` auto-open failed: ${details.browserOpenError}`));
|
|
1795
|
+
const timeout = typeof details?.timeoutSeconds === "number" ? details.timeoutSeconds : undefined;
|
|
1796
|
+
const shortcut = typeof details?.shortcut === "string" ? details.shortcut : curateKey;
|
|
1797
|
+
lines.push(theme.fg("dim", timeout ? ` auto-submits after ${timeout}s idle; ${shortcut} reopens` : ` ${shortcut} reopens`));
|
|
1798
|
+
return new Text(lines.join("\n"), 0, 0);
|
|
1799
|
+
}
|
|
1800
|
+
if (details?.phase === "curating" || details?.phase === "waiting-for-approval" || details?.phase === "generating-summary") {
|
|
1801
|
+
const phaseText = details?.phase === "generating-summary"
|
|
1802
|
+
? "generating summary draft..."
|
|
1803
|
+
: details?.phase === "waiting-for-approval"
|
|
1804
|
+
? "summary draft ready; approve in browser..."
|
|
1805
|
+
: "waiting for summary approval in browser...";
|
|
1806
|
+
const lines = [theme.fg("accent", phaseText)];
|
|
1807
|
+
if (details?.curatorUrl) {
|
|
1808
|
+
lines.push(theme.fg("muted", ` ${details.curatorUrl}`));
|
|
1809
|
+
}
|
|
1810
|
+
const timeout = typeof details?.timeoutSeconds === "number" ? details.timeoutSeconds : undefined;
|
|
1811
|
+
const shortcut = typeof details?.shortcut === "string" ? details.shortcut : curateKey;
|
|
1812
|
+
if (timeout) {
|
|
1813
|
+
lines.push(theme.fg("dim", ` auto-submits after ${timeout}s idle; ${shortcut} reopens`));
|
|
1814
|
+
} else {
|
|
1815
|
+
lines.push(theme.fg("dim", ` ${shortcut} reopens`));
|
|
1816
|
+
}
|
|
1817
|
+
return new Text(lines.join("\n"), 0, 0);
|
|
1818
|
+
}
|
|
1819
|
+
if (details?.phase === "searching") {
|
|
1820
|
+
const progress = details?.progress ?? 0;
|
|
1821
|
+
const bar = "\u2588".repeat(Math.floor(progress * 10)) + "\u2591".repeat(10 - Math.floor(progress * 10));
|
|
1822
|
+
const query = details?.currentQuery || "";
|
|
1823
|
+
const display = query.length > 40 ? query.slice(0, 37) + "..." : query;
|
|
1824
|
+
return new Text(theme.fg("accent", `[${bar}] ${display}`), 0, 0);
|
|
1825
|
+
}
|
|
1826
|
+
const progress = details?.progress ?? 0;
|
|
1827
|
+
const bar = "\u2588".repeat(Math.floor(progress * 10)) + "\u2591".repeat(10 - Math.floor(progress * 10));
|
|
1828
|
+
return new Text(theme.fg("accent", `[${bar}] ${details?.phase || "searching"}`), 0, 0);
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
if (details?.error) {
|
|
1832
|
+
// Expandable Ctrl+O diagnostics: which queries completed, per-query errors,
|
|
1833
|
+
// browser connection state, cancel reason. See render-search-error.ts.
|
|
1834
|
+
const plan = buildSearchErrorPlan(details as SearchErrorDetails);
|
|
1835
|
+
if (plan) return renderSearchErrorPlan(plan, expanded, theme);
|
|
1836
|
+
return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0);
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1839
|
+
let statusLine: string;
|
|
1840
|
+
const queryInfo = details?.queryCount === 1 ? "" : `${details?.successfulQueries}/${details?.queryCount} queries, `;
|
|
1841
|
+
statusLine = theme.fg("success", `${queryInfo}${details?.totalResults ?? 0} sources`);
|
|
1842
|
+
if (details?.curated && details?.curatedFrom) {
|
|
1843
|
+
statusLine += theme.fg("muted", ` (${details.queryCount}/${details.curatedFrom} queries curated)`);
|
|
1844
|
+
}
|
|
1845
|
+
if (details?.fetchId && details?.fetchUrls) {
|
|
1846
|
+
statusLine += theme.fg("muted", ` (fetching ${details.fetchUrls.length} URLs)`);
|
|
1847
|
+
} else if (details?.fetchId) {
|
|
1848
|
+
statusLine += theme.fg("muted", " (content ready)");
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
// Build expanded lines first so collapsed view can reference total count
|
|
1852
|
+
const lines = [statusLine];
|
|
1853
|
+
if (details?.summary?.text) {
|
|
1854
|
+
lines.push("");
|
|
1855
|
+
lines.push(theme.fg("accent", `── Summary (${details.summary.workflow}) ` + "─".repeat(32)));
|
|
1856
|
+
lines.push("");
|
|
1857
|
+
for (const line of details.summary.text.split("\n")) {
|
|
1858
|
+
lines.push(` ${line}`);
|
|
1859
|
+
}
|
|
1860
|
+
lines.push("");
|
|
1861
|
+
const metaParts = [
|
|
1862
|
+
details.summary.model ? `model=${details.summary.model}` : "model=deterministic",
|
|
1863
|
+
`duration=${details.summary.durationMs}ms`,
|
|
1864
|
+
`tokens~${details.summary.tokenEstimate}`,
|
|
1865
|
+
details.summary.fallbackUsed ? "fallback=true" : "fallback=false",
|
|
1866
|
+
details.summary.phase ? `phase=${details.summary.phase}` : "",
|
|
1867
|
+
details.summary.edited ? "edited=true" : "edited=false",
|
|
1868
|
+
];
|
|
1869
|
+
if (details.summary.fallbackReason) {
|
|
1870
|
+
metaParts.push(`reason=${details.summary.fallbackReason}`);
|
|
1871
|
+
}
|
|
1872
|
+
lines.push(theme.fg("dim", " " + metaParts.filter(Boolean).join(" · ")));
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
const queryDetails = details?.curatedQueries;
|
|
1876
|
+
if (queryDetails?.length) {
|
|
1877
|
+
const kept = queryDetails.length;
|
|
1878
|
+
const from = details?.curatedFrom ?? kept;
|
|
1879
|
+
lines.push("");
|
|
1880
|
+
lines.push(theme.fg("accent", `\u2500\u2500 Curated Results (${kept} of ${from} queries kept) ` + "\u2500".repeat(24)));
|
|
1881
|
+
|
|
1882
|
+
for (const cq of queryDetails) {
|
|
1883
|
+
lines.push("");
|
|
1884
|
+
const dq = cq.query.length > 65 ? cq.query.slice(0, 62) + "..." : cq.query;
|
|
1885
|
+
const providerLabel = cq.provider ? ` (${cq.provider})` : "";
|
|
1886
|
+
lines.push(theme.fg("accent", ` "${dq}"${providerLabel}`));
|
|
1887
|
+
|
|
1888
|
+
if (cq.error) {
|
|
1889
|
+
lines.push(theme.fg("error", ` ${cq.error}`));
|
|
1890
|
+
} else if (cq.answer) {
|
|
1891
|
+
lines.push("");
|
|
1892
|
+
for (const line of cq.answer.split("\n")) {
|
|
1893
|
+
lines.push(` ${line}`);
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
if (cq.sources.length > 0) {
|
|
1898
|
+
lines.push("");
|
|
1899
|
+
for (const s of cq.sources) {
|
|
1900
|
+
const domain = s.url.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
|
|
1901
|
+
const title = s.title.length > 50 ? s.title.slice(0, 47) + "..." : s.title;
|
|
1902
|
+
lines.push(theme.fg("muted", ` \u25b8 ${title}`) + theme.fg("dim", ` \u00b7 ${domain}`));
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
lines.push("");
|
|
1907
|
+
} else {
|
|
1908
|
+
const textContent = result.content.find((c) => c.type === "text")?.text || "";
|
|
1909
|
+
const preview = textContent.length > 500 ? textContent.slice(0, 500) + "..." : textContent;
|
|
1910
|
+
for (const line of preview.split("\n")) {
|
|
1911
|
+
lines.push(theme.fg("dim", line));
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
if (details?.fetchUrls && details.fetchUrls.length > 0) {
|
|
1916
|
+
if (details.curated) {
|
|
1917
|
+
lines.push(theme.fg("muted", `Fetching ${details.fetchUrls.length} URLs in background`));
|
|
1918
|
+
} else {
|
|
1919
|
+
lines.push(theme.fg("muted", "Fetching:"));
|
|
1920
|
+
for (const u of details.fetchUrls.slice(0, 5)) {
|
|
1921
|
+
const display = u.length > 60 ? u.slice(0, 57) + "..." : u;
|
|
1922
|
+
lines.push(theme.fg("dim", " " + display));
|
|
1923
|
+
}
|
|
1924
|
+
if (details.fetchUrls.length > 5) {
|
|
1925
|
+
lines.push(theme.fg("dim", ` ... and ${details.fetchUrls.length - 5} more`));
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
const totalLines = lines.length;
|
|
1931
|
+
|
|
1932
|
+
if (!expanded) {
|
|
1933
|
+
const box = new Box(1, 0);
|
|
1934
|
+
box.addChild(new Text(statusLine, 0, 0));
|
|
1935
|
+
|
|
1936
|
+
let collapsedLines = 1; // statusLine
|
|
1937
|
+
const summaryPreview = details?.summary?.text?.trim() || "";
|
|
1938
|
+
if (summaryPreview) {
|
|
1939
|
+
const preview = summaryPreview.length > 120 ? summaryPreview.slice(0, 117) + "..." : summaryPreview;
|
|
1940
|
+
box.addChild(new Text(theme.fg("dim", preview), 0, 0));
|
|
1941
|
+
collapsedLines++;
|
|
1942
|
+
} else if (details?.curatedQueries?.length) {
|
|
1943
|
+
for (const cq of details.curatedQueries.slice(0, 3)) {
|
|
1944
|
+
const dq = cq.query.length > 55 ? cq.query.slice(0, 52) + "..." : cq.query;
|
|
1945
|
+
const srcCount = cq.sources?.length ?? 0;
|
|
1946
|
+
const suffix = cq.error ? theme.fg("error", " (error)") : theme.fg("dim", ` · ${srcCount} sources`);
|
|
1947
|
+
box.addChild(new Text(theme.fg("accent", ` "${dq}"`) + suffix, 0, 0));
|
|
1948
|
+
collapsedLines++;
|
|
1949
|
+
}
|
|
1950
|
+
if (details.curatedQueries.length > 3) {
|
|
1951
|
+
box.addChild(new Text(theme.fg("dim", ` ... and ${details.curatedQueries.length - 3} more`), 0, 0));
|
|
1952
|
+
collapsedLines++;
|
|
1953
|
+
}
|
|
1954
|
+
} else {
|
|
1955
|
+
const textContent = result.content.find((c) => c.type === "text")?.text || "";
|
|
1956
|
+
const firstContentLine = textContent.split("\n").find(l => {
|
|
1957
|
+
const t = l.trim();
|
|
1958
|
+
return t && !t.startsWith("[") && !t.startsWith("#") && !t.startsWith("---");
|
|
1959
|
+
});
|
|
1960
|
+
const fallbackLine = (firstContentLine?.trim() || "").replace(/\*\*/g, "");
|
|
1961
|
+
if (fallbackLine) {
|
|
1962
|
+
const preview = fallbackLine.length > 120 ? fallbackLine.slice(0, 117) + "..." : fallbackLine;
|
|
1963
|
+
box.addChild(new Text(theme.fg("dim", preview), 0, 0));
|
|
1964
|
+
collapsedLines++;
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
const moreLines = Math.max(0, totalLines - collapsedLines);
|
|
1968
|
+
if (moreLines > 0) {
|
|
1969
|
+
box.addChild(new Text(theme.fg("muted", `\n... (${moreLines} more lines, ${totalLines} total, ctrl+o to expand)`), 0, 0));
|
|
1970
|
+
}
|
|
1971
|
+
return box;
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
return new Text(lines.join("\n"), 0, 0);
|
|
1975
|
+
},
|
|
1976
|
+
});
|
|
1977
|
+
|
|
1978
|
+
if (sourceCheckEnabled) pi.registerTool({
|
|
1979
|
+
name: toolNames.sourceCheck,
|
|
1980
|
+
label: "Source Check",
|
|
1981
|
+
description: "Gather cited web passages about a claim for manual review.",
|
|
1982
|
+
promptSnippet: "Gather source evidence with passage citations for a claim.",
|
|
1983
|
+
parameters: Type.Object({
|
|
1984
|
+
claim: Type.String({ description: "Assertion to check" }),
|
|
1985
|
+
queries: Type.Optional(Type.Array(Type.String(), { description: "Default: the claim" })),
|
|
1986
|
+
numResults: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Default 5" })),
|
|
1987
|
+
fetchContent: Type.Optional(Type.Boolean({ description: "Fetch top 5 pages for exact passages" })),
|
|
1988
|
+
recencyFilter: Type.Optional(StringEnum(["day", "week", "month", "year"])),
|
|
1989
|
+
domainFilter: Type.Optional(Type.Array(Type.String(), { description: "Prefix - to exclude" })),
|
|
1990
|
+
provider: Type.Optional(Type.String({ description: providerDescription })),
|
|
1991
|
+
proxy: Type.Optional(Type.String({ description: "Proxy URL; omit by default; \"\" forces direct" })),
|
|
1992
|
+
}),
|
|
1993
|
+
exposure: toolExposure,
|
|
1994
|
+
async execute(_callId, params, signal, _onUpdate, ctx) {
|
|
1995
|
+
return markToolError(await core.sourceCheck(params, signal, { extensionContext: ctx }));
|
|
1996
|
+
},
|
|
1997
|
+
});
|
|
1998
|
+
|
|
1999
|
+
if (fetchContentEnabled) pi.registerTool({
|
|
2000
|
+
name: toolNames.fetchContent,
|
|
2001
|
+
label: "Fetch Content",
|
|
2002
|
+
description: `Fetch web pages, PDFs, GitHub repos, images, YouTube and local video, as the mode allows. ${fetchContentStorageNote}${retrievalOnlySuffix}`,
|
|
2003
|
+
promptSnippet:
|
|
2004
|
+
`Use to fetch URL content, direct images, GitHub repos, and videos.${fetchModeConfig.allowedModes.includes("extract") ? ' For specific values (a price, version, date or limit), use mode "extract" with fields instead of reading the whole page.' : ""}`,
|
|
2005
|
+
parameters: Type.Object({
|
|
2006
|
+
url: Type.Optional(Type.String()),
|
|
2007
|
+
urls: Type.Optional(Type.Array(Type.String())),
|
|
2008
|
+
forceClone: Type.Optional(Type.Boolean({ description: "Clone GitHub repos over the size limit" })),
|
|
2009
|
+
// prompt and model only steer model routes (answer mode, video analysis), which the policy closes.
|
|
2010
|
+
...(retrievalOnly.enabled ? {} : {
|
|
2011
|
+
prompt: Type.Optional(Type.String({
|
|
2012
|
+
description: fetchModeConfig.allowedModes.includes("answer")
|
|
2013
|
+
? "Question for video analysis or answer mode"
|
|
2014
|
+
: "Question for video analysis",
|
|
2015
|
+
})),
|
|
2016
|
+
}) as { prompt: TOptional<TString> },
|
|
2017
|
+
mode: Type.Optional(StringEnum(fetchModeConfig.allowedModes, {
|
|
2018
|
+
description: `${fetchModeDescription}.`,
|
|
2019
|
+
})),
|
|
2020
|
+
...(fetchModeConfig.allowedModes.includes("answer") ? {
|
|
2021
|
+
answerModel: Type.Optional(Type.String({
|
|
2022
|
+
description: "provider/model-id for answer mode",
|
|
2023
|
+
})),
|
|
2024
|
+
} : {}),
|
|
2025
|
+
...(fetchModeConfig.allowedModes.includes("extract") ? {
|
|
2026
|
+
fields: Type.Optional(Type.Record(Type.String(), Type.String(), {
|
|
2027
|
+
description: "For extract: name → \"type\" or \"type: what to find\"; types: text, number, integer, date, time, datetime, duration[.unit], list[.number|.date]",
|
|
2028
|
+
})),
|
|
2029
|
+
} : {}),
|
|
2030
|
+
timestamp: Type.Optional(Type.String({
|
|
2031
|
+
description: "Video frame time ('1:23:45') or range ('23:41-25:00'); needs ffmpeg",
|
|
2032
|
+
})),
|
|
2033
|
+
frames: Type.Optional(Type.Integer({
|
|
2034
|
+
minimum: 1,
|
|
2035
|
+
maximum: 12,
|
|
2036
|
+
description: "Frames over a range, 5s apart from one time, or over the video",
|
|
2037
|
+
})),
|
|
2038
|
+
...(retrievalOnly.enabled ? {} : { model: Type.Optional(Type.String({ description: "Gemini model for video analysis" })) }) as { model: TOptional<TString> },
|
|
2039
|
+
auth: Type.Optional(Type.Union([Type.String(), Type.Boolean()], {
|
|
2040
|
+
description: "authFetch profile name, or true for the only one",
|
|
2041
|
+
})),
|
|
2042
|
+
proxy: Type.Optional(Type.String({ description: "Proxy URL; omit by default; \"\" forces direct" })),
|
|
2043
|
+
redirects: Type.Optional(StringEnum(["same-origin"], {
|
|
2044
|
+
description: "Refuse cross-origin redirects",
|
|
2045
|
+
})),
|
|
2046
|
+
}),
|
|
2047
|
+
outputSchema: fetchContentOutputSchema,
|
|
2048
|
+
exposure: toolExposure,
|
|
2049
|
+
|
|
2050
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx): Promise<AgentToolResult<Record<string, unknown>>> {
|
|
2051
|
+
return markToolError(await core.fetchContent(params, signal, { extensionContext: ctx, onUpdate, browserCookieConsent: browserCookieConsent(ctx) }));
|
|
2052
|
+
},
|
|
2053
|
+
|
|
2054
|
+
renderCall(args, theme) {
|
|
2055
|
+
let normalized: ReturnType<typeof normalizeFetchContentParams>;
|
|
2056
|
+
try {
|
|
2057
|
+
normalized = normalizeFetchContentParams(args);
|
|
2058
|
+
} catch {
|
|
2059
|
+
return new Text(theme.fg("toolTitle", theme.bold("fetch ")) + theme.fg("error", "(invalid parameters)"), 0, 0);
|
|
2060
|
+
}
|
|
2061
|
+
if (normalized.problems.length > 0) {
|
|
2062
|
+
return new Text(theme.fg("toolTitle", theme.bold("fetch ")) + theme.fg("error", "(invalid parameters)"), 0, 0);
|
|
2063
|
+
}
|
|
2064
|
+
const { urlList, options } = normalized;
|
|
2065
|
+
const { prompt, timestamp, frames, model, mode, answerModel, auth } = options;
|
|
2066
|
+
if (urlList.length === 0) {
|
|
2067
|
+
return new Text(theme.fg("toolTitle", theme.bold("fetch ")) + theme.fg("error", "(no URL)"), 0, 0);
|
|
2068
|
+
}
|
|
2069
|
+
const lines: string[] = [];
|
|
2070
|
+
if (urlList.length === 1) {
|
|
2071
|
+
lines.push(theme.fg("toolTitle", theme.bold("fetch ")) + theme.fg("accent", urlList[0]));
|
|
2072
|
+
} else {
|
|
2073
|
+
lines.push(theme.fg("toolTitle", theme.bold("fetch ")) + theme.fg("accent", `${urlList.length} URLs`));
|
|
2074
|
+
for (const u of urlList.slice(0, 5)) {
|
|
2075
|
+
lines.push(theme.fg("muted", " " + u));
|
|
2076
|
+
}
|
|
2077
|
+
if (urlList.length > 5) {
|
|
2078
|
+
lines.push(theme.fg("muted", ` ... and ${urlList.length - 5} more`));
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
if (mode && mode !== "readable") {
|
|
2082
|
+
lines.push(theme.fg("dim", " mode: ") + theme.fg("warning", mode));
|
|
2083
|
+
}
|
|
2084
|
+
if (timestamp) {
|
|
2085
|
+
lines.push(theme.fg("dim", " timestamp: ") + theme.fg("warning", timestamp));
|
|
2086
|
+
}
|
|
2087
|
+
if (typeof frames === "number") {
|
|
2088
|
+
lines.push(theme.fg("dim", " frames: ") + theme.fg("warning", String(frames)));
|
|
2089
|
+
}
|
|
2090
|
+
if (prompt) {
|
|
2091
|
+
const display = prompt.length > 250 ? prompt.slice(0, 247) + "..." : prompt;
|
|
2092
|
+
lines.push(theme.fg("dim", " prompt: ") + theme.fg("muted", `"${display}"`));
|
|
2093
|
+
}
|
|
2094
|
+
if (model) {
|
|
2095
|
+
lines.push(theme.fg("dim", " model: ") + theme.fg("warning", model));
|
|
2096
|
+
}
|
|
2097
|
+
if (answerModel) {
|
|
2098
|
+
lines.push(theme.fg("dim", " answer model: ") + theme.fg("warning", answerModel));
|
|
2099
|
+
}
|
|
2100
|
+
if (auth !== undefined) {
|
|
2101
|
+
lines.push(theme.fg("dim", " auth: ") + theme.fg("warning", auth === true ? "true" : auth));
|
|
2102
|
+
}
|
|
2103
|
+
return new Text(lines.join("\n"), 0, 0);
|
|
2104
|
+
},
|
|
2105
|
+
|
|
2106
|
+
renderResult(result, { expanded, isPartial }, theme) {
|
|
2107
|
+
const details = result.details as {
|
|
2108
|
+
urlCount?: number;
|
|
2109
|
+
successful?: number;
|
|
2110
|
+
totalChars?: number;
|
|
2111
|
+
error?: string;
|
|
2112
|
+
title?: string;
|
|
2113
|
+
truncated?: boolean;
|
|
2114
|
+
responseId?: string;
|
|
2115
|
+
phase?: string;
|
|
2116
|
+
progress?: number;
|
|
2117
|
+
hasImage?: boolean;
|
|
2118
|
+
imageCount?: number;
|
|
2119
|
+
prompt?: string;
|
|
2120
|
+
timestamp?: string;
|
|
2121
|
+
frames?: number;
|
|
2122
|
+
duration?: number;
|
|
2123
|
+
};
|
|
2124
|
+
|
|
2125
|
+
if (isPartial) {
|
|
2126
|
+
const progress = details?.progress ?? 0;
|
|
2127
|
+
const bar = "\u2588".repeat(Math.floor(progress * 10)) + "\u2591".repeat(10 - Math.floor(progress * 10));
|
|
2128
|
+
return new Text(theme.fg("accent", `[${bar}] ${details?.phase || "fetching"}`), 0, 0);
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
if (details?.error) {
|
|
2132
|
+
const fd = details as typeof details & { urls?: string[] };
|
|
2133
|
+
const extras: string[] = [];
|
|
2134
|
+
if (typeof fd.urlCount === "number" || typeof fd.successful === "number") {
|
|
2135
|
+
extras.push(`urls: ${fd.successful ?? 0}/${fd.urlCount ?? 0} succeeded`);
|
|
2136
|
+
}
|
|
2137
|
+
if (fd.responseId) extras.push(`response id: ${fd.responseId}`);
|
|
2138
|
+
if (fd.urls && fd.urls.length > 0) {
|
|
2139
|
+
for (const u of fd.urls.slice(0, 8)) extras.push(` \u25b8 ${u}`);
|
|
2140
|
+
if (fd.urls.length > 8) extras.push(` ... and ${fd.urls.length - 8} more`);
|
|
2141
|
+
}
|
|
2142
|
+
const plan = buildSearchErrorPlan({ error: details.error, extraLines: extras });
|
|
2143
|
+
if (plan) return renderSearchErrorPlan(plan, expanded, theme);
|
|
2144
|
+
return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0);
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
if (details?.urlCount === 1) {
|
|
2148
|
+
const title = details?.title || "Untitled";
|
|
2149
|
+
const imgCount = details?.imageCount ?? (details?.hasImage ? 1 : 0);
|
|
2150
|
+
const imageBadge = imgCount > 1
|
|
2151
|
+
? theme.fg("accent", ` [${imgCount} images]`)
|
|
2152
|
+
: imgCount === 1
|
|
2153
|
+
? theme.fg("accent", " [image]")
|
|
2154
|
+
: "";
|
|
2155
|
+
let statusLine = theme.fg("success", title) + theme.fg("muted", ` (${details?.totalChars ?? 0} chars)`) + imageBadge;
|
|
2156
|
+
if (details?.truncated) {
|
|
2157
|
+
statusLine += theme.fg("warning", " [truncated]");
|
|
2158
|
+
}
|
|
2159
|
+
if (typeof details?.duration === "number") {
|
|
2160
|
+
statusLine += theme.fg("muted", ` | ${formatSeconds(Math.floor(details.duration))} total`);
|
|
2161
|
+
}
|
|
2162
|
+
const textContent = result.content.find((c) => c.type === "text")?.text || "";
|
|
2163
|
+
if (!expanded) {
|
|
2164
|
+
const brief = textContent.length > 200 ? textContent.slice(0, 200) + "..." : textContent;
|
|
2165
|
+
return new Text(statusLine + "\n" + theme.fg("dim", brief), 0, 0);
|
|
2166
|
+
}
|
|
2167
|
+
const lines = [statusLine];
|
|
2168
|
+
if (details?.prompt) {
|
|
2169
|
+
const display = details.prompt.length > 250 ? details.prompt.slice(0, 247) + "..." : details.prompt;
|
|
2170
|
+
lines.push(theme.fg("dim", ` prompt: "${display}"`));
|
|
2171
|
+
}
|
|
2172
|
+
if (details?.timestamp) {
|
|
2173
|
+
lines.push(theme.fg("dim", ` timestamp: ${details.timestamp}`));
|
|
2174
|
+
}
|
|
2175
|
+
if (typeof details?.frames === "number") {
|
|
2176
|
+
lines.push(theme.fg("dim", ` frames: ${details.frames}`));
|
|
2177
|
+
}
|
|
2178
|
+
const preview = textContent.length > 500 ? textContent.slice(0, 500) + "..." : textContent;
|
|
2179
|
+
lines.push(theme.fg("dim", preview));
|
|
2180
|
+
return new Text(lines.join("\n"), 0, 0);
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
const countColor = (details?.successful ?? 0) > 0 ? "success" : "error";
|
|
2184
|
+
const statusLine = theme.fg(countColor, `${details?.successful}/${details?.urlCount} URLs`) + theme.fg("muted", getSearchContentEnabled ? " (content stored)" : " (content fetched)");
|
|
2185
|
+
if (!expanded) {
|
|
2186
|
+
return new Text(statusLine, 0, 0);
|
|
2187
|
+
}
|
|
2188
|
+
const textContent = result.content.find((c) => c.type === "text")?.text || "";
|
|
2189
|
+
const preview = textContent.length > 500 ? textContent.slice(0, 500) + "..." : textContent;
|
|
2190
|
+
return new Text(statusLine + "\n" + theme.fg("dim", preview), 0, 0);
|
|
2191
|
+
},
|
|
2192
|
+
});
|
|
2193
|
+
|
|
2194
|
+
if (getSearchContentEnabled) {
|
|
2195
|
+
const maxInlineContentChars = getMaxInlineContentChars(initConfig);
|
|
2196
|
+
pi.registerTool({
|
|
2197
|
+
name: toolNames.getSearchContent,
|
|
2198
|
+
label: "Get Search Content",
|
|
2199
|
+
description: `Page through or search stored content from ${storedContentSources} by responseId.`,
|
|
2200
|
+
promptSnippet:
|
|
2201
|
+
`Use after ${storedContentSources} to read stored content; findText finds passages without paging.`,
|
|
2202
|
+
parameters: Type.Object({
|
|
2203
|
+
responseId: Type.String(),
|
|
2204
|
+
query: Type.Optional(Type.String()),
|
|
2205
|
+
queryIndex: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
2206
|
+
url: Type.Optional(Type.String()),
|
|
2207
|
+
urlIndex: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
2208
|
+
offset: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
2209
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: maxInlineContentChars, description: "Characters, default the maximum" })),
|
|
2210
|
+
findText: Type.Optional(Type.Union([
|
|
2211
|
+
Type.String({ minLength: 1, maxLength: 500 }),
|
|
2212
|
+
Type.Array(Type.String({ minLength: 1, maxLength: 500 }), { minItems: 1, maxItems: 10 }),
|
|
2213
|
+
], { description: "Find passages instead of paging" })),
|
|
2214
|
+
findMode: Type.Optional(StringEnum(["exact", "case-insensitive", "fuzzy"])),
|
|
2215
|
+
}),
|
|
2216
|
+
exposure: toolExposure,
|
|
2217
|
+
|
|
2218
|
+
async execute(_toolCallId, rawParams): Promise<AgentToolResult<Record<string, unknown>>> {
|
|
2219
|
+
return markToolError(await core.getSearchContent(rawParams));
|
|
2220
|
+
},
|
|
2221
|
+
|
|
2222
|
+
renderCall(args, theme) {
|
|
2223
|
+
const { responseId, query, queryIndex, url, urlIndex, offset, findText } = args as {
|
|
2224
|
+
responseId: string;
|
|
2225
|
+
query?: string;
|
|
2226
|
+
queryIndex?: number;
|
|
2227
|
+
url?: string;
|
|
2228
|
+
urlIndex?: number;
|
|
2229
|
+
offset?: number;
|
|
2230
|
+
findText?: string | string[];
|
|
2231
|
+
};
|
|
2232
|
+
let target = "";
|
|
2233
|
+
if (query) target = `query="${query}"`;
|
|
2234
|
+
else if (queryIndex !== undefined) target = `queryIndex=${queryIndex}`;
|
|
2235
|
+
else if (url) target = url.length > 30 ? url.slice(0, 27) + "..." : url;
|
|
2236
|
+
else if (urlIndex !== undefined) target = `urlIndex=${urlIndex}`;
|
|
2237
|
+
if (offset !== undefined) target += target ? ` @ ${offset}` : `offset=${offset}`;
|
|
2238
|
+
if (findText !== undefined) {
|
|
2239
|
+
const queries = Array.isArray(findText) ? findText : [findText];
|
|
2240
|
+
target += `${target ? " · " : ""}find ${queries.length}`;
|
|
2241
|
+
}
|
|
2242
|
+
return new Text(theme.fg("toolTitle", theme.bold("get_content ")) + theme.fg("accent", target || responseId.slice(0, 8)), 0, 0);
|
|
2243
|
+
},
|
|
2244
|
+
|
|
2245
|
+
renderResult(result, { expanded }, theme) {
|
|
2246
|
+
const details = result.details as {
|
|
2247
|
+
error?: string;
|
|
2248
|
+
query?: string;
|
|
2249
|
+
url?: string;
|
|
2250
|
+
title?: string;
|
|
2251
|
+
resultCount?: number;
|
|
2252
|
+
contentLength?: number;
|
|
2253
|
+
offset?: number;
|
|
2254
|
+
returnedChars?: number;
|
|
2255
|
+
nextOffset?: number | null;
|
|
2256
|
+
matchCount?: number;
|
|
2257
|
+
returnedMatches?: number;
|
|
2258
|
+
};
|
|
2259
|
+
|
|
2260
|
+
if (details?.error) {
|
|
2261
|
+
const extras: string[] = [];
|
|
2262
|
+
if (details.query) extras.push(`query: ${details.query}`);
|
|
2263
|
+
if (details.url) extras.push(`url: ${details.url}`);
|
|
2264
|
+
else if (details.title) extras.push(`resource: ${details.title}`);
|
|
2265
|
+
const plan = buildSearchErrorPlan({ error: details.error, extraLines: extras });
|
|
2266
|
+
if (plan) return renderSearchErrorPlan(plan, expanded, theme);
|
|
2267
|
+
return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0);
|
|
2268
|
+
}
|
|
2269
|
+
|
|
2270
|
+
let statusLine: string;
|
|
2271
|
+
if (typeof details?.matchCount === "number") {
|
|
2272
|
+
statusLine = theme.fg("success", details?.title || details?.query || "Content") + theme.fg("muted", ` (${details.matchCount} matches, ${details.returnedMatches ?? 0} shown)`);
|
|
2273
|
+
} else if (details?.query) {
|
|
2274
|
+
statusLine = theme.fg("success", `"${details.query}"`) + theme.fg("muted", ` (${details.resultCount} results)`);
|
|
2275
|
+
} else {
|
|
2276
|
+
const start = details?.offset ?? 0;
|
|
2277
|
+
const returned = details?.returnedChars ?? details?.contentLength ?? 0;
|
|
2278
|
+
const end = start + returned;
|
|
2279
|
+
const slice = details?.nextOffset !== undefined || start > 0
|
|
2280
|
+
? `, showing ${start}-${end}`
|
|
2281
|
+
: "";
|
|
2282
|
+
statusLine = theme.fg("success", details?.title || "Content") + theme.fg("muted", ` (${details?.contentLength ?? 0} chars${slice})`);
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
if (!expanded) {
|
|
2286
|
+
return new Text(statusLine, 0, 0);
|
|
2287
|
+
}
|
|
2288
|
+
|
|
2289
|
+
const textContent = result.content.find((c) => c.type === "text")?.text || "";
|
|
2290
|
+
const preview = textContent.length > 500 ? textContent.slice(0, 500) + "..." : textContent;
|
|
2291
|
+
return new Text(statusLine + "\n" + theme.fg("dim", preview), 0, 0);
|
|
2292
|
+
},
|
|
2293
|
+
});
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2296
|
+
// Deferred tools are never declared on registration, so web_enable must stay the model's route
|
|
2297
|
+
// to them: auto's eager path would leave a session with neither the tools nor the loader.
|
|
2298
|
+
// "none" skips it on purpose: codemode scripts and tool_search still reach deferred tools.
|
|
2299
|
+
if (toolActivation !== "eager" && toolActivation !== "none") registerWebToolActivation(pi, [
|
|
2300
|
+
...(webSearchEnabled ? [{ name: toolNames.webSearch, capability: "search" as const }] : []),
|
|
2301
|
+
...(sourceCheckEnabled ? [{ name: toolNames.sourceCheck, capability: "source-check" as const }] : []),
|
|
2302
|
+
...(fetchContentEnabled ? [{ name: toolNames.fetchContent, capability: "fetch" as const }] : []),
|
|
2303
|
+
...(getSearchContentEnabled ? [{ name: toolNames.getSearchContent, capability: "stored-content" as const }] : []),
|
|
2304
|
+
], toolExposure === "deferred" ? "dynamic" : toolActivation);
|
|
2305
|
+
|
|
2306
|
+
if (isCommandEnabled(initConfig, "websearch")) pi.registerCommand("websearch", {
|
|
2307
|
+
description: "Open web search curator",
|
|
2308
|
+
handler: async (args, ctx) => {
|
|
2309
|
+
const sessionToken = randomUUID();
|
|
2310
|
+
const commandCallId = `cmd:${sessionToken}`;
|
|
2311
|
+
closeCurator(commandCallId);
|
|
2312
|
+
|
|
2313
|
+
const raw = args.trim();
|
|
2314
|
+
const queries = raw.length > 0
|
|
2315
|
+
? normalizeQueryList(raw.split(","))
|
|
2316
|
+
: [];
|
|
2317
|
+
|
|
2318
|
+
let bootstrap: CuratorBootstrap;
|
|
2319
|
+
try {
|
|
2320
|
+
bootstrap = await loadCuratorBootstrap(undefined, ctx);
|
|
2321
|
+
} catch (err) {
|
|
2322
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2323
|
+
ctx.ui.notify(`Failed to load web search config: ${message}`, "error");
|
|
2324
|
+
return;
|
|
2325
|
+
}
|
|
2326
|
+
const availableProviders = bootstrap.availableProviders;
|
|
2327
|
+
const initialProvider = bootstrap.defaultProvider;
|
|
2328
|
+
const curatorTimeoutSeconds = bootstrap.timeoutSeconds;
|
|
2329
|
+
let currentProvider: SearchProvider = initialProvider;
|
|
2330
|
+
const commandConfig = loadConfig();
|
|
2331
|
+
const rawSearchProvider = normalizeProviderInput(
|
|
2332
|
+
commandConfig.searchProvider ?? commandConfig.provider ?? "auto",
|
|
2333
|
+
`provider in ${WEB_SEARCH_CONFIG_PATH}`,
|
|
2334
|
+
) ?? "auto";
|
|
2335
|
+
let currentSearchProvider: SearchProviderSelection = Array.isArray(rawSearchProvider)
|
|
2336
|
+
? rawSearchProvider
|
|
2337
|
+
: rawSearchProvider === "auto" ? "auto" : initialProvider;
|
|
2338
|
+
// A curator provider pick replaces currentSearchProvider with a string, which stays strict.
|
|
2339
|
+
const configDefaultProvider = currentSearchProvider;
|
|
2340
|
+
const summaryContext: SummaryGenerationContext = {
|
|
2341
|
+
model: ctx.model,
|
|
2342
|
+
modelRegistry: ctx.modelRegistry,
|
|
2343
|
+
sessionManager: ctx.sessionManager,
|
|
2344
|
+
scopedModels: ctx.scopedModels,
|
|
2345
|
+
};
|
|
2346
|
+
const summaryModelChoices = await loadSummaryModelChoices(summaryContext);
|
|
2347
|
+
|
|
2348
|
+
ctx.ui.notify("Opening web search curator...", "info");
|
|
2349
|
+
|
|
2350
|
+
const collected = new Map<number, QueryResultData>();
|
|
2351
|
+
const searchAbort = new AbortController();
|
|
2352
|
+
let aborted = false;
|
|
2353
|
+
let commandHandle: CuratorServerHandle | null = null;
|
|
2354
|
+
const isCommandActive = () => commandHandle !== null && activeCurators.get(commandCallId) === commandHandle;
|
|
2355
|
+
|
|
2356
|
+
function sendFollowUpFromReturn(payload: ReturnType<typeof buildSearchReturn>) {
|
|
2357
|
+
pi.sendMessage({
|
|
2358
|
+
customType: "web-search-results",
|
|
2359
|
+
content: payload.content,
|
|
2360
|
+
display: true,
|
|
2361
|
+
details: payload.details,
|
|
2362
|
+
}, { triggerTurn: true, deliverAs: "followUp" });
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
try {
|
|
2366
|
+
const { startCuratorServer } = await import("./curator-server.ts");
|
|
2367
|
+
const handle = await startCuratorServer(
|
|
2368
|
+
{
|
|
2369
|
+
queries,
|
|
2370
|
+
initialResultIndexCapacity: curatorResultIndexCapacity(queries.length),
|
|
2371
|
+
sessionToken,
|
|
2372
|
+
timeout: curatorTimeoutSeconds,
|
|
2373
|
+
availableProviders,
|
|
2374
|
+
defaultProvider: initialProvider,
|
|
2375
|
+
searchProvider: toCuratorProvider(currentSearchProvider) ?? "auto",
|
|
2376
|
+
summaryModels: summaryModelChoices.summaryModels,
|
|
2377
|
+
defaultSummaryModel: summaryModelChoices.defaultSummaryModel,
|
|
2378
|
+
},
|
|
2379
|
+
{
|
|
2380
|
+
async onSummarize(selectedQueryIndices, summarizeSignal, model, feedback) {
|
|
2381
|
+
if (commandHandle && !isCommandActive()) {
|
|
2382
|
+
throw new Error("Curator session is no longer active.");
|
|
2383
|
+
}
|
|
2384
|
+
return generateSummaryForSelectedIndices(
|
|
2385
|
+
selectedQueryIndices,
|
|
2386
|
+
collected,
|
|
2387
|
+
summaryContext,
|
|
2388
|
+
summarizeSignal,
|
|
2389
|
+
model,
|
|
2390
|
+
feedback,
|
|
2391
|
+
);
|
|
2392
|
+
},
|
|
2393
|
+
onSubmit(payload) {
|
|
2394
|
+
if (commandHandle && !isCommandActive()) return;
|
|
2395
|
+
aborted = true;
|
|
2396
|
+
searchAbort.abort();
|
|
2397
|
+
const filtered = payload.selectedQueryIndices.length > 0
|
|
2398
|
+
? filterByQueryIndices(payload.selectedQueryIndices, collected)
|
|
2399
|
+
: collectAllResultsAndUrls(collected);
|
|
2400
|
+
const base: SearchReturnOptions = {
|
|
2401
|
+
queryList: filtered.results.map(r => r.query),
|
|
2402
|
+
results: filtered.results,
|
|
2403
|
+
urls: filtered.urls,
|
|
2404
|
+
includeContent: false,
|
|
2405
|
+
curated: true,
|
|
2406
|
+
curatedFrom: collected.size,
|
|
2407
|
+
};
|
|
2408
|
+
if (!payload.rawResults) {
|
|
2409
|
+
const resolvedSummary = resolveSummaryForSubmit(payload, collected);
|
|
2410
|
+
base.workflow = "summary-review";
|
|
2411
|
+
base.approvedSummary = resolvedSummary.approvedSummary;
|
|
2412
|
+
base.summaryMeta = resolvedSummary.summaryMeta;
|
|
2413
|
+
}
|
|
2414
|
+
sendFollowUpFromReturn(buildSearchReturn(base));
|
|
2415
|
+
closeCurator(commandCallId);
|
|
2416
|
+
},
|
|
2417
|
+
onCancel(reason) {
|
|
2418
|
+
if (commandHandle && !isCommandActive()) return;
|
|
2419
|
+
aborted = true;
|
|
2420
|
+
searchAbort.abort();
|
|
2421
|
+
if (reason === "timeout") {
|
|
2422
|
+
const all = collectAllResultsAndUrls(collected);
|
|
2423
|
+
const resolvedSummary = resolveSummaryForSubmit({ selectedQueryIndices: [], summary: undefined, summaryMeta: undefined }, collected);
|
|
2424
|
+
sendFollowUpFromReturn(buildSearchReturn({
|
|
2425
|
+
queryList: all.results.map(r => r.query),
|
|
2426
|
+
results: all.results,
|
|
2427
|
+
urls: all.urls,
|
|
2428
|
+
includeContent: false,
|
|
2429
|
+
curated: true,
|
|
2430
|
+
curatedFrom: collected.size,
|
|
2431
|
+
workflow: "summary-review",
|
|
2432
|
+
approvedSummary: resolvedSummary.approvedSummary,
|
|
2433
|
+
summaryMeta: resolvedSummary.summaryMeta,
|
|
2434
|
+
}));
|
|
2435
|
+
}
|
|
2436
|
+
closeCurator(commandCallId);
|
|
2437
|
+
},
|
|
2438
|
+
onProviderChange(provider) {
|
|
2439
|
+
if (commandHandle && !isCommandActive()) return;
|
|
2440
|
+
const normalized = normalizeProviderInput(provider);
|
|
2441
|
+
if (!normalized || normalized === "auto" || Array.isArray(normalized)) return;
|
|
2442
|
+
currentProvider = normalized;
|
|
2443
|
+
currentSearchProvider = normalized;
|
|
2444
|
+
try {
|
|
2445
|
+
saveConfig({ provider: normalized });
|
|
2446
|
+
} catch (err) {
|
|
2447
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2448
|
+
console.error(`Failed to persist default provider: ${message}`);
|
|
2449
|
+
}
|
|
2450
|
+
},
|
|
2451
|
+
async onAddSearch(query, provider) {
|
|
2452
|
+
return runWithProxy(undefined, async () => {
|
|
2453
|
+
if (commandHandle && !isCommandActive()) {
|
|
2454
|
+
throw new Error("Curator session is no longer active.");
|
|
2455
|
+
}
|
|
2456
|
+
const requestedProvider = resolveCuratorSearchProvider(provider, currentSearchProvider);
|
|
2457
|
+
const response = await search(query, {
|
|
2458
|
+
provider: requestedProvider,
|
|
2459
|
+
providerFromConfig: requestedProvider === configDefaultProvider,
|
|
2460
|
+
signal: searchAbort.signal,
|
|
2461
|
+
extensionContext: ctx,
|
|
2462
|
+
});
|
|
2463
|
+
if (commandHandle && !isCommandActive()) {
|
|
2464
|
+
throw new Error("Curator session is no longer active.");
|
|
2465
|
+
}
|
|
2466
|
+
return toCuratorSearchEntries(response);
|
|
2467
|
+
});
|
|
2468
|
+
},
|
|
2469
|
+
onAddSearchResults(entries) {
|
|
2470
|
+
if (commandHandle && !isCommandActive()) return;
|
|
2471
|
+
for (const entry of entries) {
|
|
2472
|
+
collected.set(entry.queryIndex, indexedCuratorEntryToQueryResult(entry));
|
|
2473
|
+
}
|
|
2474
|
+
},
|
|
2475
|
+
async onRewriteQuery(query, rewriteSignal) {
|
|
2476
|
+
if (commandHandle && !isCommandActive()) {
|
|
2477
|
+
throw new Error("Curator session is no longer active.");
|
|
2478
|
+
}
|
|
2479
|
+
return rewriteSearchQuery(query, summaryContext, rewriteSignal, readHelperModelKey("queryRewriteModel"));
|
|
2480
|
+
},
|
|
2481
|
+
},
|
|
2482
|
+
);
|
|
2483
|
+
|
|
2484
|
+
commandHandle = handle;
|
|
2485
|
+
activeCurators.set(commandCallId, handle);
|
|
2486
|
+
let browserOpenError: string | null = null;
|
|
2487
|
+
if (!shouldAutoOpenCuratorBrowser(loadConfig())) {
|
|
2488
|
+
ctx.ui.notify(`Search curator is running. Open manually: ${handle.url}`, "info");
|
|
2489
|
+
} else {
|
|
2490
|
+
const open = platform() === "darwin" ? await getGlimpseOpen() : null;
|
|
2491
|
+
if (open) {
|
|
2492
|
+
try {
|
|
2493
|
+
const win = openInGlimpse(open, handle.url, "Search Curator");
|
|
2494
|
+
glimpseWins.set(commandCallId, win);
|
|
2495
|
+
win.on("closed", () => {
|
|
2496
|
+
if (glimpseWins.get(commandCallId) === win) {
|
|
2497
|
+
glimpseWins.delete(commandCallId);
|
|
2498
|
+
closeCurator(commandCallId);
|
|
2499
|
+
}
|
|
2500
|
+
});
|
|
2501
|
+
} catch (err) {
|
|
2502
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2503
|
+
console.error(`Failed to open Glimpse curator window: ${message}`);
|
|
2504
|
+
glimpseWins.delete(commandCallId);
|
|
2505
|
+
try {
|
|
2506
|
+
await openInBrowser(pi, handle.url);
|
|
2507
|
+
} catch (browserErr) {
|
|
2508
|
+
browserOpenError = browserErr instanceof Error ? browserErr.message : String(browserErr);
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
} else {
|
|
2512
|
+
try {
|
|
2513
|
+
await openInBrowser(pi, handle.url);
|
|
2514
|
+
} catch (browserErr) {
|
|
2515
|
+
browserOpenError = browserErr instanceof Error ? browserErr.message : String(browserErr);
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
if (browserOpenError) {
|
|
2519
|
+
console.error(`Failed to open curator UI: ${browserOpenError}`);
|
|
2520
|
+
ctx.ui.notify(`Search curator is running, but the browser did not open automatically. Open manually: ${handle.url}`, "info");
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
|
|
2524
|
+
if (queries.length > 0) {
|
|
2525
|
+
(async () => {
|
|
2526
|
+
await runSearchQueries(queries, async (query, qi) => {
|
|
2527
|
+
if (aborted || !isCommandActive()) return;
|
|
2528
|
+
const requestedProvider = currentSearchProvider;
|
|
2529
|
+
try {
|
|
2530
|
+
const response = await runWithProxy(undefined, () => search(query, {
|
|
2531
|
+
provider: requestedProvider,
|
|
2532
|
+
providerFromConfig: requestedProvider === configDefaultProvider,
|
|
2533
|
+
signal: searchAbort.signal,
|
|
2534
|
+
extensionContext: ctx,
|
|
2535
|
+
}));
|
|
2536
|
+
if (aborted || !isCommandActive()) return;
|
|
2537
|
+
const entries = toCuratorSearchEntries(response);
|
|
2538
|
+
for (let entryIndex = 0; entryIndex < entries.length; entryIndex++) {
|
|
2539
|
+
const entry = entries[entryIndex];
|
|
2540
|
+
const resultIndex = curatorResultIndex(qi, entryIndex, queries.length);
|
|
2541
|
+
const indexedEntry: IndexedCuratorSearchEntry = {
|
|
2542
|
+
...entry,
|
|
2543
|
+
queryIndex: resultIndex,
|
|
2544
|
+
query,
|
|
2545
|
+
};
|
|
2546
|
+
collected.set(resultIndex, indexedCuratorEntryToQueryResult(indexedEntry));
|
|
2547
|
+
if (entry.error) {
|
|
2548
|
+
handle.pushError(resultIndex, entry.error, entry.provider, { query, slotIndex: qi });
|
|
2549
|
+
} else {
|
|
2550
|
+
handle.pushResult(resultIndex, { ...entry, query, slotIndex: qi });
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
} catch (err) {
|
|
2554
|
+
if (aborted || !isCommandActive()) return;
|
|
2555
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2556
|
+
const failedProvider = toCuratorProvider(requestedProvider);
|
|
2557
|
+
handle.pushError(qi, message, failedProvider, { query, slotIndex: qi });
|
|
2558
|
+
collected.set(qi, { query, answer: "", results: [], error: message, provider: failedProvider });
|
|
2559
|
+
}
|
|
2560
|
+
});
|
|
2561
|
+
if (!aborted && isCommandActive()) handle.searchesDone();
|
|
2562
|
+
})();
|
|
2563
|
+
} else {
|
|
2564
|
+
if (isCommandActive()) handle.searchesDone();
|
|
2565
|
+
}
|
|
2566
|
+
} catch (err) {
|
|
2567
|
+
closeCurator(commandCallId);
|
|
2568
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2569
|
+
ctx.ui.notify(`Failed to open curator: ${message}`, "error");
|
|
2570
|
+
}
|
|
2571
|
+
},
|
|
2572
|
+
});
|
|
2573
|
+
|
|
2574
|
+
if (isCommandEnabled(initConfig, "curator")) pi.registerCommand("curator", {
|
|
2575
|
+
description: "Toggle or configure the search curator workflow",
|
|
2576
|
+
handler: async (args, ctx) => {
|
|
2577
|
+
const arg = args.trim().toLowerCase();
|
|
2578
|
+
|
|
2579
|
+
let newWorkflow: WebSearchWorkflow;
|
|
2580
|
+
if (arg.length === 0) {
|
|
2581
|
+
const current = resolveWebSearchWorkflow(loadConfigForExtensionInit().workflow, true);
|
|
2582
|
+
newWorkflow = current === "none" ? "summary-review" : "none";
|
|
2583
|
+
} else if (arg === "on") {
|
|
2584
|
+
newWorkflow = "summary-review";
|
|
2585
|
+
} else if (arg === "off") {
|
|
2586
|
+
newWorkflow = "none";
|
|
2587
|
+
} else if (arg === "none" || arg === "summary-review" || arg === "auto-summary") {
|
|
2588
|
+
newWorkflow = arg;
|
|
2589
|
+
} else {
|
|
2590
|
+
ctx.ui.notify(`Unknown option: ${arg}. Use on, off, summary-review, or auto-summary.`, "error");
|
|
2591
|
+
return;
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
try {
|
|
2595
|
+
saveConfig({ workflow: newWorkflow });
|
|
2596
|
+
} catch (err) {
|
|
2597
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2598
|
+
ctx.ui.notify(`Failed to save config: ${message}`, "error");
|
|
2599
|
+
return;
|
|
2600
|
+
}
|
|
2601
|
+
|
|
2602
|
+
const label = newWorkflow === "none"
|
|
2603
|
+
? `Curator disabled — ${toolNames.webSearch} will return raw results`
|
|
2604
|
+
: newWorkflow === "auto-summary"
|
|
2605
|
+
? `Auto-summary enabled — ${toolNames.webSearch} will generate a summary without opening the curator`
|
|
2606
|
+
: `Curator enabled — ${toolNames.webSearch} will open curator and auto-generate a summary draft`;
|
|
2607
|
+
pi.sendMessage({
|
|
2608
|
+
customType: "curator-config",
|
|
2609
|
+
content: [{ type: "text", text: label }],
|
|
2610
|
+
display: true,
|
|
2611
|
+
details: { workflow: newWorkflow },
|
|
2612
|
+
}, { triggerTurn: false, deliverAs: "followUp" });
|
|
2613
|
+
},
|
|
2614
|
+
});
|
|
2615
|
+
|
|
2616
|
+
const googleAccountCommand = isCommandEnabled(initConfig, "google-account") ? "/google-account" : undefined;
|
|
2617
|
+
let browserCookieQuestion: { answer: Promise<boolean>; dismiss: AbortController; waiting: number } | null = null;
|
|
2618
|
+
// After a "No", Gemini-only routes return the setup hint for the rest of the session instead of asking again.
|
|
2619
|
+
let browserCookiesDeclined = false;
|
|
2620
|
+
|
|
2621
|
+
function browserCookieConsent(ctx: ExtensionContext | undefined): BrowserCookieConsent {
|
|
2622
|
+
return {
|
|
2623
|
+
...(googleAccountCommand ? { command: googleAccountCommand } : {}),
|
|
2624
|
+
...(ctx?.hasUI ? { ask: (signal?: AbortSignal) => askForBrowserCookies(ctx, signal) } : {}),
|
|
2625
|
+
};
|
|
2626
|
+
}
|
|
2627
|
+
|
|
2628
|
+
/** Parallel tool calls (several URLs in one fetch_content) share one question. A caller whose signal
|
|
2629
|
+
* aborts stops waiting with false; the dialog closes once every caller has aborted, and an abort
|
|
2630
|
+
* is not a "No", so a later call asks again. */
|
|
2631
|
+
function askForBrowserCookies(ctx: ExtensionContext, signal?: AbortSignal): Promise<boolean> {
|
|
2632
|
+
if (browserCookiesDeclined || signal?.aborted) return Promise.resolve(false);
|
|
2633
|
+
if (!browserCookieQuestion) {
|
|
2634
|
+
const dismiss = new AbortController();
|
|
2635
|
+
const question = {
|
|
2636
|
+
dismiss,
|
|
2637
|
+
waiting: 0,
|
|
2638
|
+
answer: chooseBrowserCookieAccess(ctx, "Gemini needs your Google login.", dismiss.signal)
|
|
2639
|
+
.then((granted) => {
|
|
2640
|
+
if (!granted && !dismiss.signal.aborted) browserCookiesDeclined = true;
|
|
2641
|
+
return granted;
|
|
2642
|
+
})
|
|
2643
|
+
.finally(() => { if (browserCookieQuestion === question) browserCookieQuestion = null; }),
|
|
2644
|
+
};
|
|
2645
|
+
browserCookieQuestion = question;
|
|
2646
|
+
}
|
|
2647
|
+
const question = browserCookieQuestion;
|
|
2648
|
+
question.waiting++;
|
|
2649
|
+
return new Promise((resolve, reject) => {
|
|
2650
|
+
const onAbort = () => {
|
|
2651
|
+
if (--question.waiting === 0) {
|
|
2652
|
+
question.dismiss.abort();
|
|
2653
|
+
// A dialog that ignores the abort must not keep later calls from asking.
|
|
2654
|
+
if (browserCookieQuestion === question) browserCookieQuestion = null;
|
|
2655
|
+
}
|
|
2656
|
+
resolve(false);
|
|
2657
|
+
};
|
|
2658
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2659
|
+
question.answer.then(resolve, reject).finally(() => signal?.removeEventListener("abort", onAbort));
|
|
2660
|
+
});
|
|
2661
|
+
}
|
|
2662
|
+
|
|
2663
|
+
/** Asks which browser's Google login Gemini Web may use, and for how long. True once access is on.
|
|
2664
|
+
* Detection only checks that profile folders exist; no cookie is read before the user says yes. */
|
|
2665
|
+
async function chooseBrowserCookieAccess(ctx: ExtensionContext, reason: string, signal?: AbortSignal): Promise<boolean> {
|
|
2666
|
+
const found = detectBrowserProfiles();
|
|
2667
|
+
if (found.length === 0) return false;
|
|
2668
|
+
let chosen = found[0];
|
|
2669
|
+
if (found.length > 1) {
|
|
2670
|
+
const labels = found.map(({ name, profiles }) => `${name} (${profiles.join(", ")})`);
|
|
2671
|
+
const index = labels.indexOf(await ctx.ui.select(`${reason} Which browser are you signed into Google in?`, [...labels, "No"], { signal }) ?? "");
|
|
2672
|
+
if (index === -1 || signal?.aborted) return false;
|
|
2673
|
+
chosen = found[index];
|
|
2674
|
+
}
|
|
2675
|
+
const session = "Yes, this session";
|
|
2676
|
+
const always = "Yes, always (saves to web-search.json)";
|
|
2677
|
+
const answer = await ctx.ui.select(`${reason} Read ${chosen.name}'s browser cookies to use it?`, [session, always, "No"], { signal });
|
|
2678
|
+
if (signal?.aborted) return false;
|
|
2679
|
+
// Keep a configured profile when it belongs to the chosen browser, so the same Google account is used.
|
|
2680
|
+
const configured = getBrowserCookieSelectionFromConfig();
|
|
2681
|
+
const selection = { ...(!configured.browser || configured.browser === chosen.browser ? configured : {}), browser: chosen.browser };
|
|
2682
|
+
if (answer === session) {
|
|
2683
|
+
grantBrowserCookieAccessForSession(selection);
|
|
2684
|
+
return true;
|
|
2685
|
+
}
|
|
2686
|
+
if (answer !== always) return false;
|
|
2687
|
+
saveConfig({ allowBrowserCookies: true, browserCookies: selection });
|
|
2688
|
+
clearGeminiWebConfigCache();
|
|
2689
|
+
revokeBrowserCookieAccessForSession();
|
|
2690
|
+
return true;
|
|
2691
|
+
}
|
|
2692
|
+
|
|
2693
|
+
function turnOffBrowserCookies(): string {
|
|
2694
|
+
revokeBrowserCookieAccessForSession();
|
|
2695
|
+
saveConfig({ allowBrowserCookies: false });
|
|
2696
|
+
return isBrowserCookieAccessAllowed()
|
|
2697
|
+
? "Browser cookie access is still on because PI_ALLOW_BROWSER_COOKIES=1 (or FEYNMAN_ALLOW_BROWSER_COOKIES=1) is set in the environment."
|
|
2698
|
+
: "Browser cookie access is off. Gemini Web no longer reads browser cookies.";
|
|
2699
|
+
}
|
|
2700
|
+
|
|
2701
|
+
if (googleAccountCommand) pi.registerCommand("google-account", {
|
|
2702
|
+
description: "Show the active Google account for Gemini Web, or turn its browser cookie access on or off",
|
|
2703
|
+
handler: async (_args, ctx) => {
|
|
2704
|
+
const send = (text: string, details: Record<string, unknown>) => pi.sendMessage({
|
|
2705
|
+
customType: "google-account",
|
|
2706
|
+
content: [{ type: "text", text }],
|
|
2707
|
+
display: true,
|
|
2708
|
+
details,
|
|
2709
|
+
}, { triggerTurn: true, deliverAs: "followUp" });
|
|
2710
|
+
|
|
2711
|
+
const wasAllowed = isBrowserCookieAccessAllowed();
|
|
2712
|
+
if (!wasAllowed && !(ctx.hasUI && await chooseBrowserCookieAccess(ctx, "Gemini Web can use your Google login from a browser."))) {
|
|
2713
|
+
send(`Gemini Web browser cookie access is off.\n${browserCookieAccessHint()}`, { available: false, cookieAccessAllowed: false });
|
|
2714
|
+
return;
|
|
2715
|
+
}
|
|
2716
|
+
|
|
2717
|
+
let text: string;
|
|
2718
|
+
let details: Record<string, unknown>;
|
|
2719
|
+
const cookies = await isGeminiWebAvailable();
|
|
2720
|
+
if (!cookies) {
|
|
2721
|
+
const diagnostic = getGeminiWebAvailabilityDiagnostic();
|
|
2722
|
+
const diagnosticDetails = getGeminiWebAvailabilityDiagnosticDetails();
|
|
2723
|
+
const attempted = formatCookieAttempts(diagnosticDetails?.attempts ?? []);
|
|
2724
|
+
text = diagnostic
|
|
2725
|
+
? `Gemini Web is unavailable: ${diagnostic}${attempted ? ` Attempted browser profiles: ${attempted}.` : ""}`
|
|
2726
|
+
: `Gemini Web is unavailable. ${browserCookieAccessHint()}.`;
|
|
2727
|
+
details = { available: false, cookieAccessAllowed: true, diagnostic, cookieDiagnostic: diagnosticDetails };
|
|
2728
|
+
} else {
|
|
2729
|
+
const email = await getActiveGoogleEmail(cookies);
|
|
2730
|
+
text = email
|
|
2731
|
+
? `Active Google account: ${email}`
|
|
2732
|
+
: "Gemini Web is available, but the active Google account could not be determined.";
|
|
2733
|
+
details = { available: true, email: email ?? null };
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2736
|
+
if (wasAllowed && ctx.hasUI) {
|
|
2737
|
+
const choice = await ctx.ui.select(`${text}\nGemini Web reads your browser cookies.`, ["Keep it on", "Turn it off"]);
|
|
2738
|
+
if (choice === "Turn it off") {
|
|
2739
|
+
text = turnOffBrowserCookies();
|
|
2740
|
+
details = { available: false, cookieAccessAllowed: isBrowserCookieAccessAllowed() };
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
send(text, details);
|
|
2744
|
+
},
|
|
2745
|
+
});
|
|
2746
|
+
|
|
2747
|
+
function formatCookieAttempts(attempts: { browser: string; profile: string; status: string }[]): string {
|
|
2748
|
+
return attempts.map(({ browser, profile, status }) => `${browser}/${profile} (${status})`).join(", ");
|
|
2749
|
+
}
|
|
2750
|
+
|
|
2751
|
+
if (isCommandEnabled(initConfig, "search")) pi.registerCommand("search", {
|
|
2752
|
+
description: "Browse stored web search results",
|
|
2753
|
+
handler: async (_args, ctx) => {
|
|
2754
|
+
const results = getAllResults().filter((r) => ownedResults.has(r.id));
|
|
2755
|
+
|
|
2756
|
+
if (results.length === 0) {
|
|
2757
|
+
ctx.ui.notify("No stored search results", "info");
|
|
2758
|
+
return;
|
|
2759
|
+
}
|
|
2760
|
+
|
|
2761
|
+
const options = results.map((r) => {
|
|
2762
|
+
const age = Math.floor((Date.now() - r.timestamp) / 60000);
|
|
2763
|
+
const ageStr = age < 60 ? `${age}m ago` : `${Math.floor(age / 60)}h ago`;
|
|
2764
|
+
if (r.type === "search" && r.queries) {
|
|
2765
|
+
const query = r.queries[0]?.query || "unknown";
|
|
2766
|
+
return `[${r.id.slice(0, 6)}] "${query}" (${r.queries.length} queries) - ${ageStr}`;
|
|
2767
|
+
}
|
|
2768
|
+
if (r.type === "fetch" && (r.urls || r.urlMetadata)) {
|
|
2769
|
+
return `[${r.id.slice(0, 6)}] ${(r.urls ?? r.urlMetadata ?? []).length} URLs fetched - ${ageStr}`;
|
|
2770
|
+
}
|
|
2771
|
+
return `[${r.id.slice(0, 6)}] ${r.type} - ${ageStr}`;
|
|
2772
|
+
});
|
|
2773
|
+
|
|
2774
|
+
const choice = await ctx.ui.select("Stored Search Results", options);
|
|
2775
|
+
if (!choice) return;
|
|
2776
|
+
|
|
2777
|
+
const match = choice.match(/^\[([a-z0-9]+)\]/);
|
|
2778
|
+
if (!match) return;
|
|
2779
|
+
|
|
2780
|
+
const selected = results.find((r) => r.id.startsWith(match[1]));
|
|
2781
|
+
if (!selected) return;
|
|
2782
|
+
|
|
2783
|
+
const actions = ["View details", "Delete"];
|
|
2784
|
+
const action = await ctx.ui.select(`Result ${selected.id.slice(0, 6)}`, actions);
|
|
2785
|
+
|
|
2786
|
+
if (action === "Delete") {
|
|
2787
|
+
deleteHeldResult(selected.id);
|
|
2788
|
+
ownedResults.delete(selected.id);
|
|
2789
|
+
ctx.ui.notify(`Deleted ${selected.id.slice(0, 6)}`, "info");
|
|
2790
|
+
} else if (action === "View details") {
|
|
2791
|
+
let info = `ID: ${selected.id}\nType: ${selected.type}\nAge: ${Math.floor((Date.now() - selected.timestamp) / 60000)}m\n\n`;
|
|
2792
|
+
if (selected.type === "search" && selected.queries) {
|
|
2793
|
+
info += "Queries:\n";
|
|
2794
|
+
const queries = selected.queries.slice(0, 10);
|
|
2795
|
+
for (const q of queries) {
|
|
2796
|
+
info += `- "${q.query}" (${q.results.length} results)\n`;
|
|
2797
|
+
}
|
|
2798
|
+
if (selected.queries.length > 10) {
|
|
2799
|
+
info += `... and ${selected.queries.length - 10} more\n`;
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
if (selected.type === "fetch" && (selected.urls || selected.urlMetadata)) {
|
|
2803
|
+
info += "URLs:\n";
|
|
2804
|
+
const urlItems = selected.urls ?? selected.urlMetadata ?? [];
|
|
2805
|
+
const urls = urlItems.slice(0, 10);
|
|
2806
|
+
for (const u of urls) {
|
|
2807
|
+
const urlDisplay = u.url.length > 50 ? u.url.slice(0, 47) + "..." : u.url;
|
|
2808
|
+
const contentLength = "content" in u ? u.content.length : u.contentLength;
|
|
2809
|
+
info += `- ${urlDisplay} (${u.error || `${contentLength} chars`})\n`;
|
|
2810
|
+
}
|
|
2811
|
+
if (urlItems.length > 10) {
|
|
2812
|
+
info += `... and ${urlItems.length - 10} more\n`;
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
ctx.ui.notify(info, "info");
|
|
2816
|
+
}
|
|
2817
|
+
},
|
|
2818
|
+
});
|
|
2819
|
+
}
|