@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/mcp-server.ts ADDED
@@ -0,0 +1,84 @@
1
+ // MCP server exposing the web tools over any transport. Tool behavior lives in
2
+ // the WebToolCore; this module only lists tools, validates arguments at the
3
+ // boundary, forwards cancellation, and maps results to MCP content.
4
+
5
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
6
+ import {
7
+ CallToolRequestSchema,
8
+ type CallToolResult,
9
+ ErrorCode,
10
+ ListToolsRequestSchema,
11
+ McpError,
12
+ } from "@modelcontextprotocol/sdk/types.js";
13
+ import { MCP_TOOL_DEFINITIONS, validateMcpToolArguments } from "./mcp-tool-definitions.ts";
14
+ import { getRetrievalOnlyPolicy, RETRIEVAL_ONLY_DESCRIPTION_SUFFIX } from "./retrieval-only.ts";
15
+ import type {
16
+ FetchContentCallParams,
17
+ GetSearchContentCallParams,
18
+ SourceCheckCallParams,
19
+ WebSearchCallParams,
20
+ WebToolCore,
21
+ WebToolResult,
22
+ } from "./web-tool-contract.ts";
23
+
24
+ export interface McpServerInfo {
25
+ name: string;
26
+ version: string;
27
+ }
28
+
29
+ type ToolRunner = (core: WebToolCore, args: Record<string, unknown>, signal: AbortSignal) => Promise<WebToolResult>;
30
+ type ToolInputSchema = { type: "object"; [key: string]: unknown };
31
+
32
+ // Arguments are validated against the matching MCP schema before these casts run.
33
+ const TOOL_RUNNERS: Record<string, ToolRunner> = {
34
+ web_search: (core, args, signal) => core.webSearch(args as WebSearchCallParams, signal),
35
+ fetch_content: (core, args, signal) => core.fetchContent(args as FetchContentCallParams, signal),
36
+ get_search_content: (core, args, signal) => core.getSearchContent(args as unknown as GetSearchContentCallParams, signal),
37
+ source_check: (core, args, signal) => core.sourceCheck(args as unknown as SourceCheckCallParams, signal),
38
+ };
39
+
40
+ function errorResult(text: string): CallToolResult {
41
+ return { content: [{ type: "text", text }], isError: true };
42
+ }
43
+
44
+ // details stays off the wire: clients such as Codex show the model structuredContent
45
+ // instead of content, and details holds host metadata rather than the results.
46
+ function toCallToolResult(result: WebToolResult): CallToolResult {
47
+ return { content: result.content, ...(result.isError && { isError: true }) };
48
+ }
49
+
50
+ /** Serves enabledTools (default: all four). Only a host with a live Pi context may enable piContext. */
51
+ export function createMcpServer(core: WebToolCore, info: McpServerInfo, enabledTools?: readonly string[], options: { piContext?: boolean } = {}): Server {
52
+ const server = new Server(info, { capabilities: { tools: {} } });
53
+ const tools = enabledTools ? MCP_TOOL_DEFINITIONS.filter((tool) => enabledTools.includes(tool.name)) : MCP_TOOL_DEFINITIONS;
54
+
55
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
56
+ tools: tools.map((tool) => ({
57
+ name: tool.name,
58
+ description: getRetrievalOnlyPolicy().enabled && (tool.name === "web_search" || tool.name === "fetch_content")
59
+ ? tool.description + RETRIEVAL_ONLY_DESCRIPTION_SUFFIX
60
+ : tool.description,
61
+ inputSchema: tool.inputSchema as ToolInputSchema,
62
+ annotations: tool.annotations,
63
+ })),
64
+ }));
65
+
66
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
67
+ const { name } = request.params;
68
+ const tool = tools.find((candidate) => candidate.name === name);
69
+ const run = TOOL_RUNNERS[name];
70
+ if (!tool || !run) throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${name}`);
71
+
72
+ const args = request.params.arguments ?? {};
73
+ const problems = validateMcpToolArguments(tool, args, options);
74
+ if (problems.length > 0) return errorResult(`Invalid arguments for ${name}:\n- ${problems.join("\n- ")}`);
75
+
76
+ try {
77
+ return toCallToolResult(await run(core, args, extra.signal));
78
+ } catch (error) {
79
+ return errorResult(error instanceof Error ? error.message : String(error));
80
+ }
81
+ });
82
+
83
+ return server;
84
+ }
@@ -0,0 +1,143 @@
1
+ // MCP-only tool definitions: names, descriptions, and input schemas for the
2
+ // MCP server. Deliberately independent of the Pi tool schemas in
3
+ // index.ts so MCP changes never touch Pi's provider-facing definitions.
4
+ // Pi-only parameters (workflow/curator, prompt, answerModel, timestamp, frames,
5
+ // model, auth) are not exposed; unknown properties are rejected.
6
+
7
+ import { Type, type TSchema } from "typebox";
8
+ import { Value } from "typebox/value";
9
+ import { getCustomSearchProviderNames, RESOLVED_SEARCH_PROVIDERS, removedSearchProviderMessage } from "./gemini-search.ts";
10
+
11
+ function stringEnum(values: readonly string[], description?: string) {
12
+ return Type.Unsafe<string>({ type: "string", enum: [...values], ...(description && { description }) });
13
+ }
14
+
15
+ // Standalone MCP has no Pi login. Only the embedded host opts into Pi providers.
16
+ const MCP_SEARCH_PROVIDERS = RESOLVED_SEARCH_PROVIDERS.filter((provider) => provider !== "kimi");
17
+
18
+ // Names are checked in validateMcpToolArguments instead of listed in the schema: the
19
+ // provider enum, written for both the single and list forms, was ~1,060 characters per tool.
20
+ const providerSchema = Type.Union([
21
+ Type.String(),
22
+ Type.Array(Type.String(), { minItems: 1 }),
23
+ ], { description: "auto, all, a name, or a list of names searched together; omit for the configured default." });
24
+ function providerProblem(value: unknown, piContext: boolean): string | undefined {
25
+ const providers = piContext ? RESOLVED_SEARCH_PROVIDERS : MCP_SEARCH_PROVIDERS;
26
+ const unlisted = typeof value === "string"
27
+ ? (value === "auto" || value === "all" || providers.includes(value as never) ? [] : [value])
28
+ : Array.isArray(value) ? value.filter((name) => !providers.includes(name)) : [];
29
+ if (unlisted.length === 0) return undefined;
30
+ let custom: readonly string[];
31
+ try {
32
+ custom = getCustomSearchProviderNames();
33
+ } catch {
34
+ return undefined; // The core reports the same configuration error.
35
+ }
36
+ const invalid = unlisted.filter((name) => !custom.includes(name));
37
+ if (invalid.length === 0) return undefined;
38
+ const removed = invalid.map((name) => removedSearchProviderMessage(name)).find(Boolean);
39
+ if (removed) return `/provider: ${removed}`;
40
+ return `/provider: unknown provider ${invalid.map((name) => JSON.stringify(name)).join(", ")}. Use auto, all, or one or more of: ${providers.join(", ")}.${custom.length > 0 ? ` Custom: ${custom.join(", ")}.` : ""}`;
41
+ }
42
+
43
+ const recencySchema = stringEnum(["day", "week", "month", "year"]);
44
+ const domainFilterSchema = Type.Array(Type.String(), { description: "Prefix - to exclude" });
45
+ const numResultsSchema = Type.Integer({ minimum: 1, maximum: 20, description: "Default 5" });
46
+ const proxySchema = Type.String({ description: "Proxy URL; omit by default; \"\" forces direct" });
47
+ // Page fetches write a page cache and clone GitHub URLs into a temp directory,
48
+ // including the fetches behind includeContent and fetchContent.
49
+ const fetchingAnnotations = { readOnlyHint: false, destructiveHint: false, openWorldHint: true };
50
+
51
+ export interface McpToolDefinition {
52
+ name: string;
53
+ description: string;
54
+ inputSchema: TSchema;
55
+ annotations: { readOnlyHint: boolean; destructiveHint?: boolean; openWorldHint: boolean };
56
+ }
57
+
58
+ export const MCP_TOOL_DEFINITIONS: readonly McpToolDefinition[] = [
59
+ {
60
+ name: "web_search",
61
+ description: "Search the web for sources or answers. Full results are stored for retrieval with get_search_content by responseId. Prefer 2-4 varied queries.",
62
+ inputSchema: Type.Object({
63
+ query: Type.Optional(Type.String()),
64
+ queries: Type.Optional(Type.Array(Type.String(), { description: "Run concurrently; vary the angle" })),
65
+ objective: Type.Optional(Type.String({ maxLength: 4096, description: "Goal; Exa API, Parallel" })),
66
+ numResults: Type.Optional(numResultsSchema),
67
+ includeContent: Type.Optional(Type.Boolean({ description: "Also fetch full page content" })),
68
+ recencyFilter: Type.Optional(recencySchema),
69
+ domainFilter: Type.Optional(domainFilterSchema),
70
+ category: Type.Optional(Type.String({ description: "Exa only, e.g. news" })),
71
+ provider: Type.Optional(providerSchema),
72
+ proxy: Type.Optional(proxySchema),
73
+ }, { additionalProperties: false }),
74
+ annotations: fetchingAnnotations,
75
+ },
76
+ {
77
+ name: "fetch_content",
78
+ description: "Fetch web pages, PDFs, and GitHub repos. Full content is stored for retrieval with get_search_content by responseId.",
79
+ inputSchema: Type.Object({
80
+ url: Type.Optional(Type.String()),
81
+ urls: Type.Optional(Type.Array(Type.String())),
82
+ mode: Type.Optional(stringEnum(["readable", "raw"], "readable (default): main text as markdown; raw: exact text body, direct HTTP only; no forceClone")),
83
+ forceClone: Type.Optional(Type.Boolean({ description: "Clone GitHub repos over the size limit" })),
84
+ proxy: Type.Optional(proxySchema),
85
+ }, { additionalProperties: false }),
86
+ annotations: fetchingAnnotations,
87
+ },
88
+ {
89
+ name: "get_search_content",
90
+ description: "Page through or search stored content from web_search, source_check, or fetch_content by responseId.",
91
+ inputSchema: Type.Object({
92
+ responseId: Type.String(),
93
+ query: Type.Optional(Type.String()),
94
+ queryIndex: Type.Optional(Type.Integer({ minimum: 0 })),
95
+ url: Type.Optional(Type.String()),
96
+ urlIndex: Type.Optional(Type.Integer({ minimum: 0 })),
97
+ offset: Type.Optional(Type.Integer({ minimum: 0 })),
98
+ limit: Type.Optional(Type.Integer({ minimum: 1, description: "Characters, default the maximum" })),
99
+ findText: Type.Optional(Type.Union([
100
+ Type.String({ minLength: 1, maxLength: 500 }),
101
+ Type.Array(Type.String({ minLength: 1, maxLength: 500 }), { minItems: 1, maxItems: 10 }),
102
+ ], { description: "Find passages instead of paging" })),
103
+ findMode: Type.Optional(stringEnum(["exact", "case-insensitive", "fuzzy"])),
104
+ }, { additionalProperties: false }),
105
+ annotations: { readOnlyHint: true, openWorldHint: false },
106
+ },
107
+ {
108
+ name: "source_check",
109
+ description: "Gather cited web passages about a claim for manual review.",
110
+ inputSchema: Type.Object({
111
+ claim: Type.String({ description: "Assertion to check" }),
112
+ queries: Type.Optional(Type.Array(Type.String(), { description: "Default: the claim" })),
113
+ numResults: Type.Optional(numResultsSchema),
114
+ fetchContent: Type.Optional(Type.Boolean({ description: "Fetch top 5 pages for exact passages" })),
115
+ recencyFilter: Type.Optional(recencySchema),
116
+ domainFilter: Type.Optional(domainFilterSchema),
117
+ provider: Type.Optional(providerSchema),
118
+ proxy: Type.Optional(proxySchema),
119
+ }, { additionalProperties: false }),
120
+ annotations: fetchingAnnotations,
121
+ },
122
+ ];
123
+
124
+ /** Returns human-readable validation problems; an empty array means the arguments are valid. */
125
+ export function validateMcpToolArguments(tool: McpToolDefinition, args: unknown, { piContext = false }: { piContext?: boolean } = {}): string[] {
126
+ const checksProvider = (tool.inputSchema as { properties?: Record<string, unknown> }).properties?.provider !== undefined;
127
+ const provider = checksProvider && typeof args === "object" && args !== null
128
+ ? providerProblem((args as { provider?: unknown }).provider, piContext)
129
+ : undefined;
130
+ if (Value.Check(tool.inputSchema, args)) return provider ? [provider] : [];
131
+ const problems = new Set<string>();
132
+ if (provider) problems.add(provider);
133
+ for (const error of Value.Errors(tool.inputSchema, args)) {
134
+ // additionalProperties also reports a per-property "schema is false"; the summary below names the property.
135
+ if (error.keyword === "boolean") continue;
136
+ const path = error.instancePath || "arguments";
137
+ const unknown = error.keyword === "additionalProperties"
138
+ ? (error.params as { additionalProperties?: string[] }).additionalProperties
139
+ : undefined;
140
+ problems.add(unknown?.length ? `${path}: unknown properties ${unknown.join(", ")}` : `${path}: ${error.message}`);
141
+ }
142
+ return problems.size > 0 ? [...problems] : ["arguments do not match the input schema"];
143
+ }
@@ -0,0 +1,268 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
4
+ import type { SearchOptions, SearchResponse, SearchResult } from "./perplexity.ts";
5
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
6
+ import { getWebSearchConfigPath, resolveProviderApiUrl, fetchWithCredentialRedirects } from "./utils.ts";
7
+
8
+ const MISTRAL_CONVERSATIONS_URL = "https://api.mistral.ai/v1/conversations";
9
+ const CONFIG_PATH = getWebSearchConfigPath();
10
+ const SEARCH_TIMEOUT_MS = 60_000;
11
+ const DEFAULT_SEARCH_MODEL = "mistral-small-latest";
12
+ const DEFAULT_SEARCH_TOOL = "web_search";
13
+ const MAX_RESULTS = 20;
14
+
15
+ type MistralSearchTool = "web_search" | "web_search_premium";
16
+
17
+ interface WebSearchConfig {
18
+ mistralSearchBaseUrl?: unknown;
19
+ mistralApiKey?: unknown;
20
+ mistralSearchModel?: unknown;
21
+ mistralSearchTool?: unknown;
22
+ }
23
+
24
+ interface DomainFilters {
25
+ include: string[];
26
+ exclude: string[];
27
+ }
28
+
29
+ let cachedConfig: WebSearchConfig | null = null;
30
+
31
+ function loadConfig(): WebSearchConfig {
32
+ if (cachedConfig) return cachedConfig;
33
+ if (!existsSync(CONFIG_PATH)) {
34
+ cachedConfig = {};
35
+ return cachedConfig;
36
+ }
37
+
38
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
39
+ let parsed: unknown;
40
+ try {
41
+ parsed = JSON.parse(raw);
42
+ } catch (err) {
43
+ const message = err instanceof Error ? err.message : String(err);
44
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
45
+ }
46
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
47
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
48
+ }
49
+ cachedConfig = parsed as WebSearchConfig;
50
+ return cachedConfig;
51
+ }
52
+
53
+ function resolveSearchModel(value: unknown): string {
54
+ if (value === undefined) return DEFAULT_SEARCH_MODEL;
55
+ if (typeof value !== "string" || value.trim().length === 0) {
56
+ throw new Error(`mistralSearchModel in ${CONFIG_PATH} must be a non-empty string`);
57
+ }
58
+ return value.trim();
59
+ }
60
+
61
+ function resolveSearchTool(value: unknown): MistralSearchTool {
62
+ if (value === undefined) return DEFAULT_SEARCH_TOOL;
63
+ if (value !== "web_search" && value !== "web_search_premium") {
64
+ throw new Error(`mistralSearchTool in ${CONFIG_PATH} must be either web_search or web_search_premium`);
65
+ }
66
+ return value;
67
+ }
68
+
69
+ function normalizeCount(value: number | undefined): number {
70
+ if (typeof value !== "number" || !Number.isFinite(value)) return 5;
71
+ return Math.max(1, Math.min(Math.floor(value), MAX_RESULTS));
72
+ }
73
+
74
+ function parseDomainFilters(domainFilter: string[] | undefined): DomainFilters {
75
+ const filters: DomainFilters = { include: [], exclude: [] };
76
+ for (const raw of domainFilter ?? []) {
77
+ const domain = normalizeDomain(raw);
78
+ if (!domain) continue;
79
+ const target = raw.trim().startsWith("-") ? filters.exclude : filters.include;
80
+ if (!target.includes(domain)) target.push(domain);
81
+ }
82
+ return filters;
83
+ }
84
+
85
+ function passesDomainFilters(url: string, filters: DomainFilters): boolean {
86
+ if (filters.include.length === 0 && filters.exclude.length === 0) return true;
87
+ const hostname = new URL(url).hostname.toLowerCase();
88
+ const matches = (domain: string) => hostname === domain || hostname.endsWith(`.${domain}`);
89
+ if (filters.exclude.some(matches)) return false;
90
+ return filters.include.length === 0 || filters.include.some(matches);
91
+ }
92
+
93
+ function normalizeResultUrl(value: unknown): string | null {
94
+ if (typeof value !== "string") return null;
95
+ const url = value.trim();
96
+ if (!url) return null;
97
+ try {
98
+ const parsed = new URL(url);
99
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
100
+ } catch {
101
+ return null;
102
+ }
103
+ return url;
104
+ }
105
+
106
+ function buildSearchPrompt(query: string, options: SearchOptions, numResults: number): string {
107
+ const lines: string[] = [];
108
+ if (options.recencyFilter) {
109
+ const labels: Record<string, string> = {
110
+ day: "past 24 hours",
111
+ week: "past week",
112
+ month: "past month",
113
+ year: "past year",
114
+ };
115
+ lines.push(`Prefer sources from the ${labels[options.recencyFilter] ?? options.recencyFilter}.`);
116
+ }
117
+ if (typeof options.numResults === "number" && Number.isFinite(options.numResults) && options.numResults > 0) {
118
+ lines.push(`Prefer up to ${numResults} distinct sources.`);
119
+ }
120
+
121
+ const filters = parseDomainFilters(options.domainFilter);
122
+ if (filters.include.length > 0) lines.push(`Only use sources from: ${filters.include.slice(0, 100).join(", ")}.`);
123
+ if (filters.exclude.length > 0) lines.push(`Do not use sources from: ${filters.exclude.slice(0, 100).join(", ")}.`);
124
+ return lines.length > 0 ? `${lines.join(" ")}\n\n${query}` : query;
125
+ }
126
+
127
+ function errorMessage(err: unknown): string {
128
+ return err instanceof Error ? err.message : String(err);
129
+ }
130
+
131
+ function invalidResponse(message: string): Error {
132
+ return new Error(`Mistral API returned invalid response: ${message}`);
133
+ }
134
+
135
+ function parseConversationResponse(value: unknown, options: SearchOptions, numResults: number): SearchResponse {
136
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
137
+ throw invalidResponse("expected an object envelope");
138
+ }
139
+ const outputs = (value as Record<string, unknown>).outputs;
140
+ if (!Array.isArray(outputs)) throw invalidResponse("outputs must be an array");
141
+
142
+ const answerParts: string[] = [];
143
+ const results: SearchResult[] = [];
144
+ const seenUrls = new Set<string>();
145
+ const domainFilters = parseDomainFilters(options.domainFilter);
146
+
147
+ for (const output of outputs) {
148
+ if (!output || typeof output !== "object" || Array.isArray(output)) continue;
149
+ const entry = output as Record<string, unknown>;
150
+ if (entry.type !== "message.output") continue;
151
+ const content = entry.content;
152
+ if (typeof content === "string") {
153
+ if (content.trim()) answerParts.push(content.trim());
154
+ continue;
155
+ }
156
+ if (!Array.isArray(content)) continue;
157
+
158
+ for (const chunk of content) {
159
+ if (!chunk || typeof chunk !== "object" || Array.isArray(chunk)) continue;
160
+ const part = chunk as Record<string, unknown>;
161
+ if (part.type === "text") {
162
+ if (typeof part.text === "string" && part.text.trim()) answerParts.push(part.text.trim());
163
+ continue;
164
+ }
165
+ if (part.type !== "tool_reference" || results.length >= numResults) continue;
166
+
167
+ const url = normalizeResultUrl(part.url);
168
+ if (!url || !passesDomainFilters(url, domainFilters) || seenUrls.has(url)) continue;
169
+ seenUrls.add(url);
170
+ const title = typeof part.title === "string" && part.title.trim() ? part.title.trim() : url;
171
+ const snippet = typeof part.description === "string" ? part.description : "";
172
+ results.push({ title, url, snippet });
173
+ }
174
+ }
175
+
176
+ const answer = answerParts.join("\n").trim();
177
+ if (!answer && results.length === 0) throw invalidResponse("no answer or sources");
178
+ return { answer, results };
179
+ }
180
+
181
+ async function getApiKey(signal?: AbortSignal): Promise<string> {
182
+ const apiKey = await resolveCredential({
183
+ provider: "Mistral",
184
+ configuredValue: loadConfig().mistralApiKey,
185
+ environmentValue: process.env.MISTRAL_API_KEY,
186
+ signal,
187
+ });
188
+ if (!apiKey) {
189
+ throw new Error(
190
+ "Mistral API key not found. Either:\n" +
191
+ ` 1. Create ${CONFIG_PATH} with { "mistralApiKey": "your-key" }\n` +
192
+ " 2. Set MISTRAL_API_KEY environment variable\n" +
193
+ "Get a key at https://console.mistral.ai/api-keys",
194
+ );
195
+ }
196
+ return apiKey;
197
+ }
198
+
199
+ export function isMistralAvailable(): boolean {
200
+ try {
201
+ const config = loadConfig();
202
+ resolveSearchModel(config.mistralSearchModel);
203
+ resolveSearchTool(config.mistralSearchTool);
204
+ return hasCredentialSource({
205
+ provider: "Mistral",
206
+ configuredValue: config.mistralApiKey,
207
+ environmentValue: process.env.MISTRAL_API_KEY,
208
+ });
209
+ } catch {
210
+ return false;
211
+ }
212
+ }
213
+
214
+ export async function searchWithMistral(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
215
+ const config = loadConfig();
216
+ const model = options.model ?? resolveSearchModel(config.mistralSearchModel);
217
+ const tool = resolveSearchTool(config.mistralSearchTool);
218
+ const numResults = normalizeCount(options.numResults);
219
+ const apiKey = await getApiKey(options.signal);
220
+ const requestSignal = options.signal
221
+ ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal])
222
+ : AbortSignal.timeout(SEARCH_TIMEOUT_MS);
223
+ const activityId = activityMonitor.logStart({ type: "api", query });
224
+
225
+ try {
226
+ const response = await fetchWithCredentialRedirects(resolveProviderApiUrl("mistralSearch", MISTRAL_CONVERSATIONS_URL, loadConfig().mistralSearchBaseUrl), {
227
+ method: "POST",
228
+ headers: {
229
+ Authorization: `Bearer ${apiKey}`,
230
+ "Content-Type": "application/json",
231
+ },
232
+ body: JSON.stringify({
233
+ inputs: [{ role: "user", content: buildSearchPrompt(query, options, numResults) }],
234
+ stream: false,
235
+ model,
236
+ tools: [{ type: tool }],
237
+ }),
238
+ signal: requestSignal,
239
+ }, ["Authorization"]);
240
+
241
+ if (!response.ok) {
242
+ const errorText = redactCredential(await response.text(), apiKey);
243
+ throw new Error(`Mistral API error ${response.status}: ${errorText.slice(0, 300)}`);
244
+ }
245
+
246
+ let parsed: unknown;
247
+ try {
248
+ parsed = await response.json();
249
+ } catch (err) {
250
+ throw new Error(`Mistral API returned invalid JSON: ${errorMessage(err)}`);
251
+ }
252
+ const result = parseConversationResponse(parsed, options, numResults);
253
+ activityMonitor.logComplete(activityId, response.status);
254
+ return result;
255
+ } catch (err) {
256
+ const message = errorMessage(err);
257
+ const redactedMessage = redactCredential(message, apiKey);
258
+ if (redactedMessage.toLowerCase().includes("abort")) {
259
+ activityMonitor.logComplete(activityId, 0);
260
+ } else {
261
+ activityMonitor.logError(activityId, redactedMessage);
262
+ }
263
+ if (redactedMessage === message) throw err;
264
+ const redactedError = new Error(redactedMessage);
265
+ if (err instanceof Error) redactedError.name = err.name;
266
+ throw redactedError;
267
+ }
268
+ }
package/ninerouter.ts ADDED
@@ -0,0 +1,92 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { redactCredential, resolveCredential } from "./credential-source.ts";
4
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
5
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
6
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
7
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
8
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveApiBaseUrl } from "./utils.ts";
9
+
10
+ // 9router (https://github.com/decolua/9router) is a self-hosted router whose POST /v1/search
11
+ // fronts many search APIs. It has no official host, so the base URL is required.
12
+ const CONFIG_PATH = getWebSearchConfigPath();
13
+ const SEARCH_TIMEOUT_MS = 30_000;
14
+
15
+ function loadConfig(): Record<string, unknown> {
16
+ if (!existsSync(CONFIG_PATH)) return {};
17
+ let parsed: unknown;
18
+ // JSON parse errors can quote credentials from the file, so they are not echoed.
19
+ try { parsed = JSON.parse(readFileSync(CONFIG_PATH, "utf-8")); } catch { parsed = undefined; }
20
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
21
+ return parsed as Record<string, unknown>;
22
+ }
23
+
24
+ export function isNineRouterAvailable(): boolean {
25
+ const base = process.env.NINEROUTER_BASE_URL ?? loadConfig().ninerouterBaseUrl;
26
+ return typeof base === "string" && base.trim().length > 0;
27
+ }
28
+
29
+ export async function searchWithNineRouter(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
30
+ const config = loadConfig();
31
+ const base = resolveApiBaseUrl({ configKey: "ninerouterBaseUrl", configuredValue: config.ninerouterBaseUrl, defaultValue: "", environmentKey: "NINEROUTER_BASE_URL", environmentValue: process.env.NINEROUTER_BASE_URL });
32
+ if (!base) throw new Error(`9router base URL not found. Set ninerouterBaseUrl in ${CONFIG_PATH} or NINEROUTER_BASE_URL (e.g. https://your-router/v1)`);
33
+ const provider = process.env.NINEROUTER_SEARCH_PROVIDER || config.ninerouterProvider || "serper";
34
+ if (typeof provider !== "string") throw new Error(`ninerouterProvider in ${CONFIG_PATH} must be a string`);
35
+ // The key is optional: a self-hosted router may run with auth disabled.
36
+ const apiKey = await resolveCredential({ provider: "9router", configuredValue: config.ninerouterApiKey, environmentValue: process.env.NINEROUTER_API_KEY, signal: options.signal });
37
+ const include: string[] = [];
38
+ const exclude: string[] = [];
39
+ for (const raw of options.domainFilter ?? []) {
40
+ const domain = normalizeDomain(raw);
41
+ if (domain) (raw.trim().startsWith("-") ? exclude : include).push(domain);
42
+ }
43
+ const numResults = normalizeSearchResultCount(options.numResults);
44
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
45
+ const activityId = activityMonitor.logStart({ type: "api", query });
46
+ let data: { results?: unknown; answer?: unknown } | null;
47
+ try {
48
+ const response = await fetchWithCredentialRedirects(`${base}/search`, {
49
+ method: "POST",
50
+ headers: { ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), "Content-Type": "application/json", Accept: "application/json" },
51
+ body: JSON.stringify({
52
+ provider,
53
+ query,
54
+ max_results: numResults,
55
+ ...(options.recencyFilter ? { time_range: options.recencyFilter } : {}),
56
+ ...(include.length ? { domain_filter: include } : {}),
57
+ }),
58
+ signal: options.signal ? AbortSignal.any([timeout, options.signal]) : timeout,
59
+ }, ["Authorization"]);
60
+ // The status stays in the message so searchRouting can classify quota and transient failures.
61
+ if (!response.ok) throw new Error(`9router error ${response.status}: ${redactCredential(await response.text(), apiKey).slice(0, 300)}`);
62
+ // Syntax errors can quote the body, so they are not echoed; a stalled body read reaches the timeout check below.
63
+ data = await response.json().catch((err: unknown) => { throw err instanceof SyntaxError ? new Error("9router returned invalid JSON") : err; });
64
+ activityMonitor.logComplete(activityId, response.status);
65
+ } catch (err) {
66
+ // Node reports the deadline as "aborted due to timeout", which routing would treat as a cancellation.
67
+ if (!options.signal?.aborted && (timeout.aborted || (err instanceof Error && err.name === "TimeoutError"))) {
68
+ const message = `9router request timed out after ${SEARCH_TIMEOUT_MS / 1000}s`;
69
+ activityMonitor.logError(activityId, message);
70
+ throw new Error(message);
71
+ }
72
+ const message = redactCredential(err instanceof Error ? err.message : String(err), apiKey);
73
+ activityMonitor.logError(activityId, message);
74
+ if (err instanceof Error && err.message === message) throw err;
75
+ throw new Error(message);
76
+ }
77
+ if (!Array.isArray(data?.results)) throw new Error("9router returned invalid response: expected results array");
78
+ const results: SearchResponse["results"] = [];
79
+ for (const entry of data.results as { title?: unknown; url?: unknown; snippet?: unknown }[]) {
80
+ let url: URL;
81
+ try { url = new URL(String(entry?.url)); } catch { continue; }
82
+ if (url.protocol !== "https:" && url.protocol !== "http:") continue;
83
+ const matches = (domain: string) => url.hostname === domain || url.hostname.endsWith(`.${domain}`);
84
+ // Not every upstream honours domain_filter, and exclusions are only applied here.
85
+ if (exclude.some(matches) || (include.length && !include.some(matches))) continue;
86
+ const title = typeof entry.title === "string" && entry.title.trim() ? entry.title.trim() : `Source ${results.length + 1}`;
87
+ results.push({ title, url: url.href, snippet: typeof entry.snippet === "string" ? entry.snippet : "" });
88
+ if (results.length >= numResults) break;
89
+ }
90
+ const answer = typeof data.answer === "string" ? data.answer.trim() : "";
91
+ return { answer: answer || formatSearchResultsAsAnswer(results), results };
92
+ }
@@ -0,0 +1,72 @@
1
+ // Asks a classifier model from Pi's catalog whether a search response addresses its query, for the
2
+ // searchRouting "off-topic" fallback (#619). eval/offtopic-judge.mjs measured the thresholds.
3
+ import type { ClassifierContext } from "@earendil-works/pi-ai";
4
+ import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
5
+ import { isRecord } from "./utils.ts";
6
+
7
+ const LABELS = ["addresses", "off_topic"] as const;
8
+ type Label = typeof LABELS[number];
9
+
10
+ // Frozen after calibration (docs/offtopic-judge.md); change it only after re-measuring.
11
+ const INSTRUCTIONS = "A search engine returned this answer and these results for the query. addresses: the answer or at least one result is about what the query asks for, even if incomplete or outdated. off_topic: nothing is about what the query asks for, including results that only share words with it, a different meaning of the same word, or a different product.";
12
+
13
+ /** The only Pi classifier references accepted, each with its measured off_topic threshold (docs/offtopic-judge.md). */
14
+ export const OFFTOPIC_JUDGE_MODELS = {
15
+ "cloudflare-workers-ai/@cf/cloudflare/clef": 0.85,
16
+ "typesafe/jev-latest": 0.85,
17
+ "cloudflare-workers-ai/typesafe/jev-1.14.0": 0.85,
18
+ } as const;
19
+ export type OffTopicJudgeModel = keyof typeof OFFTOPIC_JUDGE_MODELS;
20
+
21
+ export type OffTopicResult = { title: string; url: string; snippet: string };
22
+ export type OffTopicJudgment = { probabilities: Record<Label, number> } | { error: string };
23
+
24
+ const TIMEOUT_MS = 10_000;
25
+ const MAX_RESULTS = 10;
26
+ const MAX_ANSWER_CHARS = 4_000;
27
+ const MAX_SNIPPET_CHARS = 500;
28
+ const PROBABILITY_SUM_TOLERANCE = 0.02;
29
+
30
+ /** Returns the model's probabilities for "addresses" and "off_topic"; every model failure is an error, a caller abort is rethrown. */
31
+ export async function judgeOffTopic(
32
+ model: OffTopicJudgeModel,
33
+ query: string,
34
+ response: { answer: string; results: OffTopicResult[] },
35
+ modelRegistry: Pick<ModelRegistry, "findOfType" | "classify">,
36
+ signal?: AbortSignal,
37
+ ): Promise<OffTopicJudgment> {
38
+ if (typeof modelRegistry.findOfType !== "function" || typeof modelRegistry.classify !== "function") return { error: "this Pi version cannot run classifier models; update Pi" };
39
+ const slash = model.indexOf("/");
40
+ const classifier = modelRegistry.findOfType("classifier", model.slice(0, slash), model.slice(slash + 1));
41
+ if (!classifier) return { error: `${model} is not in this Pi's classifier catalog` };
42
+ const context: ClassifierContext = {
43
+ state: {
44
+ query,
45
+ answer: response.answer.slice(0, MAX_ANSWER_CHARS),
46
+ results: response.results.slice(0, MAX_RESULTS).map(({ title, url, snippet }) => ({ title, url, snippet: snippet.slice(0, MAX_SNIPPET_CHARS) })),
47
+ },
48
+ // Null criteria: empty strings changed Clef's answers.
49
+ questions: { relevance: { type: "choice", instructions: INSTRUCTIONS, criteria: { addresses: null, off_topic: null } as unknown as Record<string, string> } },
50
+ };
51
+ const timeout = AbortSignal.timeout(TIMEOUT_MS);
52
+ try {
53
+ const result = await modelRegistry.classify(classifier, context, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
54
+ signal?.throwIfAborted();
55
+ if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS / 1000} s` };
56
+ if (result.stopReason !== "stop") return { error: result.errorMessage || `the model stopped with ${result.stopReason}` };
57
+ const answer: unknown = result.answers?.relevance;
58
+ const probabilities = isRecord(answer) ? answer.probabilities : undefined;
59
+ if (!isRecord(answer) || !LABELS.includes(answer.choice as Label) || !isRecord(probabilities)) return { error: "the response is invalid: relevance choice is not one of its labels" };
60
+ const keys = Object.keys(probabilities);
61
+ const values = LABELS.map((label) => probabilities[label]);
62
+ if (keys.length !== LABELS.length || !values.every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1)) {
63
+ return { error: "the response is invalid: relevance probabilities do not match the labels" };
64
+ }
65
+ if (Math.abs((values as number[]).reduce((total, value) => total + value, 0) - 1) > PROBABILITY_SUM_TOLERANCE) return { error: "the response is invalid: relevance probabilities do not sum to 1" };
66
+ return { probabilities: probabilities as Record<Label, number> };
67
+ } catch (err) {
68
+ signal?.throwIfAborted();
69
+ if (timeout.aborted) return { error: `timed out after ${TIMEOUT_MS / 1000} s` };
70
+ return { error: err instanceof Error ? err.message : String(err) };
71
+ }
72
+ }