@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.
Files changed (201) hide show
  1. package/ASTACK.md +23 -0
  2. package/CHANGELOG.md +1289 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1215 -2
  5. package/SECURITY.md +5 -0
  6. package/abortable.ts +17 -0
  7. package/activity.ts +101 -0
  8. package/anysearch.ts +188 -0
  9. package/auth-fetch.ts +152 -0
  10. package/baizhi.ts +124 -0
  11. package/banner.png +0 -0
  12. package/bocha.ts +203 -0
  13. package/brave-rate-limit.ts +176 -0
  14. package/brave.ts +247 -0
  15. package/brightdata-unlocker.ts +272 -0
  16. package/ceramic.ts +220 -0
  17. package/chrome-cookies.ts +752 -0
  18. package/cloudflare-search.ts +237 -0
  19. package/content-find.ts +255 -0
  20. package/crawl4ai.ts +196 -0
  21. package/credential-source.ts +242 -0
  22. package/curator-page.ts +3607 -0
  23. package/curator-run.ts +45 -0
  24. package/curator-server.ts +761 -0
  25. package/custom-search.ts +226 -0
  26. package/data-uri-sanitize.ts +406 -0
  27. package/datalab-pdf-extract.ts +568 -0
  28. package/declared-web-links.ts +173 -0
  29. package/deepseek.ts +377 -0
  30. package/degoog.ts +323 -0
  31. package/dist/index.js +28286 -0
  32. package/dist/mcp-cli.js +29186 -0
  33. package/dist/pi-mcp.js +20855 -0
  34. package/dist/types/abortable.d.ts +2 -0
  35. package/dist/types/activity.d.ts +33 -0
  36. package/dist/types/anysearch.d.ts +7 -0
  37. package/dist/types/auth-fetch.d.ts +14 -0
  38. package/dist/types/baizhi.d.ts +3 -0
  39. package/dist/types/bocha.d.ts +3 -0
  40. package/dist/types/brave-rate-limit.d.ts +35 -0
  41. package/dist/types/brave.d.ts +3 -0
  42. package/dist/types/brightdata-unlocker.d.ts +11 -0
  43. package/dist/types/ceramic.d.ts +3 -0
  44. package/dist/types/chrome-cookies.d.ts +44 -0
  45. package/dist/types/cloudflare-search.d.ts +4 -0
  46. package/dist/types/content-find.d.ts +10 -0
  47. package/dist/types/crawl4ai.d.ts +8 -0
  48. package/dist/types/credential-source.d.ts +29 -0
  49. package/dist/types/curator-page.d.ts +5 -0
  50. package/dist/types/curator-run.d.ts +10 -0
  51. package/dist/types/curator-server.d.ts +72 -0
  52. package/dist/types/custom-search.d.ts +22 -0
  53. package/dist/types/data-uri-sanitize.d.ts +20 -0
  54. package/dist/types/datalab-pdf-extract.d.ts +59 -0
  55. package/dist/types/declared-web-links.d.ts +7 -0
  56. package/dist/types/deepseek.d.ts +13 -0
  57. package/dist/types/degoog.d.ts +3 -0
  58. package/dist/types/domain-filter-normalization.d.ts +9 -0
  59. package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
  60. package/dist/types/duckduckgo.d.ts +6 -0
  61. package/dist/types/endpoint-pdf-extract.d.ts +22 -0
  62. package/dist/types/exa.d.ts +17 -0
  63. package/dist/types/extract.d.ts +70 -0
  64. package/dist/types/feature-config.d.ts +2 -0
  65. package/dist/types/fetch-params.d.ts +39 -0
  66. package/dist/types/field-extract.d.ts +37 -0
  67. package/dist/types/firecrawl.d.ts +18 -0
  68. package/dist/types/gemini-adc.d.ts +9 -0
  69. package/dist/types/gemini-api.d.ts +37 -0
  70. package/dist/types/gemini-pdf-extract.d.ts +8 -0
  71. package/dist/types/gemini-search.d.ts +76 -0
  72. package/dist/types/gemini-url-context.d.ts +3 -0
  73. package/dist/types/gemini-web-config.d.ts +25 -0
  74. package/dist/types/gemini-web.d.ts +31 -0
  75. package/dist/types/github-api.d.ts +6 -0
  76. package/dist/types/github-extract.d.ts +19 -0
  77. package/dist/types/github-issue-pr.d.ts +28 -0
  78. package/dist/types/index.d.ts +53 -0
  79. package/dist/types/jina-search.d.ts +7 -0
  80. package/dist/types/kagi.d.ts +14 -0
  81. package/dist/types/keenable.d.ts +3 -0
  82. package/dist/types/kimi-search.d.ts +4 -0
  83. package/dist/types/linkup.d.ts +5 -0
  84. package/dist/types/mcp-cli.d.ts +2 -0
  85. package/dist/types/mcp-server.d.ts +10 -0
  86. package/dist/types/mcp-tool-definitions.d.ts +16 -0
  87. package/dist/types/mistral-search.d.ts +3 -0
  88. package/dist/types/ninerouter.d.ts +3 -0
  89. package/dist/types/offtopic-judge.d.ts +26 -0
  90. package/dist/types/ollama.d.ts +14 -0
  91. package/dist/types/openai-search.d.ts +23 -0
  92. package/dist/types/page-query.d.ts +22 -0
  93. package/dist/types/parallel-mcp.d.ts +10 -0
  94. package/dist/types/parallel.d.ts +13 -0
  95. package/dist/types/pdf-extract.d.ts +44 -0
  96. package/dist/types/perplexity.d.ts +26 -0
  97. package/dist/types/pi-mcp.d.ts +56 -0
  98. package/dist/types/pi-session-results.d.ts +8 -0
  99. package/dist/types/querit.d.ts +9 -0
  100. package/dist/types/query-rewrite.d.ts +2 -0
  101. package/dist/types/render-search-error.d.ts +56 -0
  102. package/dist/types/retrieval-only.d.ts +78 -0
  103. package/dist/types/rsc-extract.d.ts +11 -0
  104. package/dist/types/search-answer-formatting.d.ts +7 -0
  105. package/dist/types/search-result-count-normalization.d.ts +1 -0
  106. package/dist/types/searchinfinity.d.ts +7 -0
  107. package/dist/types/searxng.d.ts +3 -0
  108. package/dist/types/source-check.d.ts +102 -0
  109. package/dist/types/ssrf-protection.d.ts +66 -0
  110. package/dist/types/storage.d.ts +69 -0
  111. package/dist/types/summary-model-scope.d.ts +33 -0
  112. package/dist/types/summary-review.d.ts +30 -0
  113. package/dist/types/tabstack.d.ts +5 -0
  114. package/dist/types/tavily.d.ts +7 -0
  115. package/dist/types/tinyfish.d.ts +10 -0
  116. package/dist/types/tool-activation.d.ts +7 -0
  117. package/dist/types/tool-arguments.d.ts +1 -0
  118. package/dist/types/upgrade-notice.d.ts +6 -0
  119. package/dist/types/utils.d.ts +55 -0
  120. package/dist/types/valyu.d.ts +5 -0
  121. package/dist/types/video-extract.d.ts +15 -0
  122. package/dist/types/web-tool-contract.d.ts +98 -0
  123. package/dist/types/web-tool-core.d.ts +227 -0
  124. package/dist/types/xai-search.d.ts +12 -0
  125. package/dist/types/you.d.ts +3 -0
  126. package/dist/types/youtube-extract.d.ts +29 -0
  127. package/dist/types/zai.d.ts +3 -0
  128. package/docs/pi-mcp.md +41 -0
  129. package/domain-filter-normalization.ts +44 -0
  130. package/duckduckgo-rate-limit.ts +205 -0
  131. package/duckduckgo.ts +123 -0
  132. package/endpoint-pdf-extract.ts +225 -0
  133. package/exa.ts +620 -0
  134. package/extract.ts +1721 -0
  135. package/feature-config.ts +29 -0
  136. package/fetch-params.ts +147 -0
  137. package/field-extract.ts +347 -0
  138. package/firecrawl.ts +476 -0
  139. package/gemini-adc.ts +345 -0
  140. package/gemini-api.ts +368 -0
  141. package/gemini-pdf-extract.ts +108 -0
  142. package/gemini-search.ts +1162 -0
  143. package/gemini-url-context.ts +128 -0
  144. package/gemini-web-config.ts +131 -0
  145. package/gemini-web.ts +527 -0
  146. package/github-api.ts +197 -0
  147. package/github-extract.ts +1064 -0
  148. package/github-issue-pr.ts +717 -0
  149. package/index.ts +2819 -0
  150. package/jina-search.ts +275 -0
  151. package/kagi.ts +257 -0
  152. package/keenable.ts +222 -0
  153. package/kimi-search.ts +209 -0
  154. package/linkup.ts +170 -0
  155. package/mcp-cli.ts +40 -0
  156. package/mcp-server.ts +84 -0
  157. package/mcp-tool-definitions.ts +143 -0
  158. package/mistral-search.ts +268 -0
  159. package/ninerouter.ts +92 -0
  160. package/offtopic-judge.ts +72 -0
  161. package/ollama.ts +237 -0
  162. package/openai-search.ts +855 -0
  163. package/package.json +108 -4
  164. package/page-query.ts +185 -0
  165. package/parallel-mcp.ts +255 -0
  166. package/parallel.ts +373 -0
  167. package/pdf-extract.ts +447 -0
  168. package/perplexity.ts +245 -0
  169. package/pi-mcp.ts +139 -0
  170. package/pi-session-results.ts +40 -0
  171. package/pi-web-fetch-demo.mp4 +0 -0
  172. package/promise-try.d.ts +7 -0
  173. package/querit.ts +394 -0
  174. package/query-rewrite.ts +84 -0
  175. package/render-search-error.ts +170 -0
  176. package/retrieval-only.ts +102 -0
  177. package/rsc-extract.ts +338 -0
  178. package/search-answer-formatting.ts +11 -0
  179. package/search-result-count-normalization.ts +4 -0
  180. package/searchinfinity.ts +246 -0
  181. package/searxng.ts +236 -0
  182. package/source-check.ts +269 -0
  183. package/ssrf-protection.ts +602 -0
  184. package/storage.ts +547 -0
  185. package/summary-model-scope.ts +72 -0
  186. package/summary-review.ts +476 -0
  187. package/tabstack.ts +289 -0
  188. package/tavily.ts +257 -0
  189. package/tinyfish.ts +373 -0
  190. package/tool-activation.ts +169 -0
  191. package/tool-arguments.ts +23 -0
  192. package/upgrade-notice.ts +47 -0
  193. package/utils.ts +693 -0
  194. package/valyu.ts +177 -0
  195. package/video-extract.ts +398 -0
  196. package/web-tool-contract.ts +93 -0
  197. package/web-tool-core.ts +1810 -0
  198. package/xai-search.ts +443 -0
  199. package/you.ts +165 -0
  200. package/youtube-extract.ts +336 -0
  201. package/zai.ts +161 -0
package/pi-mcp.ts ADDED
@@ -0,0 +1,139 @@
1
+ // Opt-in embedded MCP entry. Importing the standalone CLI never imports this host.
2
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { createPiSessionResults } from "./pi-session-results.ts";
4
+ import { deleteResult, storeFetchedContentResult } from "./storage.ts";
5
+ import { getRetrievalOnlyPolicy } from "./retrieval-only.ts";
6
+ import {
7
+ createWebToolCore, DEFAULT_TOOL_NAMES, getMaxInlineContentChars, isToolEnabled,
8
+ loadConfig, markToolError, resolveFetchModeConfig,
9
+ type ToolNames, type WebToolCoreSettings, type WebToolCoreInstance,
10
+ } from "./web-tool-core.ts";
11
+ import type { WebToolCore, WebToolResult } from "./web-tool-contract.ts";
12
+ import { createMcpServer as createServer, type McpServerInfo } from "./mcp-server.ts";
13
+ export type { McpServerInfo } from "./mcp-server.ts";
14
+ export type { WebToolCore, WebToolResult } from "./web-tool-contract.ts";
15
+
16
+ export interface PiWebToolCore extends WebToolCore {
17
+ readonly enabledToolNames: readonly string[];
18
+ /** Abort and settle pending calls, unsubscribe, then release this session's results. */
19
+ close(): Promise<void>;
20
+ }
21
+
22
+ /** The embedded entry admits Pi-authenticated search providers, but keeps all MCP input checks. */
23
+ export function createMcpServer(core: PiWebToolCore, info: McpServerInfo, enabledTools?: readonly string[]) {
24
+ return createServer(core, info, enabledTools, { piContext: true });
25
+ }
26
+
27
+ /**
28
+ * Bind once from session_start to the actual context Pi supplied. Its live getters,
29
+ * model registry and auth owner remain intact; this does not recreate or copy them.
30
+ * A replacement runtime needs a new core. The host must await close on shutdown.
31
+ * Searches send the query, not the session transcript. No curator, summaries,
32
+ * background turns or page-answer model calls are installed by this adapter.
33
+ */
34
+ export function createPiWebToolCore({ pi, context }: {
35
+ pi: Pick<ExtensionAPI, "appendEntry" | "on">;
36
+ context: ExtensionContext;
37
+ }): PiWebToolCore {
38
+ const config = loadConfig();
39
+ getRetrievalOnlyPolicy(config);
40
+ const settings: WebToolCoreSettings = {
41
+ toolNames: { ...DEFAULT_TOOL_NAMES },
42
+ enabledTools: {
43
+ webSearch: isToolEnabled(config, "webSearch"),
44
+ sourceCheck: isToolEnabled(config, "sourceCheck"),
45
+ fetchContent: isToolEnabled(config, "fetchContent"),
46
+ getSearchContent: isToolEnabled(config, "getSearchContent"),
47
+ },
48
+ maxInlineContentChars: getMaxInlineContentChars(config),
49
+ fetchModes: resolveFetchModeConfig(config),
50
+ };
51
+ const results = createPiSessionResults(pi);
52
+ const pending = new Set<Promise<void>>();
53
+ let closing: Promise<void> | undefined;
54
+ let closed = false;
55
+
56
+ function bind(ctx: ExtensionContext) {
57
+ results.start(ctx);
58
+ return { context: ctx, lifetime: new AbortController() };
59
+ }
60
+ function callCore(signal: AbortSignal) {
61
+ return createWebToolCore({
62
+ settings,
63
+ storeFetchedContent(id, data) {
64
+ signal.throwIfAborted();
65
+ results.publish(storeFetchedContentResult(id, data));
66
+ },
67
+ publishResult(data) {
68
+ // The core stores search data before publication. Cancelled calls must
69
+ // neither retain it nor append it to the current or a replacement branch.
70
+ if (signal.aborted) {
71
+ deleteResult(data.id);
72
+ signal.throwIfAborted();
73
+ }
74
+ results.publish(data);
75
+ },
76
+ extractOptions: { rejectDirectImages: "Direct image fetch is not supported over MCP; fetch_content returns text there." },
77
+ });
78
+ }
79
+ let active = bind(context);
80
+ const unsubscribeTree = pi.on("session_tree", (_event, ctx) => {
81
+ if (closed) return;
82
+ active.lifetime.abort();
83
+ active = bind(ctx);
84
+ });
85
+ const error = (message: string): WebToolResult => ({ content: [{ type: "text", text: message }], details: { error: message }, isError: true });
86
+
87
+ function run(key: keyof ToolNames, signal: AbortSignal | undefined,
88
+ operation: (core: WebToolCoreInstance, context: ExtensionContext, signal: AbortSignal) => Promise<WebToolResult>): Promise<WebToolResult> {
89
+ if (closed) return Promise.reject(new Error("Pi web core is closed."));
90
+ if (!settings.enabledTools[key]) return Promise.resolve(error("This web tool is disabled."));
91
+ const branch = active;
92
+ const signals = [branch.lifetime.signal, signal, branch.context.signal].filter((value): value is AbortSignal => value !== undefined);
93
+ const combined = AbortSignal.any(signals);
94
+ const work = (async () => {
95
+ combined.throwIfAborted();
96
+ const result = await operation(callCore(combined), branch.context, combined);
97
+ combined.throwIfAborted();
98
+ return markToolError(result);
99
+ })();
100
+ const settled = work.then(() => undefined, () => undefined);
101
+ pending.add(settled);
102
+ void settled.then(() => pending.delete(settled));
103
+ return work;
104
+ }
105
+ return {
106
+ enabledToolNames: (['webSearch', 'sourceCheck', 'fetchContent', 'getSearchContent'] satisfies (keyof ToolNames)[])
107
+ .filter(key => settings.enabledTools[key]).map(key => DEFAULT_TOOL_NAMES[key]),
108
+ webSearch(params, signal) {
109
+ return run("webSearch", signal, (core, context, signal) => core.webSearch(params, signal, { extensionContext: context, awaitContent: true }));
110
+ },
111
+ fetchContent(params, signal) {
112
+ return run("fetchContent", signal, (core, context, signal) => {
113
+ if (params.mode === "answer" || (params.mode === undefined && settings.fetchModes.defaultMode === "answer")) {
114
+ return Promise.resolve(error('Page answers are not enabled by the Pi MCP host; use mode "readable" or "raw".'));
115
+ }
116
+ return core.fetchContent(params, signal, { extensionContext: context });
117
+ });
118
+ },
119
+ getSearchContent(params, signal) {
120
+ return run("getSearchContent", signal, (core, context, signal) => {
121
+ const owned = results.ownedResults.has(params.responseId) && context.sessionManager.getBranch().some(entry =>
122
+ entry.type === "custom" && entry.customType === "web-search-results" &&
123
+ typeof entry.data === "object" && entry.data !== null && "id" in entry.data && entry.data.id === params.responseId);
124
+ return owned ? core.getSearchContent(params, signal) : Promise.resolve(error("Stored web content is not owned by this session branch."));
125
+ });
126
+ },
127
+ sourceCheck(params, signal) {
128
+ return run("sourceCheck", signal, (core, context, signal) => core.sourceCheck(params, signal, { extensionContext: context }));
129
+ },
130
+ close() {
131
+ if (closing) return closing;
132
+ closed = true;
133
+ unsubscribeTree();
134
+ active.lifetime.abort();
135
+ closing = Promise.allSettled(pending).then(() => { results.close(); });
136
+ return closing;
137
+ },
138
+ };
139
+ }
@@ -0,0 +1,40 @@
1
+ // Shared Pi journal and result lifetime for the native extension and embedded MCP.
2
+ // No model/auth ownership belongs here; each host supplies the real Pi context.
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { clearCloneCache, releaseClonesUnusedSince, touchClones } from "./github-extract.ts";
5
+ import { holdResults, loadSessionResults, releaseResults, type StoredSearchData } from "./storage.ts";
6
+
7
+ /** Clones remain live while any session may still reference their paths. */
8
+ const liveInstances = new Map<object, number>();
9
+
10
+ export function createPiSessionResults(pi: Pick<ExtensionAPI, "appendEntry">) {
11
+ const instance = {};
12
+ const ownedResults = new Set<string>();
13
+ function own(id: string): void {
14
+ if (ownedResults.has(id)) return;
15
+ ownedResults.add(id);
16
+ holdResults([id]);
17
+ }
18
+ function close(): void {
19
+ releaseResults(ownedResults);
20
+ ownedResults.clear();
21
+ liveInstances.delete(instance);
22
+ if (liveInstances.size === 0) clearCloneCache();
23
+ else releaseClonesUnusedSince(Math.min(...liveInstances.values()));
24
+ }
25
+ return {
26
+ ownedResults,
27
+ publish(data: StoredSearchData): void {
28
+ own(data.id);
29
+ pi.appendEntry("web-search-results", data);
30
+ },
31
+ start(ctx: ExtensionContext): void {
32
+ close();
33
+ liveInstances.set(instance, Date.now());
34
+ const restored = loadSessionResults(ctx);
35
+ for (const data of restored) own(data.id);
36
+ touchClones(restored.flatMap(data => data.type === "fetch" ? (data.urls ?? data.urlMetadata ?? []).map(url => url.url) : []));
37
+ },
38
+ close,
39
+ };
40
+ }
Binary file
@@ -0,0 +1,7 @@
1
+ declare module "promise.try" {
2
+ function promiseTry<T>(callback: () => T | PromiseLike<T>): Promise<T>;
3
+ namespace promiseTry {
4
+ function shim(): void;
5
+ }
6
+ export default promiseTry;
7
+ }
package/querit.ts ADDED
@@ -0,0 +1,394 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
4
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
5
+ import type { ExtractedContent, ExtractOptions } from "./extract.ts";
6
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
7
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
8
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
9
+ import { getWebSearchConfigPath, resolveProviderApiUrl, fetchWithCredentialRedirects } from "./utils.ts";
10
+
11
+ const QUERIT_SEARCH_URL = "https://api.querit.ai/v1/search";
12
+ const QUERIT_CONTENTS_URL = "https://api.querit.ai/v1/contents";
13
+ const CONFIG_PATH = getWebSearchConfigPath();
14
+ const SEARCH_TIMEOUT_MS = 60_000;
15
+ const CONTENTS_TIMEOUT_MS = 60_000;
16
+ const MAX_CONTENT_URLS = 10;
17
+
18
+ interface WebSearchConfig {
19
+ queritBaseUrl?: unknown;
20
+ queritApiKey?: unknown;
21
+ }
22
+
23
+ interface QueritSearchResult {
24
+ url?: string | null;
25
+ title?: string | null;
26
+ snippet?: string | null;
27
+ page_age?: string | null;
28
+ site_name?: string | null;
29
+ }
30
+
31
+ interface QueritSearchResponse {
32
+ error_code?: number | string;
33
+ error_msg?: string;
34
+ search_id?: number | string;
35
+ results?: { result?: QueritSearchResult[] };
36
+ }
37
+
38
+ interface QueritContentMetadata {
39
+ title?: string | null;
40
+ url?: string | null;
41
+ publishTime?: string | null;
42
+ siteName?: string | null;
43
+ siteIcon?: string | null;
44
+ }
45
+
46
+ interface QueritContentResult {
47
+ id?: string | null;
48
+ url?: string | null;
49
+ content?: string | null;
50
+ extrasMeta?: QueritContentMetadata | null;
51
+ }
52
+
53
+ interface QueritContentStatus {
54
+ id?: string | null;
55
+ status?: string | null;
56
+ }
57
+
58
+ interface QueritContentsResponse {
59
+ error_code?: number | string;
60
+ error_msg?: string;
61
+ search_id?: number | string;
62
+ results?: QueritContentResult[];
63
+ statuses?: QueritContentStatus[];
64
+ searchTime?: number;
65
+ }
66
+
67
+ interface QueritSearchOptions extends SearchOptions {
68
+ includeContent?: boolean;
69
+ }
70
+
71
+ let cachedConfig: WebSearchConfig | null = null;
72
+
73
+ function loadConfig(): WebSearchConfig {
74
+ if (cachedConfig) return cachedConfig;
75
+ if (!existsSync(CONFIG_PATH)) {
76
+ cachedConfig = {};
77
+ return cachedConfig;
78
+ }
79
+
80
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
81
+ let parsed: unknown;
82
+ try {
83
+ parsed = JSON.parse(raw);
84
+ } catch (err) {
85
+ const message = err instanceof Error ? err.message : String(err);
86
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
87
+ }
88
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
89
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
90
+ }
91
+ cachedConfig = parsed as WebSearchConfig;
92
+ return cachedConfig;
93
+ }
94
+
95
+ async function getApiKey(signal?: AbortSignal): Promise<string> {
96
+ const key = await resolveCredential({
97
+ provider: "Querit",
98
+ configuredValue: loadConfig().queritApiKey,
99
+ environmentValue: process.env.QUERIT_API_KEY,
100
+ signal,
101
+ });
102
+ if (!key) {
103
+ throw new Error(
104
+ "Querit API key not found. Either:\n" +
105
+ ` 1. Create ${CONFIG_PATH} with { "queritApiKey": "your-key" }\n` +
106
+ " 2. Set QUERIT_API_KEY environment variable\n" +
107
+ "Create a key at https://www.querit.ai/en/dashboard/api-keys",
108
+ );
109
+ }
110
+ return key;
111
+ }
112
+
113
+ export function isQueritAvailable(): boolean {
114
+ return hasCredentialSource({
115
+ provider: "Querit",
116
+ configuredValue: loadConfig().queritApiKey,
117
+ environmentValue: process.env.QUERIT_API_KEY,
118
+ });
119
+ }
120
+
121
+ function errorMessage(err: unknown): string {
122
+ return err instanceof Error ? err.message : String(err);
123
+ }
124
+
125
+ function requestSignal(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
126
+ const timeout = AbortSignal.timeout(timeoutMs);
127
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
128
+ }
129
+
130
+ function mapDomainFilter(domainFilter: string[] | undefined): { include: string[]; exclude: string[] } {
131
+ const include: string[] = [];
132
+ const exclude: string[] = [];
133
+ for (const raw of domainFilter ?? []) {
134
+ const domain = normalizeDomain(raw);
135
+ if (!domain) continue;
136
+ const target = raw.trim().startsWith("-") ? exclude : include;
137
+ if (!target.includes(domain)) target.push(domain);
138
+ }
139
+ return { include, exclude };
140
+ }
141
+
142
+ function mapRecencyFilter(value: SearchOptions["recencyFilter"]): string | undefined {
143
+ if (value === "day") return "d1";
144
+ if (value === "week") return "w1";
145
+ if (value === "month") return "m1";
146
+ if (value === "year") return "y1";
147
+ return undefined;
148
+ }
149
+
150
+ function buildSearchBody(query: string, options: QueritSearchOptions): Record<string, unknown> {
151
+ const { include, exclude } = mapDomainFilter(options.domainFilter);
152
+ const date = mapRecencyFilter(options.recencyFilter);
153
+ const filters: Record<string, unknown> = {};
154
+ if (include.length > 0 || exclude.length > 0) {
155
+ filters.sites = {
156
+ ...(include.length > 0 ? { include } : {}),
157
+ ...(exclude.length > 0 ? { exclude } : {}),
158
+ };
159
+ }
160
+ if (date) filters.timeRange = { date };
161
+ return {
162
+ query,
163
+ count: normalizeSearchResultCount(options.numResults),
164
+ ...(Object.keys(filters).length > 0 ? { filters } : {}),
165
+ };
166
+ }
167
+
168
+ function normalizeTimeoutMs(value: number | undefined): number {
169
+ if (typeof value !== "number" || !Number.isFinite(value)) return CONTENTS_TIMEOUT_MS;
170
+ return Math.max(1, Math.floor(value));
171
+ }
172
+
173
+ function crawlTimeoutSeconds(value: number | undefined): number {
174
+ if (typeof value !== "number" || !Number.isFinite(value)) return 10;
175
+ return Math.max(1, Math.min(Math.ceil(value / 1_000), 60));
176
+ }
177
+
178
+ function buildContentsBody(urls: string[], options: ExtractOptions = {}): Record<string, unknown> {
179
+ return {
180
+ urls,
181
+ format: "markdown",
182
+ crawlTimeout: crawlTimeoutSeconds(options.timeoutMs),
183
+ extrasMeta: true,
184
+ };
185
+ }
186
+
187
+ async function queritJsonRequest<T>(
188
+ label: "Search" | "Contents",
189
+ url: string,
190
+ apiKey: string,
191
+ body: Record<string, unknown>,
192
+ timeoutMs: number,
193
+ signal?: AbortSignal,
194
+ ): Promise<T> {
195
+ let response: Response;
196
+ try {
197
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("querit", url, loadConfig().queritBaseUrl), {
198
+ method: "POST",
199
+ headers: {
200
+ Authorization: `Bearer ${apiKey}`,
201
+ Accept: "application/json",
202
+ "Content-Type": "application/json",
203
+ },
204
+ body: JSON.stringify(body),
205
+ signal: requestSignal(signal, timeoutMs),
206
+ }, ["Authorization"]);
207
+ } catch (err) {
208
+ const message = errorMessage(err);
209
+ const isRequestAbort = err instanceof Error
210
+ ? err.name === "AbortError" || err.name === "TimeoutError" || /abort|timeout/i.test(message)
211
+ : /abort|timeout/i.test(message);
212
+ if (!signal?.aborted && isRequestAbort) {
213
+ const timeoutError = new Error(`Querit ${label} API request timed out after ${Math.ceil(timeoutMs / 1_000)} seconds`);
214
+ timeoutError.name = "TimeoutError";
215
+ throw timeoutError;
216
+ }
217
+ const redactedMessage = redactCredential(message, apiKey);
218
+ if (redactedMessage === message) throw err;
219
+ const redactedError = new Error(redactedMessage);
220
+ if (err instanceof Error) redactedError.name = err.name;
221
+ throw redactedError;
222
+ }
223
+
224
+ const raw = await response.text();
225
+ if (!response.ok) {
226
+ throw new Error(`Querit ${label} API error ${response.status}: ${redactCredential(raw, apiKey).slice(0, 300)}`);
227
+ }
228
+ try {
229
+ return JSON.parse(raw) as T;
230
+ } catch (err) {
231
+ throw new Error(`Querit ${label} API returned invalid JSON: ${errorMessage(err)}`);
232
+ }
233
+ }
234
+
235
+ function assertApiSuccess(label: "Search" | "Contents", data: QueritSearchResponse | QueritContentsResponse): void {
236
+ const code = Number(data.error_code);
237
+ if (!Number.isFinite(code) || code !== 200) {
238
+ const renderedCode = data.error_code === undefined ? "unknown" : String(data.error_code);
239
+ const message = typeof data.error_msg === "string" && data.error_msg.trim() ? `: ${data.error_msg.trim()}` : "";
240
+ throw new Error(`Querit ${label} API returned error ${renderedCode}${message}`);
241
+ }
242
+ }
243
+
244
+ function mapSearchResults(data: QueritSearchResponse): SearchResponse["results"] {
245
+ const items = data.results?.result;
246
+ if (!Array.isArray(items)) {
247
+ throw new Error("Querit Search API returned an unexpected response shape");
248
+ }
249
+ return items.flatMap((item) => {
250
+ if (!item || typeof item.url !== "string" || item.url.trim().length === 0) return [];
251
+ const url = item.url.trim();
252
+ return [{
253
+ title: typeof item.title === "string" && item.title.trim() ? item.title.trim() : url,
254
+ url,
255
+ snippet: typeof item.snippet === "string" ? item.snippet.replace(/\s+/g, " ").trim() : "",
256
+ }];
257
+ });
258
+ }
259
+
260
+ function mapContentResult(result: QueritContentResult | undefined, requestedUrl: string): ExtractedContent | null {
261
+ if (!result || typeof result.content !== "string" || result.content.trim().length === 0) return null;
262
+ const metadata = result.extrasMeta;
263
+ return {
264
+ url: requestedUrl,
265
+ title: metadata && typeof metadata.title === "string" ? metadata.title.trim() : "",
266
+ content: result.content.trim(),
267
+ error: null,
268
+ };
269
+ }
270
+
271
+ function findContentResult(
272
+ data: QueritContentsResponse,
273
+ requestedUrl: string,
274
+ index: number,
275
+ requestedCount: number,
276
+ ): QueritContentResult | undefined {
277
+ if (!Array.isArray(data.results)) return undefined;
278
+ const exact = data.results.find((item) => item?.url === requestedUrl || item?.extrasMeta?.url === requestedUrl);
279
+ if (exact) return exact;
280
+ if (requestedCount === 1) return data.results[0];
281
+ return data.results.length === requestedCount ? data.results[index] : undefined;
282
+ }
283
+
284
+ function failedContentStatus(data: QueritContentsResponse, result: QueritContentResult | undefined, index: number): boolean {
285
+ if (!Array.isArray(data.statuses)) return false;
286
+ const status = result?.id
287
+ ? data.statuses.find((item) => item?.id === result.id)
288
+ : data.statuses[index];
289
+ return status?.status === "failed";
290
+ }
291
+
292
+ async function fetchContentsBatch(
293
+ urls: string[],
294
+ apiKey: string,
295
+ signal?: AbortSignal,
296
+ options: ExtractOptions = {},
297
+ ): Promise<QueritContentsResponse> {
298
+ const data = await queritJsonRequest<QueritContentsResponse>(
299
+ "Contents",
300
+ QUERIT_CONTENTS_URL,
301
+ apiKey,
302
+ buildContentsBody(urls, options),
303
+ normalizeTimeoutMs(options.timeoutMs),
304
+ signal,
305
+ );
306
+ assertApiSuccess("Contents", data);
307
+ if (!Array.isArray(data.results) || !Array.isArray(data.statuses)) {
308
+ throw new Error("Querit Contents API returned an unexpected response shape");
309
+ }
310
+ return data;
311
+ }
312
+
313
+ async function fetchInlineContent(urls: string[], apiKey: string, signal?: AbortSignal): Promise<ExtractedContent[]> {
314
+ const content: ExtractedContent[] = [];
315
+ for (let offset = 0; offset < urls.length; offset += MAX_CONTENT_URLS) {
316
+ const batch = urls.slice(offset, offset + MAX_CONTENT_URLS);
317
+ const data = await fetchContentsBatch(batch, apiKey, signal);
318
+ for (let index = 0; index < batch.length; index++) {
319
+ const requestedUrl = batch[index];
320
+ const result = findContentResult(data, requestedUrl, index, batch.length);
321
+ const mapped = mapContentResult(result, requestedUrl);
322
+ if (mapped) content.push(mapped);
323
+ }
324
+ }
325
+ return content;
326
+ }
327
+
328
+ export async function searchWithQuerit(
329
+ query: string,
330
+ options: QueritSearchOptions = {},
331
+ ): Promise<SearchResponse> {
332
+ const apiKey = await getApiKey(options.signal);
333
+ const activityId = activityMonitor.logStart({ type: "api", query });
334
+ try {
335
+ const data = await queritJsonRequest<QueritSearchResponse>(
336
+ "Search",
337
+ QUERIT_SEARCH_URL,
338
+ apiKey,
339
+ buildSearchBody(query, options),
340
+ SEARCH_TIMEOUT_MS,
341
+ options.signal,
342
+ );
343
+ assertApiSuccess("Search", data);
344
+ const results = mapSearchResults(data);
345
+ const response: SearchResponse = { answer: formatSearchResultsAsAnswer(results), results };
346
+ if (options.includeContent && results.length > 0) {
347
+ const inlineContent = await fetchInlineContent(results.map((result) => result.url), apiKey, options.signal);
348
+ if (inlineContent.length > 0) response.inlineContent = inlineContent;
349
+ }
350
+ activityMonitor.logComplete(activityId, 200);
351
+ return response;
352
+ } catch (err) {
353
+ const message = errorMessage(err);
354
+ const redactedMessage = redactCredential(message, apiKey);
355
+ if (options.signal?.aborted) activityMonitor.logComplete(activityId, 0);
356
+ else activityMonitor.logError(activityId, redactedMessage);
357
+ if (redactedMessage === message) throw err;
358
+ const redactedError = new Error(redactedMessage);
359
+ if (err instanceof Error) redactedError.name = err.name;
360
+ throw redactedError;
361
+ }
362
+ }
363
+
364
+ export async function extractWithQuerit(
365
+ url: string,
366
+ signal?: AbortSignal,
367
+ options: ExtractOptions = {},
368
+ ): Promise<ExtractedContent | null> {
369
+ const apiKey = await getApiKey(signal);
370
+ const activityId = activityMonitor.logStart({ type: "fetch", url });
371
+ try {
372
+ const data = await fetchContentsBatch([url], apiKey, signal, options);
373
+ const result = findContentResult(data, url, 0, 1);
374
+ const mapped = mapContentResult(result, url);
375
+ if (mapped) {
376
+ activityMonitor.logComplete(activityId, 200);
377
+ return mapped;
378
+ }
379
+ if (failedContentStatus(data, result, 0)) {
380
+ throw new Error(`Querit Contents API failed to crawl ${url}`);
381
+ }
382
+ activityMonitor.logComplete(activityId, 200);
383
+ return null;
384
+ } catch (err) {
385
+ const message = errorMessage(err);
386
+ const redactedMessage = redactCredential(message, apiKey);
387
+ if (signal?.aborted) activityMonitor.logComplete(activityId, 0);
388
+ else activityMonitor.logError(activityId, redactedMessage);
389
+ if (redactedMessage === message) throw err;
390
+ const redactedError = new Error(redactedMessage);
391
+ if (err instanceof Error) redactedError.name = err.name;
392
+ throw redactedError;
393
+ }
394
+ }
@@ -0,0 +1,84 @@
1
+ import type { complete, Api, Model, ProviderHeaders } from "@earendil-works/pi-ai/compat";
2
+ import { resolveThinkingLevel, type SummaryGenerationContext } from "./summary-review.ts";
3
+ import { awaitWithAbort } from "./abortable.ts";
4
+ import { findModelWithProviderRouting, isModelInScope, resolveHelperModelSelector, type SummaryThinkingLevel } from "./summary-model-scope.ts";
5
+ import { getRetrievalOnlyPolicy, retrievalOnlyError } from "./retrieval-only.ts";
6
+
7
+ async function resolveFirstAvailableModel(
8
+ ctx: SummaryGenerationContext,
9
+ candidates: Array<{ provider: string; id: string }>,
10
+ ): Promise<{ model: Model<Api>; apiKey?: string; headers?: ProviderHeaders }> {
11
+ for (const { provider, id } of candidates) {
12
+ const model = findModelWithProviderRouting(ctx.modelRegistry, provider, id);
13
+ if (!model || !isModelInScope(model, ctx.scopedModels)) continue;
14
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
15
+ if (auth.ok) return { model, apiKey: auth.apiKey, headers: auth.headers };
16
+ }
17
+ throw new Error(`No enabled model available: ${candidates.map(candidate => `${candidate.provider}/${candidate.id}`).join(", ")}`);
18
+ }
19
+
20
+ async function resolveConfiguredModel(
21
+ ctx: SummaryGenerationContext,
22
+ selector: string,
23
+ ): Promise<{ model: Model<Api>; apiKey?: string; headers?: ProviderHeaders; thinkingLevel?: SummaryThinkingLevel }> {
24
+ const spec = resolveHelperModelSelector(selector, "query rewrite model", ctx.model);
25
+ if (!spec) throw new Error(`Query rewrite model not found: ${selector} (no active Pi session model)`);
26
+ const model = findModelWithProviderRouting(ctx.modelRegistry, spec.provider, spec.id);
27
+ if (!model) throw new Error(`Query rewrite model not found: ${selector}`);
28
+ const value = `${model.provider}/${model.id}`;
29
+ if (!isModelInScope(model, ctx.scopedModels)) throw new Error(`Query rewrite model is not enabled: ${value}`);
30
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
31
+ if (!auth.ok) throw new Error(`No API key available for query rewrite model ${value}`);
32
+ return { model, apiKey: auth.apiKey, headers: auth.headers, thinkingLevel: spec.thinkingLevel };
33
+ }
34
+
35
+ export async function rewriteSearchQuery(
36
+ query: string,
37
+ ctx: SummaryGenerationContext,
38
+ signal: AbortSignal,
39
+ modelSelector?: string,
40
+ ): Promise<string> {
41
+ if (getRetrievalOnlyPolicy().enabled) throw retrievalOnlyError("Query rewrite");
42
+ const { model, apiKey, headers, thinkingLevel }: Awaited<ReturnType<typeof resolveConfiguredModel>> = modelSelector === undefined
43
+ ? await resolveFirstAvailableModel(ctx, [
44
+ { provider: "anthropic", id: "claude-haiku-4-5" },
45
+ { provider: "google", id: "gemini-3.6-flash" },
46
+ { provider: "openai", id: "gpt-5-mini" },
47
+ ])
48
+ : await resolveConfiguredModel(ctx, modelSelector);
49
+ const registry = ctx.modelRegistry as typeof ctx.modelRegistry & { complete?: typeof complete };
50
+ // streamSimple is Pi's provider-neutral path and routes virtual models; complete() does not (#574).
51
+ const usesRegistryStreamSimple = typeof registry.streamSimple === "function";
52
+ const usesRegistryComplete = !usesRegistryStreamSimple && typeof registry.complete === "function";
53
+ if (signal.aborted) throw new Error("Aborted");
54
+ const compat = usesRegistryStreamSimple || usesRegistryComplete ? undefined : await awaitWithAbort(import("@earendil-works/pi-ai/compat"), signal);
55
+ if (signal.aborted) throw new Error("Aborted");
56
+ const requestedThinkingLevel = await awaitWithAbort(resolveThinkingLevel(model, thinkingLevel), signal);
57
+ const reasoning = requestedThinkingLevel !== "off" ? requestedThinkingLevel : undefined;
58
+ const context = {
59
+ messages: [{
60
+ role: "user" as const,
61
+ content: [{ type: "text" as const, text: `Rewrite this web search query to get better, more specific results. Add relevant year qualifiers, precise technical terms, and specificity. Return ONLY the improved query text, nothing else.\n\nQuery: ${query}` }],
62
+ timestamp: Date.now(),
63
+ }],
64
+ };
65
+ const response = usesRegistryStreamSimple
66
+ ? await registry.streamSimple(model, context, { signal, ...(reasoning ? { reasoning } : {}) }).result()
67
+ : usesRegistryComplete
68
+ ? await registry.complete!(model, context, {
69
+ signal,
70
+ ...(requestedThinkingLevel ? { reasoning: requestedThinkingLevel } : {}),
71
+ ...(reasoning ? { reasoningEffort: reasoning } : {}),
72
+ })
73
+ : thinkingLevel
74
+ ? await compat!.completeSimple(model, context, { apiKey, headers, signal, ...(reasoning ? { reasoning } : {}) })
75
+ : await compat!.complete(model, context, { apiKey, headers, signal });
76
+ if (response.stopReason === "aborted") throw new Error("Aborted");
77
+ const contentParts = Array.isArray(response.content) ? response.content : [];
78
+ const text = contentParts
79
+ .map((part: unknown) => part && typeof part === "object" && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : "")
80
+ .join("")
81
+ .trim();
82
+ if (!text) throw new Error("Rewrite returned empty response");
83
+ return text;
84
+ }