@herbertgao/pi-extensions 2026.10.14 → 2026.10.15

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 (41) hide show
  1. package/README.md +8 -6
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/node_modules/@narumitw/pi-btw/README.md +1 -1
  4. package/node_modules/@narumitw/pi-btw/dist/index.ts +77 -64
  5. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +2 -2
  6. package/node_modules/@narumitw/pi-btw/docs/core-alignment.md +10 -2
  7. package/node_modules/@narumitw/pi-btw/package.json +5 -5
  8. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +83 -63
  9. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  10. package/node_modules/pi-web-access/CHANGELOG.md +40 -0
  11. package/node_modules/pi-web-access/README.md +96 -22
  12. package/node_modules/pi-web-access/brave-rate-limit.ts +2 -2
  13. package/node_modules/pi-web-access/curator-page.ts +3 -1
  14. package/node_modules/pi-web-access/curator-server.ts +1 -0
  15. package/node_modules/pi-web-access/dist/index.js +2607 -1674
  16. package/node_modules/pi-web-access/dist/mcp-cli.js +1119 -327
  17. package/node_modules/pi-web-access/duckduckgo-rate-limit.ts +95 -0
  18. package/node_modules/pi-web-access/duckduckgo.ts +51 -45
  19. package/node_modules/pi-web-access/exa.ts +48 -6
  20. package/node_modules/pi-web-access/extract.ts +2 -2
  21. package/node_modules/pi-web-access/fetch-params.ts +5 -4
  22. package/node_modules/pi-web-access/field-extract.ts +347 -0
  23. package/node_modules/pi-web-access/gemini-search.ts +151 -13
  24. package/node_modules/pi-web-access/index.ts +128 -125
  25. package/node_modules/pi-web-access/mistral-search.ts +1 -1
  26. package/node_modules/pi-web-access/ninerouter.ts +92 -0
  27. package/node_modules/pi-web-access/offtopic-judge.ts +72 -0
  28. package/node_modules/pi-web-access/openai-search.ts +36 -10
  29. package/node_modules/pi-web-access/package.json +1 -1
  30. package/node_modules/pi-web-access/perplexity.ts +1 -0
  31. package/node_modules/pi-web-access/query-rewrite.ts +39 -13
  32. package/node_modules/pi-web-access/source-check.ts +31 -15
  33. package/node_modules/pi-web-access/summary-model-scope.ts +19 -1
  34. package/node_modules/pi-web-access/summary-review.ts +13 -20
  35. package/node_modules/pi-web-access/tool-arguments.ts +1 -1
  36. package/node_modules/pi-web-access/upgrade-notice.ts +47 -0
  37. package/node_modules/pi-web-access/utils.ts +26 -1
  38. package/node_modules/pi-web-access/web-tool-contract.ts +4 -1
  39. package/node_modules/pi-web-access/web-tool-core.ts +99 -19
  40. package/node_modules/pi-web-access/xai-search.ts +3 -3
  41. package/package.json +6 -6
@@ -1,12 +1,12 @@
1
1
  import type { AgentToolResult, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { Box, Text, truncateToWidth, type KeyId } from "@earendil-works/pi-tui";
3
- import { Type } from "typebox";
3
+ import { Type, type TOptional, type TString } from "typebox";
4
4
  import type { ExtractedContent } from "./extract.ts";
5
5
  import { normalizeFetchContentParams } from "./fetch-params.ts";
6
6
  import { answerFromPage } from "./page-query.ts";
7
7
  import { rewriteSearchQuery } from "./query-rewrite.ts";
8
8
  import { clearCloneCache, releaseClonesUnusedSince, touchClones } from "./github-extract.ts";
9
- import { ALL_SEARCH_PROVIDERS, getAllowedSearchProviders, getConfiguredSearchRouting, providerLabel, RESOLVED_SEARCH_PROVIDERS, search, type AttributedSearchResponse, type ProviderAvailability, type SearchProvider, type SearchProviderSelection, type ResolvedSearchProvider } from "./gemini-search.ts";
9
+ import { ALL_SEARCH_PROVIDERS, getAllowedSearchProviders, getConfiguredSearchRouting, parseProviderArgument, RESOLVED_SEARCH_PROVIDERS, search, type AttributedSearchResponse, type ProviderAvailability, type SearchProvider, type SearchProviderSelection, type ResolvedSearchProvider } from "./gemini-search.ts";
10
10
  export type { ProviderAvailability } from "./gemini-search.ts";
11
11
  import { formatSeconds, getWebSearchConfigDir, resolveCuratorNetworkConfig, runWithProxy } from "./utils.ts";
12
12
  import {
@@ -72,15 +72,17 @@ import { isSerplyAvailable } from "./serply.ts";
72
72
  import { isKeenableAvailable } from "./keenable.ts";
73
73
  import { isCeramicAvailable } from "./ceramic.ts";
74
74
  import { isLinkupAvailable } from "./linkup.ts";
75
+ import { isNineRouterAvailable } from "./ninerouter.ts";
75
76
  import { isDeepSeekAvailable } from "./deepseek.ts";
76
77
  import { isBaizhiAvailable } from "./baizhi.ts";
77
78
  import { isZaiAvailable } from "./zai.ts";
78
79
  import { isValyuAvailable } from "./valyu.ts";
79
80
  import { isXcrawlAvailable } from "./xcrawl.ts";
80
81
  import { buildSearchErrorPlan, type SearchErrorDetails, type SearchErrorPlan } from "./render-search-error.ts";
81
- import { findModelWithProviderRouting, isModelInScope, splitThinkingSuffix } from "./summary-model-scope.ts";
82
+ import { findModelWithProviderRouting, isModelInScope, resolveHelperModelSelector } from "./summary-model-scope.ts";
82
83
  import { registerCuratorRunLifecycle, resolveWebSearchWorkflow, type WebSearchWorkflow } from "./curator-run.ts";
83
84
  import { registerWebToolActivation } from "./tool-activation.ts";
85
+ import { showUpgradeNotice } from "./upgrade-notice.ts";
84
86
  import {
85
87
  createWebToolCore,
86
88
  DEFAULT_TOOL_NAMES,
@@ -150,6 +152,20 @@ const fetchContentOutputSchema = Type.Object({
150
152
  mimeType: Type.Optional(Type.String()),
151
153
  status: Type.Optional(Type.Number()),
152
154
  duration: Type.Optional(Type.Number()),
155
+ extraction: Type.Optional(Type.Union([
156
+ Type.Object({
157
+ fields: Type.Record(Type.String(), Type.Object({
158
+ status: Type.Union([Type.Literal("extracted"), Type.Literal("uncertain"), Type.Literal("null")], { description: "null means not on the page" }),
159
+ value: Type.Optional(Type.Unknown({ description: "Typed value when extracted" })),
160
+ guess: Type.Optional(Type.Unknown({ description: "Unconfirmed value when uncertain" })),
161
+ confidence: Type.Optional(Type.Number()),
162
+ line: Type.Optional(Type.String({ description: "Page line the text or number value was found on" })),
163
+ notFound: Type.Optional(Type.Boolean({ description: "Uncertain because the text is not on the page" })),
164
+ })),
165
+ cut: Type.Boolean({ description: "Only the first part of the page was read" }),
166
+ }),
167
+ Type.Object({ error: Type.String({ description: "Why extraction failed for this fetched page" }) }),
168
+ ], { description: "Extract mode only, for each fetched URL" })),
153
169
  })),
154
170
  });
155
171
 
@@ -202,6 +218,7 @@ const FETCH_MODE_DESCRIPTIONS: Record<FetchMode, string> = {
202
218
  readable: "extract readable content as markdown",
203
219
  raw: "return the exact textual body using direct HTTP only",
204
220
  answer: "answer a prompt using only fetched content",
221
+ extract: "read typed values named in fields",
205
222
  };
206
223
 
207
224
  // Keep primary query indexes stable for curator slots, then interleave additional
@@ -214,13 +231,6 @@ function curatorResultIndexCapacity(queryCount: number): number {
214
231
  return queryCount * RESOLVED_SEARCH_PROVIDERS.length;
215
232
  }
216
233
 
217
- function searchProviderSchema(description: string, allowedProviders: readonly ResolvedSearchProvider[]) {
218
- return Type.Union([
219
- StringEnum(["auto", "all", ...allowedProviders]),
220
- Type.Array(StringEnum([...allowedProviders]), { minItems: 1 }),
221
- ], { description });
222
- }
223
-
224
234
  function isCommandEnabled(config: WebSearchConfig, name: "websearch" | "curator" | "search" | "google-account"): boolean {
225
235
  return config.commands?.[name]?.enabled !== false;
226
236
  }
@@ -299,6 +309,19 @@ export function getSummaryInstructions(): string | undefined {
299
309
  return trimmed.length > 0 ? trimmed : undefined;
300
310
  }
301
311
 
312
+ function readHelperModelKey(key: "summaryModel" | "queryRewriteModel"): string | undefined {
313
+ const value: unknown = loadConfig()[key];
314
+ if (value === undefined) return undefined;
315
+ const message = `${key} in ${WEB_SEARCH_CONFIG_PATH} must be "current", "current:<level>", or "provider/model-id[:<level>]"`;
316
+ if (typeof value !== "string") throw new Error(message);
317
+ try {
318
+ resolveHelperModelSelector(value, key);
319
+ } catch {
320
+ throw new Error(message);
321
+ }
322
+ return value.trim();
323
+ }
324
+
302
325
  function shouldAutoOpenCuratorBrowser(config: WebSearchConfig): boolean {
303
326
  if (config.autoOpenBrowser === false) return false;
304
327
  if (resolveCuratorNetworkConfig().enabled && config.autoOpenBrowser !== true) return false;
@@ -348,6 +371,7 @@ async function getProviderAvailability(ctx: ExtensionContext): Promise<ProviderA
348
371
  keenable: allowedProviders.has("keenable") && isKeenableAvailable(),
349
372
  ceramic: allowedProviders.has("ceramic") && isCeramicAvailable(),
350
373
  linkup: allowedProviders.has("linkup") && isLinkupAvailable(),
374
+ ninerouter: allowedProviders.has("ninerouter") && isNineRouterAvailable(),
351
375
  deepseek: allowedProviders.has("deepseek") && isDeepSeekAvailable(),
352
376
  };
353
377
  return {
@@ -742,13 +766,9 @@ export default function (pi: ExtensionAPI) {
742
766
  throw new Error(`toolActivation "none" in ${WEB_SEARCH_CONFIG_PATH} requires toolExposure "deferred"`);
743
767
  }
744
768
  const allowedSearchProviders = initConfig.webSearch?.allowedProviders === undefined ? RESOLVED_SEARCH_PROVIDERS : getAllowedSearchProviders();
745
- const allEligibleProviders = allowedSearchProviders.filter(provider => ALL_SEARCH_PROVIDERS.includes(provider));
746
- const allExcludedProviders = allowedSearchProviders.filter(provider => !ALL_SEARCH_PROVIDERS.includes(provider));
747
- const allPolicyDescription = allEligibleProviders.length === 0
748
- ? `all has no eligible allowed providers; explicit-only allowed providers (${allExcludedProviders.map(providerLabel).join(", ")}) remain excluded`
749
- : allExcludedProviders.length > 0
750
- ? `all searches eligible allowed providers (${allEligibleProviders.map(providerLabel).join(", ")}); explicit-only allowed providers (${allExcludedProviders.map(providerLabel).join(", ")}) remain excluded`
751
- : `all searches every eligible allowed provider (${allEligibleProviders.map(providerLabel).join(", ")})`;
769
+ const modelProviders = allowedSearchProviders.filter(provider => provider === "openai" || provider === "xai" || provider === "mistral" || provider === "gemini");
770
+ // Depends on config only, never on credentials, so definitions stay byte-stable across environments.
771
+ const providerDescription = `auto, all, a name, or comma-separated names; omit for the configured default.${initConfig.webSearch?.allowedProviders === undefined ? "" : ` Allowed: ${allowedSearchProviders.join(", ")}.`}`;
752
772
  const curatorRunState = registerCuratorRunLifecycle(pi);
753
773
  const toolNames = resolveToolNames(initConfig);
754
774
  const webSearchEnabled = isToolEnabled(initConfig, "webSearch");
@@ -770,12 +790,9 @@ export default function (pi: ExtensionAPI) {
770
790
  // at tools that are disabled or were renamed after init.
771
791
  const registeredToolNames = registeredFetchToolNames(coreSettings);
772
792
  const storedContentSources = storedContentSourceNames(coreSettings);
773
- const searchQueryDescription = webSearchEnabled
774
- ? `Get content for this query (${toolNames.webSearch})`
775
- : "Get content for a stored search query";
776
793
  const fetchContentStorageNote = getSearchContentEnabled
777
- ? `Full original content is stored for retrieval with ${toolNames.getSearchContent}.`
778
- : "Full original content is stored internally, but the retrieval tool is not registered.";
794
+ ? `Full content is stored for retrieval with ${toolNames.getSearchContent}.`
795
+ : "Full content is stored, but the retrieval tool is not registered.";
779
796
  const fetchModeDescription = fetchModeConfig.allowedModes
780
797
  .map(mode => `${mode}${mode === fetchModeConfig.defaultMode ? " (default)" : ""}: ${FETCH_MODE_DESCRIPTIONS[mode]}`)
781
798
  .join("; ");
@@ -972,16 +989,18 @@ export default function (pi: ExtensionAPI) {
972
989
  if (selectedResults.length === 0) {
973
990
  throw new Error("No selected results available for summary generation");
974
991
  }
992
+ const configuredSummaryModel = readHelperModelKey("summaryModel");
975
993
  try {
976
994
  return await generateSummaryDraft(
977
995
  selectedResults,
978
996
  summaryContext,
979
997
  signal,
980
- modelOverride,
998
+ modelOverride?.trim() || configuredSummaryModel,
981
999
  feedback,
982
1000
  undefined,
983
1001
  getSummaryGenerationDeadlineMs(),
984
1002
  getSummaryInstructions(),
1003
+ { preferredFallback: configuredSummaryModel === undefined },
985
1004
  );
986
1005
  } catch (err) {
987
1006
  const isEmptyResponse = err instanceof Error && err.message.includes("Summary model returned empty response");
@@ -999,13 +1018,12 @@ export default function (pi: ExtensionAPI) {
999
1018
 
1000
1019
  async function loadSummaryModelChoices(
1001
1020
  summaryContext: SummaryGenerationContext,
1002
- ): Promise<{ summaryModels: Array<{ value: string; label: string }>; defaultSummaryModel: string | null }> {
1021
+ ): Promise<{ summaryModels: Array<{ value: string; label: string }>; defaultSummaryModel: string | null; preferredFallback: boolean }> {
1003
1022
  const summaryModels: Array<{ value: string; label: string }> = [];
1004
1023
  const seen = new Set<string>();
1005
1024
  const availableValues = new Set<string>();
1006
1025
 
1007
- const addModel = (provider: string, id: string) => {
1008
- const value = `${provider}/${id}`;
1026
+ const addModel = (value: string) => {
1009
1027
  if (seen.has(value)) return;
1010
1028
  seen.add(value);
1011
1029
  summaryModels.push({ value, label: value });
@@ -1014,18 +1032,14 @@ export default function (pi: ExtensionAPI) {
1014
1032
  for (const model of summaryContext.modelRegistry.getAvailable()) {
1015
1033
  if (!isModelInScope(model, summaryContext.scopedModels)) continue;
1016
1034
  availableValues.add(`${model.provider}/${model.id}`);
1017
- addModel(model.provider, model.id);
1035
+ addModel(`${model.provider}/${model.id}`);
1018
1036
  }
1019
1037
 
1020
- const currentModelValue = summaryContext.model
1021
- ? `${summaryContext.model.provider}/${summaryContext.model.id}`
1022
- : null;
1023
- if (summaryContext.model && currentModelValue && !seen.has(currentModelValue) && isModelInScope(summaryContext.model, summaryContext.scopedModels)) {
1024
- addModel(summaryContext.model.provider, summaryContext.model.id);
1038
+ if (summaryContext.model && isModelInScope(summaryContext.model, summaryContext.scopedModels)) {
1039
+ addModel(`${summaryContext.model.provider}/${summaryContext.model.id}`);
1025
1040
  }
1026
1041
 
1027
- const config = loadConfig();
1028
- const configuredSummaryModel = typeof config.summaryModel === "string" ? config.summaryModel.trim() : "";
1042
+ const configuredSummaryModel = readHelperModelKey("summaryModel");
1029
1043
  const preferredDefaults = [
1030
1044
  { provider: "anthropic", id: "claude-haiku-4-5" },
1031
1045
  { provider: "openai-codex", id: "gpt-5.6-luna" },
@@ -1035,32 +1049,15 @@ export default function (pi: ExtensionAPI) {
1035
1049
  { provider: "deepseek", id: "deepseek-v4-flash" },
1036
1050
  ];
1037
1051
 
1038
- const resolveAvailableModelValue = (selector: string): string | null => {
1039
- const parsed = splitThinkingSuffix(selector);
1040
- const slashIndex = parsed.value.indexOf("/");
1041
- if (slashIndex <= 0 || slashIndex >= parsed.value.length - 1) return null;
1042
- const model = findModelWithProviderRouting(
1043
- summaryContext.modelRegistry,
1044
- parsed.value.slice(0, slashIndex),
1045
- parsed.value.slice(slashIndex + 1),
1046
- );
1047
- if (!model) return null;
1048
- const value = `${model.provider}/${model.id}`;
1049
- if (!availableValues.has(value)) return null;
1050
- if (selector !== value && !seen.has(selector)) {
1051
- seen.add(selector);
1052
- summaryModels.push({ value: selector, label: selector });
1053
- }
1054
- return selector;
1055
- };
1056
-
1057
1052
  let defaultSummaryModel: string | null = null;
1058
- if (configuredSummaryModel.length > 0) {
1059
- defaultSummaryModel = availableValues.has(configuredSummaryModel)
1060
- ? configuredSummaryModel
1061
- : resolveAvailableModelValue(configuredSummaryModel);
1062
- }
1063
- if (!defaultSummaryModel) {
1053
+ if (configuredSummaryModel !== undefined) {
1054
+ const spec = resolveHelperModelSelector(configuredSummaryModel, "summary model", summaryContext.model);
1055
+ // With no concrete value to show, list nothing so the curator sends Auto (the configured selector).
1056
+ if (!spec) return { summaryModels: [], defaultSummaryModel: configuredSummaryModel, preferredFallback: false };
1057
+ // The curator groups choices by provider, so `current` must be concrete. Unavailable models stay listed so failures are visible.
1058
+ defaultSummaryModel = `${spec.provider}/${spec.id}${spec.thinkingLevel ? `:${spec.thinkingLevel}` : ""}`;
1059
+ addModel(defaultSummaryModel);
1060
+ } else {
1064
1061
  for (const preferred of preferredDefaults) {
1065
1062
  const model = findModelWithProviderRouting(summaryContext.modelRegistry, preferred.provider, preferred.id);
1066
1063
  const value = model ? `${model.provider}/${model.id}` : null;
@@ -1070,7 +1067,7 @@ export default function (pi: ExtensionAPI) {
1070
1067
  }
1071
1068
  }
1072
1069
  }
1073
- return { summaryModels, defaultSummaryModel };
1070
+ return { summaryModels, defaultSummaryModel, preferredFallback: configuredSummaryModel === undefined };
1074
1071
  }
1075
1072
 
1076
1073
  function resolveSummaryForSubmit(
@@ -1290,7 +1287,7 @@ export default function (pi: ExtensionAPI) {
1290
1287
  async onRewriteQuery(query, rewriteSignal) {
1291
1288
  return runWithProxy(pc.proxy, async () => {
1292
1289
  if (pendingCurates.get(callId) !== pc) throw new Error("Curator session is no longer active.");
1293
- return rewriteSearchQuery(query, pc.summaryContext, rewriteSignal);
1290
+ return rewriteSearchQuery(query, pc.summaryContext, rewriteSignal, readHelperModelKey("queryRewriteModel"));
1294
1291
  });
1295
1292
  },
1296
1293
  },
@@ -1405,7 +1402,11 @@ export default function (pi: ExtensionAPI) {
1405
1402
  if (event.parentToolCallId && event.toolName === toolNames.webSearch) nestedSearchCallIds.add(event.toolCallId);
1406
1403
  });
1407
1404
 
1408
- pi.on("session_start", async (_event, ctx) => { nestedSearchCallIds.clear(); startSession(ctx); });
1405
+ pi.on("session_start", async (_event, ctx) => {
1406
+ nestedSearchCallIds.clear();
1407
+ startSession(ctx);
1408
+ void showUpgradeNotice(ctx).catch((error) => console.error("Failed to show the pi-web-access upgrade notice:", error));
1409
+ });
1409
1410
  pi.on("session_tree", async (_event, ctx) => { nestedSearchCallIds.clear(); startSession(ctx); });
1410
1411
 
1411
1412
  pi.on("session_shutdown", () => {
@@ -1422,30 +1423,27 @@ export default function (pi: ExtensionAPI) {
1422
1423
  if (webSearchEnabled) pi.registerTool({
1423
1424
  name: toolNames.webSearch,
1424
1425
  label: "Web Search",
1425
- prepareArguments: (args) => parseStringifiedArrays(args, ["provider", "queries", "domainFilter"]) as never,
1426
+ prepareArguments: (args) => parseStringifiedArrays(args, ["queries", "domainFilter"]) as never,
1426
1427
  description:
1427
- `Search the web and return source-linked results or provider answers.${getSearchContentEnabled ? ` Full results are stored for retrieval with ${toolNames.getSearchContent} using the returned responseId.` : ""} For research, prefer queries with 2-4 varied angles over a single query. Omit provider to use the configured default; set it only to override that.`,
1428
+ `Search the web for sources or answers.${getSearchContentEnabled ? ` Full results are stored for retrieval with ${toolNames.getSearchContent} by responseId.` : ""} Prefer 2-4 varied queries.`,
1428
1429
  promptSnippet:
1429
- "Use for web research questions. Prefer {queries:[...]} with 2-4 varied angles over a single query for broader coverage. Omit provider unless explicitly overriding the configured default.",
1430
+ "Web research. Prefer {queries:[...]} with 2-4 varied angles; omit provider unless overriding the default.",
1430
1431
  parameters: Type.Object({
1431
- query: Type.Optional(Type.String({ description: "Single search query. For research tasks, prefer 'queries' with multiple varied angles instead." })),
1432
- queries: Type.Optional(Type.Array(Type.String(), { description: "Multiple queries searched concurrently (up to three at a time), each returning source-linked search results or a provider answer. Prefer this for research — vary phrasing, scope, and angle across 2-4 queries to maximize coverage. Good: ['React vs Vue performance benchmarks 2026', 'React vs Vue developer experience comparison', 'React ecosystem size vs Vue ecosystem']. Bad: ['React vs Vue', 'React vs Vue comparison', 'React vs Vue review'] (too similar, redundant results)." })),
1433
- numResults: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Results per query (default: 5, max: 20)" })),
1434
- includeContent: Type.Optional(Type.Boolean({ description: "Fetch full page content (async)" })),
1435
- recencyFilter: Type.Optional(
1436
- StringEnum(["day", "week", "month", "year"], { description: "Filter by recency" }),
1437
- ),
1438
- domainFilter: Type.Optional(Type.Array(Type.String(), { description: "Limit to domains (prefix with - to exclude)" })),
1439
- category: Type.Optional(Type.String({ description: "Exa only: result category, e.g. news, research paper" })),
1440
- provider: Type.Optional(searchProviderSchema(`Search provider or non-empty list of allowed providers to search simultaneously; ${allPolicyDescription}; omit this field to use the configured provider, or use auto when none is configured`, allowedSearchProviders)),
1432
+ query: Type.Optional(Type.String()),
1433
+ queries: Type.Optional(Type.Array(Type.String(), { description: "Run concurrently (up to three at a time); vary the angle" })),
1434
+ numResults: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Default 5" })),
1435
+ includeContent: Type.Optional(Type.Boolean({ description: "Also fetch full page content" })),
1436
+ recencyFilter: Type.Optional(StringEnum(["day", "week", "month", "year"])),
1437
+ domainFilter: Type.Optional(Type.Array(Type.String(), { description: "Prefix - to exclude" })),
1438
+ category: Type.Optional(Type.String({ description: "Exa only, e.g. news" })),
1439
+ ...(modelProviders.length > 0 ? { model: Type.Optional(Type.String({ description: `Model ID; needs provider ${modelProviders.join(", ")}` })) } : {}) as { model: TOptional<TString> },
1440
+ provider: Type.Optional(Type.String({ description: providerDescription })),
1441
1441
  workflow: Type.Optional(
1442
1442
  StringEnum(["none", "summary-review", "auto-summary"], {
1443
- description: "Search workflow mode: none = no curator (default), summary-review = open curator with auto summary draft, auto-summary = generate summary without opening curator",
1443
+ description: "Default none; summary-review opens the curator; auto-summary summarizes",
1444
1444
  }),
1445
1445
  ),
1446
- proxy: Type.Optional(Type.String({
1447
- description: "http(s) or socks proxy URL (e.g. http://host:port or socks5h://host:port) used for every outbound request in this call (search APIs and content fetches). Node fetch ignores HTTP(S)_PROXY env vars, so set this (or `proxy` in web-search.json) when direct access is blocked; empty string forces direct access.",
1448
- })),
1446
+ proxy: Type.Optional(Type.String({ description: "http(s) or socks proxy URL (env proxy vars ignored); \"\" forces direct" })),
1449
1447
  }),
1450
1448
  outputSchema: webSearchOutputSchema,
1451
1449
  exposure: toolExposure,
@@ -1479,6 +1477,13 @@ export default function (pi: ExtensionAPI) {
1479
1477
  };
1480
1478
  }
1481
1479
 
1480
+ if (shouldCurate && params.model !== undefined) {
1481
+ return {
1482
+ content: [{ type: "text", text: "Error: model cannot be used with workflow \"summary-review\". Pass workflow \"none\" or \"auto-summary\" to search with a specific model." }],
1483
+ details: { error: "model is not supported with summary-review" },
1484
+ };
1485
+ }
1486
+
1482
1487
  if (shouldCurate) {
1483
1488
  closeCurator(callId);
1484
1489
 
@@ -1497,7 +1502,7 @@ export default function (pi: ExtensionAPI) {
1497
1502
  let cancelled = false;
1498
1503
 
1499
1504
  const requestedProvider = resolveRequestedProvider(params.provider);
1500
- const providerFromConfig = (normalizeProviderInput(params.provider) ?? "auto") === "auto";
1505
+ const providerFromConfig = (parseProviderArgument(params.provider) ?? "auto") === "auto";
1501
1506
  const bootstrap = await loadCuratorBootstrap(requestedProvider, ctx, {
1502
1507
  numResults: params.numResults,
1503
1508
  recencyFilter,
@@ -1707,6 +1712,7 @@ export default function (pi: ExtensionAPI) {
1707
1712
  undefined,
1708
1713
  getSummaryGenerationDeadlineMs(),
1709
1714
  getSummaryInstructions(),
1715
+ { preferredFallback: summaryModelChoices.preferredFallback },
1710
1716
  );
1711
1717
  return { approvedSummary: generated.summary, summaryMeta: generated.meta };
1712
1718
  };
@@ -1972,19 +1978,17 @@ export default function (pi: ExtensionAPI) {
1972
1978
  if (sourceCheckEnabled) pi.registerTool({
1973
1979
  name: toolNames.sourceCheck,
1974
1980
  label: "Source Check",
1975
- description: "Gather web sources for a claim and return a bounded machine-readable research artifact with exact passage citations for manual review.",
1976
- promptSnippet: "Gather structured source evidence and passage-level citations for manual semantic review of a claim.",
1981
+ description: "Gather cited web passages about a claim for manual review.",
1982
+ promptSnippet: "Gather source evidence with passage citations for a claim.",
1977
1983
  parameters: Type.Object({
1978
- claim: Type.String({ description: "The assertion to gather web sources for." }),
1979
- queries: Type.Optional(Type.Array(Type.String(), { description: "Search queries (default: the claim)." })),
1980
- numResults: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Results per query (default: 5, max: 20)." })),
1981
- fetchContent: Type.Optional(Type.Boolean({ description: "Fetch up to 5 result pages for exact passage extraction." })),
1982
- recencyFilter: Type.Optional(StringEnum(["day", "week", "month", "year"], { description: "Filter by recency." })),
1983
- domainFilter: Type.Optional(Type.Array(Type.String(), { description: "Limit to domains; prefix with - to exclude." })),
1984
- provider: Type.Optional(searchProviderSchema(`Search provider or non-empty list of allowed providers to search simultaneously; ${allPolicyDescription}`, allowedSearchProviders)),
1985
- proxy: Type.Optional(Type.String({
1986
- description: "http(s) or socks proxy URL (e.g. http://host:port or socks5h://host:port) used for every outbound request in this call (search APIs and result-page fetches). Empty string forces direct access.",
1987
- })),
1984
+ claim: Type.String({ description: "Assertion to check" }),
1985
+ queries: Type.Optional(Type.Array(Type.String(), { description: "Default: the claim" })),
1986
+ numResults: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Default 5" })),
1987
+ fetchContent: Type.Optional(Type.Boolean({ description: "Fetch top 5 pages for exact passages" })),
1988
+ recencyFilter: Type.Optional(StringEnum(["day", "week", "month", "year"])),
1989
+ domainFilter: Type.Optional(Type.Array(Type.String(), { description: "Prefix - to exclude" })),
1990
+ provider: Type.Optional(Type.String({ description: providerDescription })),
1991
+ proxy: Type.Optional(Type.String({ description: "http(s) or socks proxy URL; \"\" forces direct" })),
1988
1992
  }),
1989
1993
  exposure: toolExposure,
1990
1994
  async execute(_callId, params, signal, _onUpdate, ctx) {
@@ -1995,47 +1999,46 @@ export default function (pi: ExtensionAPI) {
1995
1999
  if (fetchContentEnabled) pi.registerTool({
1996
2000
  name: toolNames.fetchContent,
1997
2001
  label: "Fetch Content",
1998
- description: `Fetch URL(s). Available modes: ${fetchModeDescription}. Direct image URLs return resized image content when supported by the selected mode. Supports YouTube transcripts, GitHub repositories, PDFs, and local videos when supported by the selected mode. ${fetchContentStorageNote}`,
2002
+ description: `Fetch web pages, PDFs, GitHub repos, images, YouTube and local video, as the mode allows. ${fetchContentStorageNote}`,
1999
2003
  promptSnippet:
2000
- "Use to fetch URL content, direct images, GitHub repos, and videos.",
2004
+ `Use to fetch URL content, direct images, GitHub repos, and videos.${fetchModeConfig.allowedModes.includes("extract") ? ' For specific values (a price, version, date or limit), use mode "extract" with fields instead of reading the whole page.' : ""}`,
2001
2005
  parameters: Type.Object({
2002
- url: Type.Optional(Type.String({ description: "Single URL to fetch" })),
2003
- urls: Type.Optional(Type.Array(Type.String(), { description: "Multiple URLs (parallel)" })),
2004
- forceClone: Type.Optional(Type.Boolean({
2005
- description: "Force cloning large GitHub repositories that exceed the size threshold",
2006
- })),
2006
+ url: Type.Optional(Type.String()),
2007
+ urls: Type.Optional(Type.Array(Type.String())),
2008
+ forceClone: Type.Optional(Type.Boolean({ description: "Clone GitHub repos over the size limit" })),
2007
2009
  prompt: Type.Optional(Type.String({
2008
2010
  description: fetchModeConfig.allowedModes.includes("answer")
2009
- ? "Question or instruction for video analysis, or the page-local question required by answer mode."
2010
- : "Question or instruction for video analysis.",
2011
+ ? "Question for video analysis or answer mode"
2012
+ : "Question for video analysis",
2011
2013
  })),
2012
2014
  mode: Type.Optional(StringEnum(fetchModeConfig.allowedModes, {
2013
- description: `Fetch mode. ${fetchModeDescription}.`,
2015
+ description: `${fetchModeDescription}.`,
2014
2016
  })),
2015
2017
  ...(fetchModeConfig.allowedModes.includes("answer") ? {
2016
2018
  answerModel: Type.Optional(Type.String({
2017
- description: "Optional provider/model-id override for answer mode. Defaults to fetch.answerProvider + fetch.answerModel when configured, otherwise the current Pi model.",
2019
+ description: "provider/model-id for answer mode",
2020
+ })),
2021
+ } : {}),
2022
+ ...(fetchModeConfig.allowedModes.includes("extract") ? {
2023
+ fields: Type.Optional(Type.Record(Type.String(), Type.String(), {
2024
+ description: "For extract: name → \"type\" or \"type: what to find\"; types: text, number, integer, date, time, datetime, duration[.unit], list[.number|.date]",
2018
2025
  })),
2019
2026
  } : {}),
2020
2027
  timestamp: Type.Optional(Type.String({
2021
- description: "Extract video frame(s) at a timestamp or time range. Single: '1:23:45', '23:45', or '85' (seconds). Range: '23:41-25:00' extracts evenly-spaced frames across that span (default 6). Use frames with ranges to control density; single+frames uses a fixed 5s interval. YouTube requires yt-dlp + ffmpeg; local videos require ffmpeg. Use a range when you know the approximate area but not the exact moment — you'll get a contact sheet to visually identify the right frame.",
2028
+ description: "Video frame time ('1:23:45') or range ('23:41-25:00'); needs ffmpeg",
2022
2029
  })),
2023
2030
  frames: Type.Optional(Type.Integer({
2024
2031
  minimum: 1,
2025
2032
  maximum: 12,
2026
- description: "Number of frames to extract. Use with timestamp range for custom density, with single timestamp to get N frames at 5s intervals, or alone to sample across the entire video. Requires yt-dlp + ffmpeg for YouTube, ffmpeg for local video.",
2027
- })),
2028
- model: Type.Optional(Type.String({
2029
- description: "Override the Gemini model for video/YouTube analysis (e.g. 'gemini-3.6-flash'). Defaults to config or gemini-3.6-flash.",
2033
+ description: "Frames over a range, 5s apart from one time, or over the video",
2030
2034
  })),
2035
+ model: Type.Optional(Type.String({ description: "Gemini model for video analysis" })),
2031
2036
  auth: Type.Optional(Type.Union([Type.String(), Type.Boolean()], {
2032
- description: "Opt into an authFetch profile for local browser-cookie fetching. Use a profile name, or true only when exactly one profile exists.",
2033
- })),
2034
- proxy: Type.Optional(Type.String({
2035
- description: "http(s) or socks proxy URL (e.g. http://host:port or socks5h://host:port) used for this fetch. Needed when the target is unreachable directly; localhost and NO_PROXY hosts always bypass the proxy. Empty string forces direct access.",
2037
+ description: "authFetch profile name, or true for the only one",
2036
2038
  })),
2039
+ proxy: Type.Optional(Type.String({ description: "http(s) or socks proxy URL; \"\" forces direct" })),
2037
2040
  redirects: Type.Optional(StringEnum(["same-origin"], {
2038
- description: "Refuse cross-origin redirects: every redirect target must match the requested URL's scheme, hostname and effective port, and extraction paths whose redirect chain cannot be observed are refused instead of used.",
2041
+ description: "Refuse cross-origin redirects",
2039
2042
  })),
2040
2043
  }),
2041
2044
  outputSchema: fetchContentOutputSchema,
@@ -2187,22 +2190,22 @@ export default function (pi: ExtensionAPI) {
2187
2190
  pi.registerTool({
2188
2191
  name: toolNames.getSearchContent,
2189
2192
  label: "Get Search Content",
2190
- description: `Retrieve bounded pages of full stored search results or fetched content, or find matching passages, from a previous ${storedContentSources} call.`,
2193
+ description: `Page through or search stored content from ${storedContentSources} by responseId.`,
2191
2194
  promptSnippet:
2192
- `Use after ${storedContentSources} to retrieve stored content via responseId. Use findText to locate passages without paging through the full content.`,
2195
+ `Use after ${storedContentSources} to read stored content; findText finds passages without paging.`,
2193
2196
  parameters: Type.Object({
2194
- responseId: Type.String({ description: `The responseId from ${storedContentSources}` }),
2195
- query: Type.Optional(Type.String({ description: searchQueryDescription })),
2196
- queryIndex: Type.Optional(Type.Integer({ minimum: 0, description: "Get content for query at index" })),
2197
- url: Type.Optional(Type.String({ description: "Get content for this URL" })),
2198
- urlIndex: Type.Optional(Type.Integer({ minimum: 0, description: "Get content for URL at index" })),
2199
- offset: Type.Optional(Type.Integer({ minimum: 0, description: "Character offset in stored search or fetched URL content (default 0). Ignored when findText is supplied." })),
2200
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: maxInlineContentChars, description: "Requested maximum stored-content characters (default and max use maxInlineContentChars). Search-page continuation guidance shares the global output cap and may reduce returnedChars. Ignored when findText is supplied." })),
2197
+ responseId: Type.String(),
2198
+ query: Type.Optional(Type.String()),
2199
+ queryIndex: Type.Optional(Type.Integer({ minimum: 0 })),
2200
+ url: Type.Optional(Type.String()),
2201
+ urlIndex: Type.Optional(Type.Integer({ minimum: 0 })),
2202
+ offset: Type.Optional(Type.Integer({ minimum: 0 })),
2203
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: maxInlineContentChars, description: "Characters, default the maximum" })),
2201
2204
  findText: Type.Optional(Type.Union([
2202
2205
  Type.String({ minLength: 1, maxLength: 500 }),
2203
2206
  Type.Array(Type.String({ minLength: 1, maxLength: 500 }), { minItems: 1, maxItems: 10 }),
2204
- ], { description: "Text or texts to find in the selected stored content. When supplied, offset and limit are ignored." })),
2205
- findMode: Type.Optional(StringEnum(["exact", "case-insensitive", "fuzzy"], { description: "Matching mode for findText (default: case-insensitive). Requires findText." })),
2207
+ ], { description: "Find passages instead of paging" })),
2208
+ findMode: Type.Optional(StringEnum(["exact", "case-insensitive", "fuzzy"])),
2206
2209
  }),
2207
2210
  exposure: toolExposure,
2208
2211
 
@@ -2466,7 +2469,7 @@ export default function (pi: ExtensionAPI) {
2466
2469
  if (commandHandle && !isCommandActive()) {
2467
2470
  throw new Error("Curator session is no longer active.");
2468
2471
  }
2469
- return rewriteSearchQuery(query, summaryContext, rewriteSignal);
2472
+ return rewriteSearchQuery(query, summaryContext, rewriteSignal, readHelperModelKey("queryRewriteModel"));
2470
2473
  },
2471
2474
  },
2472
2475
  );
@@ -213,7 +213,7 @@ export function isMistralAvailable(): boolean {
213
213
 
214
214
  export async function searchWithMistral(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
215
215
  const config = loadConfig();
216
- const model = resolveSearchModel(config.mistralSearchModel);
216
+ const model = options.model ?? resolveSearchModel(config.mistralSearchModel);
217
217
  const tool = resolveSearchTool(config.mistralSearchTool);
218
218
  const numResults = normalizeCount(options.numResults);
219
219
  const apiKey = await getApiKey(options.signal);
@@ -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
+ }