@herbertgao/pi-extensions 2026.11.1 → 2026.11.3

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 (76) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +14 -14
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +1 -1
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +1 -1
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +109 -16
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/write-execution.ts +5 -1
  9. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  10. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +12 -0
  11. package/node_modules/@herbertgao/pi-subagents/README.md +54 -42
  12. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +1 -1
  13. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +2 -0
  14. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  15. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +9 -8
  16. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +70 -9
  17. package/node_modules/@herbertgao/pi-subagents/src/agent-record-entry.ts +183 -0
  18. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +156 -13
  19. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +52 -8
  20. package/node_modules/@herbertgao/pi-subagents/src/default-agents.ts +3 -4
  21. package/node_modules/@herbertgao/pi-subagents/src/index.ts +158 -56
  22. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +3 -2
  23. package/node_modules/@herbertgao/pi-subagents/src/status-note.ts +3 -1
  24. package/node_modules/@herbertgao/pi-subagents/src/types.ts +5 -0
  25. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +167 -7
  26. package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +8 -4
  27. package/node_modules/@herbertgao/pi-subagents/src/workflow/host.ts +88 -6
  28. package/node_modules/@herbertgao/pi-subagents/src/workflow/progress.ts +3 -2
  29. package/node_modules/@narumitw/pi-btw/CHANGELOG.md +259 -0
  30. package/node_modules/@narumitw/pi-btw/package.json +6 -5
  31. package/node_modules/@narumitw/pi-caffeinate/CHANGELOG.md +70 -0
  32. package/node_modules/@narumitw/pi-caffeinate/package.json +5 -4
  33. package/node_modules/pi-commandcode-provider/CHANGELOG.md +21 -0
  34. package/node_modules/pi-commandcode-provider/README.md +18 -6
  35. package/node_modules/pi-commandcode-provider/index.ts +11 -5
  36. package/node_modules/pi-commandcode-provider/package.json +1 -1
  37. package/node_modules/pi-commandcode-provider/src/api-key.ts +26 -10
  38. package/node_modules/pi-commandcode-provider/src/auth-server.ts +33 -24
  39. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +2 -2
  40. package/node_modules/pi-commandcode-provider/src/converters.ts +3 -61
  41. package/node_modules/pi-commandcode-provider/src/core.ts +29 -4
  42. package/node_modules/pi-commandcode-provider/src/cost.ts +32 -12
  43. package/node_modules/pi-commandcode-provider/src/oauth.ts +40 -6
  44. package/node_modules/pi-commandcode-provider/src/pricing.ts +5 -3
  45. package/node_modules/pi-commandcode-provider/src/runtime.ts +14 -7
  46. package/node_modules/pi-commandcode-provider/src/transport.ts +6 -3
  47. package/node_modules/pi-provider-qoder/README.md +40 -0
  48. package/node_modules/pi-provider-qoder/dist/index.js +64 -0
  49. package/node_modules/pi-provider-qoder/package.json +4 -3
  50. package/node_modules/pi-typesafe/README.md +3 -3
  51. package/node_modules/pi-typesafe/dist/auth.d.ts +21 -4
  52. package/node_modules/pi-typesafe/dist/auth.js +32 -7
  53. package/node_modules/pi-typesafe/dist/backends.d.ts +2 -2
  54. package/node_modules/pi-typesafe/dist/backends.js +9 -0
  55. package/node_modules/pi-typesafe/dist/client.js +7 -12
  56. package/node_modules/pi-typesafe/dist/errors.d.ts +3 -2
  57. package/node_modules/pi-typesafe/dist/errors.js +12 -10
  58. package/node_modules/pi-typesafe/dist/extension.js +14 -10
  59. package/node_modules/pi-typesafe/package.json +1 -1
  60. package/node_modules/pi-web-access/CHANGELOG.md +22 -0
  61. package/node_modules/pi-web-access/README.md +31 -12
  62. package/node_modules/pi-web-access/curator-page.ts +5 -1
  63. package/node_modules/pi-web-access/curator-server.ts +2 -0
  64. package/node_modules/pi-web-access/dist/index.js +673 -308
  65. package/node_modules/pi-web-access/dist/mcp-cli.js +666 -309
  66. package/node_modules/pi-web-access/gemini-search.ts +12 -4
  67. package/node_modules/pi-web-access/github-api.ts +1 -1
  68. package/node_modules/pi-web-access/github-extract.ts +3 -2
  69. package/node_modules/pi-web-access/index.ts +7 -3
  70. package/node_modules/pi-web-access/mcp-tool-definitions.ts +1 -1
  71. package/node_modules/pi-web-access/outcrawl.ts +204 -0
  72. package/node_modules/pi-web-access/package.json +2 -2
  73. package/node_modules/pi-web-access/sofya.ts +201 -0
  74. package/node_modules/pi-web-access/utils.ts +16 -6
  75. package/node_modules/pi-web-access/web-tool-core.ts +4 -0
  76. package/package.json +11 -11
@@ -54,12 +54,14 @@ import { isLinkupAvailable, searchWithLinkup } from "./linkup.ts";
54
54
  import { isNineRouterAvailable, searchWithNineRouter } from "./ninerouter.ts";
55
55
  import { isCloudflareSearchAvailable, searchWithCloudflare } from "./cloudflare-search.ts";
56
56
  import { isSearchApiAvailable, searchWithSearchApi } from "./searchapi.ts";
57
+ import { isOutcrawlAvailable, searchWithOutcrawl } from "./outcrawl.ts";
58
+ import { isSofyaAvailable, searchWithSofya } from "./sofya.ts";
57
59
  import { isDeepSeekAvailable, searchWithDeepSeek } from "./deepseek.ts";
58
60
  import { isKimiSearchAvailable, searchWithKimi } from "./kimi-search.ts";
59
61
  import { isMistralAvailable, searchWithMistral } from "./mistral-search.ts";
60
62
  import { getWebSearchConfigPath } from "./utils.ts";
61
63
 
62
- export const RESOLVED_SEARCH_PROVIDERS = ["openai", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "you", "firecrawl", "jina", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "exa", "serpdive", "kagi", "ollama", "anysearch", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "bocha", "xcrawl", "baizhi", "zai", "keenable", "ceramic", "deepseek", "linkup", "ninerouter", "cloudflare", "searchapi", "tabstack"] as const;
64
+ export const RESOLVED_SEARCH_PROVIDERS = ["openai", "brave", "parallel", "parallel-mcp", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "you", "firecrawl", "jina", "searxng", "degoog", "duckduckgo", "perplexity", "gemini", "kimi", "exa", "serpdive", "kagi", "ollama", "anysearch", "xai", "mistral", "brightdata", "serpbase", "serpapi", "serper", "serply", "valyu", "bocha", "xcrawl", "baizhi", "zai", "keenable", "ceramic", "deepseek", "linkup", "ninerouter", "cloudflare", "searchapi", "outcrawl", "sofya", "tabstack"] as const;
63
65
  export const SEARCH_PROVIDERS = ["auto", "all", ...RESOLVED_SEARCH_PROVIDERS] as const;
64
66
 
65
67
  export type ResolvedSearchProvider = typeof RESOLVED_SEARCH_PROVIDERS[number];
@@ -128,7 +130,7 @@ export interface AttributedSearchResponse extends SearchResponse {
128
130
 
129
131
  const CONFIG_PATH = getWebSearchConfigPath();
130
132
  const DEFAULT_SEARCH_MODEL = "gemini-3.6-flash";
131
- // Explicit-only providers (Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, XCrawl, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, Keenable, Ceramic, DeepSeek, Linkup, 9router, Cloudflare, SearchApi, Tabstack) are deliberately absent:
133
+ // Explicit-only providers (Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, XCrawl, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, Keenable, Ceramic, DeepSeek, Linkup, 9router, Cloudflare, SearchApi, Outcrawl, Sofya, Tabstack) are deliberately absent:
132
134
  // `all` must never fan out to an opt-in or paid provider without the user asking for it.
133
135
  export const ALL_SEARCH_PROVIDERS: ResolvedSearchProvider[] = ["searxng", "openai", "exa", "brave", "parallel", "tinyfish", "search1api", "searchinfinity", "querit", "tavily", "firecrawl", "jina", "serpdive", "kagi", "ollama", "perplexity", "gemini", "bocha"];
134
136
  const VALID_ROUTING_KINDS = ["transient", "quota", "network", "invalid-response", "unsupported", "empty", "domain-miss", "off-topic"] as const;
@@ -517,6 +519,8 @@ async function searchWithResolvedProvider(
517
519
  if (provider === "ninerouter") return { ...(await searchWithNineRouter(query, options)), provider };
518
520
  if (provider === "cloudflare") return { ...(await searchWithCloudflare(query, options)), provider };
519
521
  if (provider === "searchapi") return { ...(await searchWithSearchApi(query, options)), provider };
522
+ if (provider === "outcrawl") return { ...(await searchWithOutcrawl(query, options)), provider };
523
+ if (provider === "sofya") return { ...(await searchWithSofya(query, options)), provider };
520
524
  if (provider === "deepseek") return { ...(await searchWithDeepSeek(query, options)), provider };
521
525
  if (provider === "xcrawl") return { ...(await searchWithXCrawl(query, options)), provider };
522
526
  if (provider === "perplexity") return { ...(await searchWithPerplexity(query, options)), provider };
@@ -577,6 +581,8 @@ async function isResolvedProviderAvailable(provider: ResolvedSearchProvider, opt
577
581
  if (provider === "ninerouter") return isNineRouterAvailable();
578
582
  if (provider === "cloudflare") return isCloudflareSearchAvailable();
579
583
  if (provider === "searchapi") return isSearchApiAvailable();
584
+ if (provider === "outcrawl") return isOutcrawlAvailable();
585
+ if (provider === "sofya") return isSofyaAvailable();
580
586
  if (provider === "deepseek") return isDeepSeekAvailable();
581
587
  if (provider === "xcrawl") return isXcrawlAvailable();
582
588
  if (provider === "perplexity") return isPerplexityAvailable();
@@ -631,6 +637,8 @@ export function providerLabel(provider: ResolvedSearchProvider): string {
631
637
  if (provider === "ninerouter") return "9router";
632
638
  if (provider === "cloudflare") return "Cloudflare";
633
639
  if (provider === "searchapi") return "SearchApi";
640
+ if (provider === "outcrawl") return "Outcrawl";
641
+ if (provider === "sofya") return "Sofya";
634
642
  if (provider === "deepseek") return "DeepSeek";
635
643
  return provider.charAt(0).toUpperCase() + provider.slice(1);
636
644
  }
@@ -660,7 +668,7 @@ async function searchWithProviders(
660
668
  : await isResolvedProviderAvailable(provider, options),
661
669
  })))).filter((entry) => entry.available).map((entry) => entry.provider);
662
670
  if (providers.length === 0) {
663
- throw new Error("No configured search provider available for provider \"all\". Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, XCrawl, Keenable, Ceramic, DeepSeek, Linkup, 9router, Cloudflare, SearchApi, and Tabstack are excluded.");
671
+ throw new Error("No configured search provider available for provider \"all\". Parallel MCP, degoog, DuckDuckGo, Kimi, AnySearch, xAI, Mistral, Bright Data, SerpBase, SerpApi, Serper, Serply, You.com, Valyu, Baizhi, Z.ai, XCrawl, Keenable, Ceramic, DeepSeek, Linkup, 9router, Cloudflare, SearchApi, Outcrawl, Sofya, and Tabstack are excluded.");
664
672
  }
665
673
 
666
674
  const settled = await Promise.allSettled(
@@ -904,7 +912,7 @@ export async function search(query: string, options: FullSearchOptions = {}): Pr
904
912
  " 3. Set OPENAI_API_KEY, BRAVE_API_KEY, PARALLEL_API_KEY, TINYFISH_API_KEY, SEARCH1API_KEY, SEARCHINFINITY_API_KEY, QUERIT_API_KEY, TAVILY_API_KEY, FIRECRAWL_BASE_URL, JINA_API_KEY, SERPDIVE_API_KEY, KAGI_API_KEY, BOCHA_API_KEY, OLLAMA_API_KEY, SEARXNG_BASE_URL, EXA_API_KEY, PERPLEXITY_API_KEY, GEMINI_API_KEY, or CLOUDFLARE_API_KEY env vars\n" +
905
913
  " 4. Set GOOGLE_GEMINI_BASE_URL with CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing\n" +
906
914
  " 5. Sign into gemini.google.com in a supported Chromium-based browser\n" +
907
- " 6. Explicitly select provider: \"anysearch\" for anonymous AnySearch, \"xcrawl\" for XCrawl, \"xai\" for Grok, \"mistral\" for Mistral Conversations web search, \"brightdata\" with brightdataSerpZone for paid Bright Data SERP, \"serpbase\", \"serpapi\", \"serper\", or \"serply\" for Google SERP, \"you\" for You.com, \"zai\" for Z.ai GLM Coding Plan search, \"valyu\" for research search, \"keenable\" for keyless Keenable search, \"ceramic\" for Ceramic search, \"deepseek\" for DeepSeek search, \"linkup\" for Linkup search, \"ninerouter\" for a 9router gateway, \"cloudflare\" for the Cloudflare Web Search API, \"searchapi\" for SearchApi Google search, or \"tabstack\" for Tabstack Research"
915
+ " 6. Explicitly select provider: \"anysearch\" for anonymous AnySearch, \"xcrawl\" for XCrawl, \"xai\" for Grok, \"mistral\" for Mistral Conversations web search, \"brightdata\" with brightdataSerpZone for paid Bright Data SERP, \"serpbase\", \"serpapi\", \"serper\", or \"serply\" for Google SERP, \"you\" for You.com, \"zai\" for Z.ai GLM Coding Plan search, \"valyu\" for research search, \"keenable\" for keyless Keenable search, \"ceramic\" for Ceramic search, \"deepseek\" for DeepSeek search, \"linkup\" for Linkup search, \"ninerouter\" for a 9router gateway, \"cloudflare\" for the Cloudflare Web Search API, \"searchapi\" for SearchApi Google search, \"outcrawl\" for Outcrawl search, \"sofya\" for Sofya search, or \"tabstack\" for Tabstack Research"
908
916
  );
909
917
  }
910
918
 
@@ -98,7 +98,7 @@ async function fetchReadmeViaApi(owner: string, repo: string, ref: string): Prom
98
98
  }
99
99
  try {
100
100
  const decoded = Buffer.from(stdout.trim(), "base64").toString("utf-8");
101
- resolve(decoded.length > 8192 ? decoded.slice(0, 8192) + "\n\n[README truncated at 8K chars]" : decoded);
101
+ resolve(decoded.length > MAX_INLINE_FILE_CHARS ? `${decoded.slice(0, MAX_INLINE_FILE_CHARS)}\n\n[README truncated at 100K chars]` : decoded);
102
102
  } catch {
103
103
  resolve(null);
104
104
  }
@@ -3,6 +3,7 @@ import { lstat as lstatAsync, open as openAsync, opendir as opendirAsync, readFi
3
3
  import { execFile, spawn, type ChildProcess } from "node:child_process";
4
4
  import { createHash } from "node:crypto";
5
5
  import { basename, dirname, extname, join, resolve as resolvePath, sep as pathSep } from "node:path";
6
+ import { tmpdir } from "node:os";
6
7
  import { activityMonitor } from "./activity.ts";
7
8
  import type { ExtractedContent } from "./extract.ts";
8
9
  import { checkGhAvailable, checkRepoSize, fetchViaApi, showGhHint } from "./github-api.ts";
@@ -113,7 +114,7 @@ function loadGitHubConfig(): GitHubCloneConfig {
113
114
  enabled: true,
114
115
  maxRepoSizeMB: 350,
115
116
  cloneTimeoutSeconds: 30,
116
- clonePath: "/tmp/pi-github-repos",
117
+ clonePath: join(tmpdir(), "pi-github-repos"),
117
118
  };
118
119
 
119
120
  if (!existsSync(CONFIG_PATH)) {
@@ -773,7 +774,7 @@ function readReadme(localPath: string): string | null {
773
774
  if (existsSync(readmePath)) {
774
775
  try {
775
776
  const content = readFileSync(readmePath, "utf-8");
776
- return content.length > 8192 ? content.slice(0, 8192) + "\n\n[README truncated at 8K chars]" : content;
777
+ return content.length > MAX_INLINE_FILE_CHARS ? `${content.slice(0, MAX_INLINE_FILE_CHARS)}\n\n[README truncated at 100K chars. Full file: ${readmePath}]` : content;
777
778
  } catch {
778
779
  continue;
779
780
  }
@@ -76,6 +76,8 @@ import { isLinkupAvailable } from "./linkup.ts";
76
76
  import { isNineRouterAvailable } from "./ninerouter.ts";
77
77
  import { isCloudflareSearchAvailable } from "./cloudflare-search.ts";
78
78
  import { isSearchApiAvailable } from "./searchapi.ts";
79
+ import { isOutcrawlAvailable } from "./outcrawl.ts";
80
+ import { isSofyaAvailable } from "./sofya.ts";
79
81
  import { isDeepSeekAvailable } from "./deepseek.ts";
80
82
  import { isBaizhiAvailable } from "./baizhi.ts";
81
83
  import { isZaiAvailable } from "./zai.ts";
@@ -378,6 +380,8 @@ async function getProviderAvailability(ctx: ExtensionContext): Promise<ProviderA
378
380
  ninerouter: allowedProviders.has("ninerouter") && isNineRouterAvailable(),
379
381
  cloudflare: allowedProviders.has("cloudflare") && isCloudflareSearchAvailable(),
380
382
  searchapi: allowedProviders.has("searchapi") && isSearchApiAvailable(),
383
+ outcrawl: allowedProviders.has("outcrawl") && isOutcrawlAvailable(),
384
+ sofya: allowedProviders.has("sofya") && isSofyaAvailable(),
381
385
  deepseek: allowedProviders.has("deepseek") && isDeepSeekAvailable(),
382
386
  };
383
387
  return {
@@ -1449,7 +1453,7 @@ export default function (pi: ExtensionAPI) {
1449
1453
  description: "Default none; summary-review opens the curator; auto-summary summarizes",
1450
1454
  }),
1451
1455
  ),
1452
- proxy: Type.Optional(Type.String({ description: "http(s) or socks proxy URL (env proxy vars ignored); \"\" forces direct" })),
1456
+ proxy: Type.Optional(Type.String({ description: "Proxy URL; omit by default (env proxy vars ignored); \"\" forces direct" })),
1453
1457
  }),
1454
1458
  outputSchema: webSearchOutputSchema,
1455
1459
  exposure: toolExposure,
@@ -1994,7 +1998,7 @@ export default function (pi: ExtensionAPI) {
1994
1998
  recencyFilter: Type.Optional(StringEnum(["day", "week", "month", "year"])),
1995
1999
  domainFilter: Type.Optional(Type.Array(Type.String(), { description: "Prefix - to exclude" })),
1996
2000
  provider: Type.Optional(Type.String({ description: providerDescription })),
1997
- proxy: Type.Optional(Type.String({ description: "http(s) or socks proxy URL; \"\" forces direct" })),
2001
+ proxy: Type.Optional(Type.String({ description: "Proxy URL; omit by default; \"\" forces direct" })),
1998
2002
  }),
1999
2003
  exposure: toolExposure,
2000
2004
  async execute(_callId, params, signal, _onUpdate, ctx) {
@@ -2042,7 +2046,7 @@ export default function (pi: ExtensionAPI) {
2042
2046
  auth: Type.Optional(Type.Union([Type.String(), Type.Boolean()], {
2043
2047
  description: "authFetch profile name, or true for the only one",
2044
2048
  })),
2045
- proxy: Type.Optional(Type.String({ description: "http(s) or socks proxy URL; \"\" forces direct" })),
2049
+ proxy: Type.Optional(Type.String({ description: "Proxy URL; omit by default; \"\" forces direct" })),
2046
2050
  redirects: Type.Optional(StringEnum(["same-origin"], {
2047
2051
  description: "Refuse cross-origin redirects",
2048
2052
  })),
@@ -34,7 +34,7 @@ function providerProblem(value: unknown): string | undefined {
34
34
  const recencySchema = stringEnum(["day", "week", "month", "year"]);
35
35
  const domainFilterSchema = Type.Array(Type.String(), { description: "Prefix - to exclude" });
36
36
  const numResultsSchema = Type.Integer({ minimum: 1, maximum: 20, description: "Default 5" });
37
- const proxySchema = Type.String({ description: "http(s) or socks proxy URL; \"\" forces direct" });
37
+ const proxySchema = Type.String({ description: "Proxy URL; omit by default; \"\" forces direct" });
38
38
  // Page fetches write a page cache and clone GitHub URLs into a temp directory,
39
39
  // including the fetches behind includeContent and fetchContent.
40
40
  const fetchingAnnotations = { readOnlyHint: false, destructiveHint: false, openWorldHint: true };
@@ -0,0 +1,204 @@
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 } from "./perplexity.ts";
5
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
6
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
7
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
8
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveProviderApiUrl } from "./utils.ts";
9
+
10
+ // Outcrawl Search API: https://outcrawl.ai/docs
11
+ const OUTCRAWL_SEARCH_URL = "https://api.outcrawl.ai/v1/search";
12
+ const CONFIG_PATH = getWebSearchConfigPath();
13
+ const SEARCH_TIMEOUT_MS = 60_000;
14
+ const MAX_REQUEST_RESULTS = 20;
15
+
16
+ interface WebSearchConfig {
17
+ outcrawlBaseUrl?: unknown;
18
+ outcrawlApiKey?: unknown;
19
+ }
20
+
21
+ interface OutcrawlHit {
22
+ url?: unknown;
23
+ title?: unknown;
24
+ snippet?: unknown;
25
+ }
26
+
27
+ let cachedConfig: WebSearchConfig | null = null;
28
+
29
+ function loadConfig(): WebSearchConfig {
30
+ if (cachedConfig) return cachedConfig;
31
+ if (!existsSync(CONFIG_PATH)) {
32
+ cachedConfig = {};
33
+ return cachedConfig;
34
+ }
35
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
36
+ let parsed: unknown;
37
+ try {
38
+ parsed = JSON.parse(raw);
39
+ } catch (err) {
40
+ const message = err instanceof Error ? err.message : String(err);
41
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
42
+ }
43
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
44
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
45
+ }
46
+ cachedConfig = parsed as WebSearchConfig;
47
+ return cachedConfig;
48
+ }
49
+
50
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
51
+ return resolveCredential({
52
+ provider: "Outcrawl",
53
+ configuredValue: loadConfig().outcrawlApiKey,
54
+ environmentValue: process.env.OUTCRAWL_API_KEY,
55
+ signal,
56
+ });
57
+ }
58
+
59
+ async function requireApiKey(signal?: AbortSignal): Promise<string> {
60
+ const apiKey = await getApiKey(signal);
61
+ if (!apiKey) {
62
+ throw new Error(
63
+ "Outcrawl API key not found. Either:\n" +
64
+ ` 1. Create ${CONFIG_PATH} with { "outcrawlApiKey": "your-key" }\n` +
65
+ " 2. Set OUTCRAWL_API_KEY environment variable\n" +
66
+ "Get a key at https://outcrawl.ai",
67
+ );
68
+ }
69
+ return apiKey;
70
+ }
71
+
72
+ interface DomainFilters {
73
+ include: string[];
74
+ exclude: string[];
75
+ }
76
+
77
+ function parseDomainFilter(domainFilter: string[] | undefined): DomainFilters {
78
+ const filters: DomainFilters = { include: [], exclude: [] };
79
+ for (const raw of domainFilter ?? []) {
80
+ const domain = normalizeDomain(raw);
81
+ if (!domain) continue;
82
+ const target = raw.trim().startsWith("-") ? filters.exclude : filters.include;
83
+ if (!target.includes(domain)) target.push(domain);
84
+ }
85
+ return filters;
86
+ }
87
+
88
+ function passesDomainFilters(url: URL, filters: DomainFilters): boolean {
89
+ if (filters.include.length === 0 && filters.exclude.length === 0) return true;
90
+ const hostname = url.hostname.toLowerCase();
91
+ const matches = (domain: string) => hostname === domain || hostname.endsWith(`.${domain}`);
92
+ if (filters.exclude.some(matches)) return false;
93
+ return filters.include.length === 0 || filters.include.some(matches);
94
+ }
95
+
96
+ function buildQuery(query: string, filters: DomainFilters): string {
97
+ const parts = [query];
98
+ if (filters.include.length === 1) parts.push(`site:${filters.include[0]}`);
99
+ if (filters.include.length > 1) parts.push(`(${filters.include.map(domain => `site:${domain}`).join(" OR ")})`);
100
+ for (const domain of filters.exclude) parts.push(`-site:${domain}`);
101
+ return parts.join(" ");
102
+ }
103
+
104
+ function errorMessage(err: unknown): string {
105
+ return err instanceof Error ? err.message : String(err);
106
+ }
107
+
108
+ function invalidResponse(message: string): Error {
109
+ return new Error(`Outcrawl returned invalid response: ${message}`);
110
+ }
111
+
112
+ function parseResponse(value: unknown): OutcrawlHit[] {
113
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalidResponse("expected an object envelope");
114
+ const envelope = value as Record<string, unknown>;
115
+ if (typeof envelope.error === "string" && envelope.error.trim()) throw invalidResponse(envelope.error.trim());
116
+ if (!Array.isArray(envelope.hits)) throw invalidResponse("expected hits array");
117
+ return envelope.hits as OutcrawlHit[];
118
+ }
119
+
120
+ export function isOutcrawlAvailable(): boolean {
121
+ return hasCredentialSource({ provider: "Outcrawl", configuredValue: loadConfig().outcrawlApiKey, environmentValue: process.env.OUTCRAWL_API_KEY });
122
+ }
123
+
124
+ // Outcrawl search has no date filter, so `recencyFilter` is not applied.
125
+ export async function searchWithOutcrawl(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
126
+ const apiKey = await requireApiKey(options.signal);
127
+ const numResults = normalizeSearchResultCount(options.numResults);
128
+ const filters = parseDomainFilter(options.domainFilter);
129
+ // Results are reapplied to the domain filters locally, so leave a little headroom.
130
+ const hasDomainClauses = filters.include.length > 0 || filters.exclude.length > 0;
131
+ const body = {
132
+ query: buildQuery(query, filters),
133
+ limit: hasDomainClauses ? Math.min(MAX_REQUEST_RESULTS, numResults + 5) : numResults,
134
+ };
135
+ const activityId = activityMonitor.logStart({ type: "api", query });
136
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
137
+ let response: Response;
138
+ let entries: OutcrawlHit[];
139
+ try {
140
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("outcrawl", OUTCRAWL_SEARCH_URL, loadConfig().outcrawlBaseUrl), {
141
+ method: "POST",
142
+ headers: {
143
+ Accept: "application/json",
144
+ Authorization: `Bearer ${apiKey}`,
145
+ "Content-Type": "application/json",
146
+ "User-Agent": "pi-web-access",
147
+ },
148
+ body: JSON.stringify(body),
149
+ signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal,
150
+ }, ["Authorization"]);
151
+ if (!response.ok) {
152
+ const errorText = await response.text();
153
+ throw new Error(`Outcrawl error ${response.status}: ${redactCredential(errorText, apiKey).slice(0, 300)}`);
154
+ }
155
+ let rawData: unknown;
156
+ try {
157
+ rawData = await response.json();
158
+ } catch (err) {
159
+ // Only a parse failure is invalid JSON; a dropped connection or timeout keeps its own classification.
160
+ if (!(err instanceof SyntaxError)) throw err;
161
+ throw new Error(`Outcrawl returned invalid JSON: ${errorMessage(err)}`);
162
+ }
163
+ entries = parseResponse(rawData);
164
+ } catch (err) {
165
+ if (options.signal?.aborted) {
166
+ activityMonitor.logComplete(activityId, 0);
167
+ throw new Error("Aborted");
168
+ }
169
+ const message = errorMessage(err);
170
+ const providerTimeout = timeoutSignal.aborted || (err instanceof Error && err.name === "TimeoutError");
171
+ const outgoing = providerTimeout
172
+ ? new Error(`Outcrawl request timed out after ${Math.round(SEARCH_TIMEOUT_MS / 1000)}s`)
173
+ : (() => {
174
+ const redactedMessage = redactCredential(message, apiKey);
175
+ if (redactedMessage === message && err instanceof Error) return err;
176
+ const redactedError = new Error(redactedMessage);
177
+ if (err instanceof Error) redactedError.name = err.name;
178
+ return redactedError;
179
+ })();
180
+ activityMonitor.logError(activityId, redactCredential(errorMessage(outgoing), apiKey));
181
+ throw outgoing;
182
+ }
183
+ activityMonitor.logComplete(activityId, response.status);
184
+ const results: SearchResponse["results"] = [];
185
+ for (const entry of entries) {
186
+ if (!entry || typeof entry !== "object") continue;
187
+ if (typeof entry.url !== "string" || !entry.url) continue;
188
+ let resultUrl: URL;
189
+ try {
190
+ resultUrl = new URL(entry.url);
191
+ } catch {
192
+ continue;
193
+ }
194
+ if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
195
+ if (!passesDomainFilters(resultUrl, filters)) continue;
196
+ results.push({
197
+ title: typeof entry.title === "string" && entry.title.trim() ? entry.title.trim() : `Source ${results.length + 1}`,
198
+ url: resultUrl.href,
199
+ snippet: typeof entry.snippet === "string" ? entry.snippet : "",
200
+ });
201
+ if (results.length >= numResults) break;
202
+ }
203
+ return { answer: formatSearchResultsAsAnswer(results), results };
204
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-web-access",
3
- "version": "0.46.0",
4
- "description": "Web search, URL fetching, GitHub repo cloning, PDF extraction, YouTube video understanding, and local video analysis for Pi coding agent. Supports OpenAI, Brave, Parallel, TinyFish, Search1API, Searchinfinity, Querit, Tavily, Firecrawl, Crawl4AI, Jina, SERPdive, Kagi, Ollama, AnySearch, Bright Data SERP, SerpBase, SerpApi, Serply, SearchApi, You.com, SearXNG, degoog, Exa, Perplexity, Gemini, Kimi, Mistral, and Tabstack.",
3
+ "version": "0.47.0",
4
+ "description": "Web search, URL fetching, GitHub repo cloning, PDF extraction, YouTube video understanding, and local video analysis for Pi coding agent. Supports OpenAI, Brave, Parallel, TinyFish, Search1API, Searchinfinity, Querit, Tavily, Firecrawl, Crawl4AI, Jina, SERPdive, Kagi, Ollama, AnySearch, Bright Data SERP, SerpBase, SerpApi, Serply, SearchApi, Outcrawl, Sofya, You.com, SearXNG, degoog, Exa, Perplexity, Gemini, Kimi, Mistral, and Tabstack.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "pi-web-access-mcp": "dist/mcp-cli.js"
@@ -0,0 +1,201 @@
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 } from "./perplexity.ts";
5
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
6
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
7
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
8
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveProviderApiUrl } from "./utils.ts";
9
+
10
+ // Sofya Search API: https://sofya.co/docs
11
+ const SOFYA_SEARCH_URL = "https://sofya.co/v1/search";
12
+ const CONFIG_PATH = getWebSearchConfigPath();
13
+ const SEARCH_TIMEOUT_MS = 60_000;
14
+ const MAX_REQUEST_RESULTS = 20;
15
+ const MAX_DOMAIN_FILTERS = 10;
16
+
17
+ interface WebSearchConfig {
18
+ sofyaBaseUrl?: unknown;
19
+ sofyaApiKey?: unknown;
20
+ }
21
+
22
+ interface SofyaHit {
23
+ url?: unknown;
24
+ title?: unknown;
25
+ content?: unknown;
26
+ description?: unknown;
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
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
38
+ let parsed: unknown;
39
+ try {
40
+ parsed = JSON.parse(raw);
41
+ } catch (err) {
42
+ const message = err instanceof Error ? err.message : String(err);
43
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
44
+ }
45
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
46
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
47
+ }
48
+ cachedConfig = parsed as WebSearchConfig;
49
+ return cachedConfig;
50
+ }
51
+
52
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
53
+ return resolveCredential({
54
+ provider: "Sofya",
55
+ configuredValue: loadConfig().sofyaApiKey,
56
+ environmentValue: process.env.SOFYA_API_KEY,
57
+ signal,
58
+ });
59
+ }
60
+
61
+ async function requireApiKey(signal?: AbortSignal): Promise<string> {
62
+ const apiKey = await getApiKey(signal);
63
+ if (!apiKey) {
64
+ throw new Error(
65
+ "Sofya API key not found. Either:\n" +
66
+ ` 1. Create ${CONFIG_PATH} with { "sofyaApiKey": "your-key" }\n` +
67
+ " 2. Set SOFYA_API_KEY environment variable\n" +
68
+ "Get a key at https://sofya.co/dashboard",
69
+ );
70
+ }
71
+ return apiKey;
72
+ }
73
+
74
+ interface DomainFilters {
75
+ include: string[];
76
+ exclude: string[];
77
+ }
78
+
79
+ function parseDomainFilter(domainFilter: string[] | undefined): DomainFilters {
80
+ const filters: DomainFilters = { include: [], exclude: [] };
81
+ for (const raw of domainFilter ?? []) {
82
+ const domain = normalizeDomain(raw);
83
+ if (!domain) continue;
84
+ const target = raw.trim().startsWith("-") ? filters.exclude : filters.include;
85
+ if (!target.includes(domain)) target.push(domain);
86
+ }
87
+ return filters;
88
+ }
89
+
90
+ function passesDomainFilters(url: URL, filters: DomainFilters): boolean {
91
+ if (filters.include.length === 0 && filters.exclude.length === 0) return true;
92
+ const hostname = url.hostname.toLowerCase();
93
+ const matches = (domain: string) => hostname === domain || hostname.endsWith(`.${domain}`);
94
+ if (filters.exclude.some(matches)) return false;
95
+ return filters.include.length === 0 || filters.include.some(matches);
96
+ }
97
+
98
+ function errorMessage(err: unknown): string {
99
+ return err instanceof Error ? err.message : String(err);
100
+ }
101
+
102
+ function invalidResponse(message: string): Error {
103
+ return new Error(`Sofya returned invalid response: ${message}`);
104
+ }
105
+
106
+ function parseResponse(value: unknown): SofyaHit[] {
107
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalidResponse("expected an object envelope");
108
+ const envelope = value as Record<string, unknown>;
109
+ if (typeof envelope.detail === "string" && envelope.detail.trim()) throw invalidResponse(envelope.detail.trim());
110
+ if (!Array.isArray(envelope.results)) throw invalidResponse("expected results array");
111
+ return envelope.results as SofyaHit[];
112
+ }
113
+
114
+ export function isSofyaAvailable(): boolean {
115
+ return hasCredentialSource({ provider: "Sofya", configuredValue: loadConfig().sofyaApiKey, environmentValue: process.env.SOFYA_API_KEY });
116
+ }
117
+
118
+ // Domain filters and recency go to Sofya's own include_domains, exclude_domains and freshness.
119
+ // "snippets" depth returns title, URL and snippet (1 credit); pages are read with the fetch tool.
120
+ export async function searchWithSofya(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
121
+ const apiKey = await requireApiKey(options.signal);
122
+ const numResults = normalizeSearchResultCount(options.numResults);
123
+ const filters = parseDomainFilter(options.domainFilter);
124
+ const body: Record<string, unknown> = {
125
+ query,
126
+ search_depth: "snippets",
127
+ max_results: Math.min(MAX_REQUEST_RESULTS, numResults),
128
+ };
129
+ if (filters.include.length > 0) body.include_domains = filters.include.slice(0, MAX_DOMAIN_FILTERS);
130
+ if (filters.exclude.length > 0) body.exclude_domains = filters.exclude.slice(0, MAX_DOMAIN_FILTERS);
131
+ if (options.recencyFilter) body.freshness = options.recencyFilter;
132
+ const activityId = activityMonitor.logStart({ type: "api", query });
133
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
134
+ let response: Response;
135
+ let entries: SofyaHit[];
136
+ try {
137
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("sofya", SOFYA_SEARCH_URL, loadConfig().sofyaBaseUrl), {
138
+ method: "POST",
139
+ headers: {
140
+ Accept: "application/json",
141
+ Authorization: `Bearer ${apiKey}`,
142
+ "Content-Type": "application/json",
143
+ "User-Agent": "pi-web-access",
144
+ },
145
+ body: JSON.stringify(body),
146
+ signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal,
147
+ }, ["Authorization"]);
148
+ if (!response.ok) {
149
+ const errorText = await response.text();
150
+ throw new Error(`Sofya error ${response.status}: ${redactCredential(errorText, apiKey).slice(0, 300)}`);
151
+ }
152
+ let rawData: unknown;
153
+ try {
154
+ rawData = await response.json();
155
+ } catch (err) {
156
+ // Only a parse failure is invalid JSON; a dropped connection or timeout keeps its own classification.
157
+ if (!(err instanceof SyntaxError)) throw err;
158
+ throw new Error(`Sofya returned invalid JSON: ${errorMessage(err)}`);
159
+ }
160
+ entries = parseResponse(rawData);
161
+ } catch (err) {
162
+ if (options.signal?.aborted) {
163
+ activityMonitor.logComplete(activityId, 0);
164
+ throw new Error("Aborted");
165
+ }
166
+ const message = errorMessage(err);
167
+ const providerTimeout = timeoutSignal.aborted || (err instanceof Error && err.name === "TimeoutError");
168
+ const outgoing = providerTimeout
169
+ ? new Error(`Sofya request timed out after ${Math.round(SEARCH_TIMEOUT_MS / 1000)}s`)
170
+ : (() => {
171
+ const redactedMessage = redactCredential(message, apiKey);
172
+ if (redactedMessage === message && err instanceof Error) return err;
173
+ const redactedError = new Error(redactedMessage);
174
+ if (err instanceof Error) redactedError.name = err.name;
175
+ return redactedError;
176
+ })();
177
+ activityMonitor.logError(activityId, redactCredential(errorMessage(outgoing), apiKey));
178
+ throw outgoing;
179
+ }
180
+ activityMonitor.logComplete(activityId, response.status);
181
+ const results: SearchResponse["results"] = [];
182
+ for (const entry of entries) {
183
+ if (!entry || typeof entry !== "object") continue;
184
+ if (typeof entry.url !== "string" || !entry.url) continue;
185
+ let resultUrl: URL;
186
+ try {
187
+ resultUrl = new URL(entry.url);
188
+ } catch {
189
+ continue;
190
+ }
191
+ if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
192
+ if (!passesDomainFilters(resultUrl, filters)) continue;
193
+ results.push({
194
+ title: typeof entry.title === "string" && entry.title.trim() ? entry.title.trim() : `Source ${results.length + 1}`,
195
+ url: resultUrl.href,
196
+ snippet: typeof entry.content === "string" && entry.content ? entry.content : typeof entry.description === "string" ? entry.description : "",
197
+ });
198
+ if (results.length >= numResults) break;
199
+ }
200
+ return { answer: formatSearchResultsAsAnswer(results), results };
201
+ }
@@ -302,8 +302,8 @@ function redactProxyUrl(value: string): string {
302
302
  return parsed.toString();
303
303
  }
304
304
 
305
- export function loadConfiguredProxy(): string | null {
306
- let configured: unknown;
305
+ function loadProxyConfig(): { proxy: string | null; locked: boolean } {
306
+ let config: { proxy?: unknown; lockProxy?: unknown } = {};
307
307
  const path = getWebSearchConfigPath();
308
308
  if (existsSync(path)) {
309
309
  let raw: unknown;
@@ -313,20 +313,30 @@ export function loadConfiguredProxy(): string | null {
313
313
  const message = err instanceof Error ? err.message : String(err);
314
314
  throw new Error(`Failed to load proxy config from ${path}: ${message}`);
315
315
  }
316
- if (raw && typeof raw === "object" && !Array.isArray(raw)) configured = (raw as { proxy?: unknown }).proxy;
316
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) config = raw as typeof config;
317
317
  }
318
- if (configured === undefined) return null;
319
- return normalizeProxyUrl(configured, `proxy in ${getWebSearchConfigPath()}`);
318
+ if (config.lockProxy !== undefined && typeof config.lockProxy !== "boolean") throw new Error(`lockProxy in ${path} must be true or false`);
319
+ const locked = config.lockProxy === true;
320
+ const proxy = config.proxy === undefined ? null : normalizeProxyUrl(config.proxy, `proxy in ${path}`);
321
+ if (locked && proxy === null) throw new Error(`lockProxy is set in ${path} but no proxy is configured there; set proxy or remove lockProxy`);
322
+ return { proxy, locked };
323
+ }
324
+
325
+ export function loadConfiguredProxy(): string | null {
326
+ return loadProxyConfig().proxy;
320
327
  }
321
328
 
322
329
  export function runWithProxy<T>(proxy: string | undefined, fn: () => T): T {
330
+ const { proxy: configured, locked } = loadProxyConfig();
323
331
  if (proxy === undefined) {
324
- const configured = loadConfiguredProxy();
325
332
  if (configured === null) return fn();
326
333
  installGlobalProxyFetch();
327
334
  return proxyStorage.run(configured, fn);
328
335
  }
329
336
  const normalized = normalizeProxyUrl(proxy, "proxy");
337
+ if (locked && normalized !== configured) {
338
+ throw new Error(`proxy argument rejected: lockProxy is set in ${getWebSearchConfigPath()}; omit proxy to use the configured proxy`);
339
+ }
330
340
  if (normalized !== null) installGlobalProxyFetch();
331
341
  return proxyStorage.run(normalized, fn);
332
342
  }
@@ -77,6 +77,10 @@ export interface WebSearchConfig {
77
77
  cloudflareSearchProvider?: unknown;
78
78
  searchapiApiKey?: unknown;
79
79
  searchapiBaseUrl?: unknown;
80
+ outcrawlApiKey?: unknown;
81
+ outcrawlBaseUrl?: unknown;
82
+ sofyaApiKey?: unknown;
83
+ sofyaBaseUrl?: unknown;
80
84
  tabstackBaseUrl?: unknown;
81
85
  tabstackApiKey?: unknown;
82
86
  tabstackResearchMode?: unknown;