@juicesharp/rpiv-web-tools 1.20.0 → 2.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.
@@ -0,0 +1,108 @@
1
+ # Providers and credential resolution
2
+
3
+ The ten search backends `rpiv-web-tools` ships with, what each one needs, and the
4
+ exact order in which the active provider, its API key, and its base URL are
5
+ resolved.
6
+
7
+ ## The ten providers
8
+
9
+ One is active at a time. Switching backends never discards the other backends'
10
+ keys — they are stored per provider under `apiKeys.<name>`.
11
+
12
+ | Provider | `provider` name | Key env var | Sign up | `web_fetch` path |
13
+ | --- | --- | --- | --- | --- |
14
+ | Brave | `brave` | `BRAVE_SEARCH_API_KEY` | [brave.com/search/api](https://brave.com/search/api/) | built-in HTTP → text, honours `raw` |
15
+ | Tavily | `tavily` | `TAVILY_API_KEY` | [tavily.com](https://tavily.com) | native extraction (plain text) |
16
+ | Serper | `serper` | `SERPER_API_KEY` | [serper.dev](https://serper.dev) | built-in HTTP → text, honours `raw` |
17
+ | Exa | `exa` | `EXA_API_KEY` | [exa.ai](https://exa.ai) | native extraction (plain text) |
18
+ | You.com | `youcom` | `YOUCOM_API_KEY` | [you.com](https://you.com) | native extraction (markdown) |
19
+ | Jina | `jina` | `JINA_API_KEY` | [jina.ai/reader](https://jina.ai/reader) | native extraction (markdown) |
20
+ | Firecrawl | `firecrawl` | `FIRECRAWL_API_KEY` | [firecrawl.dev](https://firecrawl.dev) | native extraction (markdown) |
21
+ | Perplexity | `perplexity` | `PERPLEXITY_API_KEY` | [docs.perplexity.ai](https://docs.perplexity.ai/) | built-in HTTP → text, honours `raw` |
22
+ | SearXNG | `searxng` | `SEARXNG_API_KEY` (optional) | self-hosted — see [self-hosted.md](self-hosted.md) | built-in HTTP → text, honours `raw` |
23
+ | Ollama | `ollama` | `OLLAMA_API_KEY` (optional locally) | local or [ollama.com](https://ollama.com) | native extraction |
24
+
25
+ SearXNG and Ollama also take a base URL (`SEARXNG_URL`, `OLLAMA_HOST`) because
26
+ they talk to an instance you control. Both are covered in
27
+ [self-hosted.md](self-hosted.md).
28
+
29
+ ## Active provider
30
+
31
+ Four tiers, first match wins:
32
+
33
+ 1. **The `provider` parameter on a single `web_search` call.** Validated against
34
+ the ten known names; an unknown name throws. When present, tiers 2–4 are not
35
+ consulted at all.
36
+ 2. **`WEB_SEARCH_PROVIDER`** environment variable. Trimmed; a whitespace-only
37
+ value counts as unset. Validated *only when it is the resolving tier*, so a
38
+ bogus value cannot defeat a valid per-call override — it throws on the next
39
+ `web_search` that actually resolves through it.
40
+ 3. **`provider` in the config file**, which is what `/web-tools` writes.
41
+ 4. **`brave`**, the built-in default.
42
+
43
+ `/web-tools --show` prints the resolved name together with its source
44
+ (`env`, `config`, or `default`), so you can see which tier won.
45
+
46
+ An unknown name at tier 1 or tier 2 throws:
47
+
48
+ ```
49
+ Unknown web_search provider: "bravo". Valid providers: brave, tavily, serper, exa, youcom, jina, firecrawl, perplexity, searxng, ollama.
50
+ ```
51
+
52
+ Tiers 3 and 4 are not validated at resolution time — a typo in the config file
53
+ instead surfaces `Unknown search provider: "bravo"` from the provider factory on
54
+ the next `web_search`.
55
+
56
+ ## API key
57
+
58
+ Resolved per provider, under whichever provider name won above. Three tiers,
59
+ first match wins:
60
+
61
+ 1. **The provider's own environment variable** (`BRAVE_SEARCH_API_KEY`,
62
+ `TAVILY_API_KEY`, `SERPER_API_KEY`, `EXA_API_KEY`, `YOUCOM_API_KEY`,
63
+ `JINA_API_KEY`, `FIRECRAWL_API_KEY`, `PERPLEXITY_API_KEY`,
64
+ `SEARXNG_API_KEY`, `OLLAMA_API_KEY`).
65
+ 2. **`apiKeys.<provider>`** in the config file.
66
+ 3. **Legacy top-level `apiKey`**, Brave only. It is auto-migrated into
67
+ `apiKeys.brave` and deleted from the file on the next `/web-tools` save.
68
+
69
+ Every environment value is trimmed, so an empty or whitespace-only variable is
70
+ treated as unset and resolution falls through to the next tier.
71
+
72
+ There is **no cross-provider fallback**. If the resolved provider has no key,
73
+ the call throws:
74
+
75
+ ```
76
+ EXA_API_KEY is not set. Run /web-tools to configure, or export the env var.
77
+ ```
78
+
79
+ That is deliberate — an agent can detect the misconfiguration instead of
80
+ silently getting results from a backend it did not ask for.
81
+
82
+ ## Base URL
83
+
84
+ Only consulted for providers that declare a base-URL environment variable
85
+ (SearXNG and Ollama today). Hosted providers short-circuit to the empty string.
86
+
87
+ 1. The provider's base-URL environment variable (`SEARXNG_URL`, `OLLAMA_HOST`).
88
+ 2. `baseUrls.<provider>` in the config file.
89
+ 3. The provider's built-in default (`http://localhost:8080` for SearXNG,
90
+ `http://localhost:11434` for Ollama).
91
+
92
+ `/web-tools --show` prints one `<provider> url: <resolved> (source: …)` line per
93
+ provider that declares a base URL.
94
+
95
+ ## Picker markers
96
+
97
+ The `/web-tools` provider list is ordered with the active provider first, marked
98
+ `✓`. Any provider that already resolves to a key is suffixed `(configured)`. For
99
+ SearXNG and Ollama, `(configured)` means a base URL has been set explicitly via
100
+ environment variable or config — the bare built-in default does not count,
101
+ because it only indicates the setting has never been touched.
102
+
103
+ ## Related
104
+
105
+ - [tools.md](tools.md) — the `provider` parameter and its effect on resolution.
106
+ - [configuration.md](configuration.md) — where the config file lives and what
107
+ every key does.
108
+ - [self-hosted.md](self-hosted.md) — SearXNG and Ollama setup.
@@ -0,0 +1,120 @@
1
+ # Self-hosted backends
2
+
3
+ Two of the ten providers talk to an instance you run yourself, so nothing has to
4
+ leave your network: **SearXNG** and **Ollama**. Both take a base URL in addition
5
+ to (or instead of) an API key, and both drive their own prompt flow inside
6
+ `/web-tools` — URL first, then the optional key.
7
+
8
+ ## SearXNG
9
+
10
+ [SearXNG](https://docs.searxng.org/) is a self-hosted metasearch engine. It
11
+ needs a base URL; the API key is optional and only used when the instance sits
12
+ behind a Bearer-auth reverse proxy.
13
+
14
+ ```sh
15
+ export SEARXNG_URL=http://localhost:8080
16
+ # Optional: only if your instance sits behind a Bearer-auth reverse proxy
17
+ export SEARXNG_API_KEY=…
18
+ ```
19
+
20
+ Base-URL resolution: `SEARXNG_URL` → `baseUrls.searxng` in the config file →
21
+ `http://localhost:8080`. When the resolved URL is empty, `web_search` throws
22
+ `SEARXNG_URL is not set. Run /web-tools to configure, or export the env var.`
23
+
24
+ ### JSON output must be enabled
25
+
26
+ Your instance must have `json` listed under `search.formats` in `settings.yml`.
27
+ Default SearXNG installs ship with JSON disabled and return `403 Forbidden`
28
+ otherwise (see the
29
+ [SearXNG search API docs](https://docs.searxng.org/dev/search_api.html)). The
30
+ provider surfaces that case with an actionable hint appended to the error:
31
+
32
+ - `403` → *the SearXNG instance may have JSON output disabled; enable 'json'
33
+ under 'search.formats' in its settings.yml*
34
+ - `401` → *the SearXNG instance's reverse-proxy rejected the Bearer token; check
35
+ `SEARXNG_API_KEY` or `apiKeys.searxng`*
36
+
37
+ ### Running SearXNG locally with Docker
38
+
39
+ The `searxng/searxng` entrypoint **overwrites** `/etc/searxng/settings.yml` on
40
+ first start with the bundled default (which ships `formats: [html]` only).
41
+ Pre-populating the mounted file does not stick — wait for the entrypoint, then
42
+ patch:
43
+
44
+ ```sh
45
+ mkdir -p ~/.searxng
46
+ docker run -d --name searxng --restart unless-stopped \
47
+ -p 8080:8080 -v "$HOME/.searxng":/etc/searxng \
48
+ -e BASE_URL=http://localhost:8080/ searxng/searxng:latest
49
+ sleep 5 # wait for entrypoint to write settings.yml
50
+ sed -i.bak '/^ formats:$/,/^[^ ]/ { /- html/a\
51
+ - json
52
+ }' ~/.searxng/settings.yml
53
+ docker restart searxng
54
+
55
+ # Sanity check — a number > 0 means it's wired correctly
56
+ curl -sf 'http://localhost:8080/search?q=hello&format=json' | jq '.results | length'
57
+ ```
58
+
59
+ A `403` here means JSON is still disabled — re-check `~/.searxng/settings.yml`.
60
+ Works identically on Docker Desktop and OrbStack. For a throwaway test instance,
61
+ swap `~/.searxng` for `/tmp/searxng` and drop `--restart unless-stopped`.
62
+
63
+ ### Fetching
64
+
65
+ SearXNG is search-only. `web_fetch` falls through to the built-in HTTP +
66
+ HTML-to-text pipeline, so URLs returned by `web_search` are readable with no
67
+ extra setup, and `raw: true` is honoured.
68
+
69
+ ## Ollama
70
+
71
+ [Ollama](https://ollama.com) exposes web search and web fetch as built-in
72
+ capabilities. Local use needs no third-party key; cloud use requires one.
73
+
74
+ ### Local
75
+
76
+ ```sh
77
+ ollama serve
78
+ ```
79
+
80
+ That is all — the provider talks to `http://localhost:11434` by default and no
81
+ API key is needed. If the instance is not running, the error is
82
+ `Could not connect to Ollama at <host>. Make sure Ollama is running (ollama serve).`
83
+
84
+ ### Cloud
85
+
86
+ ```sh
87
+ export OLLAMA_HOST=https://ollama.com
88
+ export OLLAMA_API_KEY=your_api_key # generate at https://ollama.com/settings/keys
89
+ ```
90
+
91
+ Or run `/web-tools`, select **Ollama**, and enter the URL and key interactively.
92
+
93
+ ### Resolution
94
+
95
+ - **Base URL**: `OLLAMA_HOST` → `baseUrls.ollama` in the config file →
96
+ `http://localhost:11434`. An empty resolved URL throws
97
+ `OLLAMA_HOST is not set. Run /web-tools to configure, or export the env var.`
98
+ - **API key**: `OLLAMA_API_KEY` → `apiKeys.ollama` in the config file. Optional
99
+ for local, required for cloud.
100
+
101
+ ### API paths
102
+
103
+ The provider picks the endpoint pair from the resolved host, so you never set it
104
+ by hand:
105
+
106
+ | Host | Search path | Fetch path |
107
+ | --- | --- | --- |
108
+ | `localhost`, `127.0.0.1`, `0.0.0.0`, `[::1]` | `/api/experimental/web_search` | `/api/experimental/web_fetch` |
109
+ | anything else (cloud) | `/api/web_search` | `/api/web_fetch` |
110
+
111
+ Ollama is a full provider: `web_fetch` uses its native extraction endpoint
112
+ rather than the built-in HTML pipeline.
113
+
114
+ ## Note on the host guard
115
+
116
+ `web_fetch` refuses private and loopback hosts, but that guard applies to URLs
117
+ fetched **on the model's behalf**, not to provider endpoints. A `SEARXNG_URL` or
118
+ `OLLAMA_HOST` pointing at `http://localhost` is intentionally reachable — these
119
+ providers are self-hosted by design. See
120
+ [tools.md](tools.md#host-guard) for the full guard.
package/docs/tools.md ADDED
@@ -0,0 +1,175 @@
1
+ # Tool reference
2
+
3
+ Complete parameter schemas, result envelopes, and failure modes for the two tools
4
+ `rpiv-web-tools` registers: `web_search` and `web_fetch`.
5
+
6
+ ## `web_search`
7
+
8
+ Registered as tool name `web_search`, label `Web Search`. Queries the active
9
+ search provider's API and returns titled results with URLs and snippets.
10
+
11
+ ### Parameters
12
+
13
+ ```ts
14
+ web_search({
15
+ query: string, // required — natural-language query
16
+ max_results?: number, // 1-10, default 5
17
+ provider?: // per-call override; see below
18
+ | "brave" | "tavily" | "serper" | "exa" | "youcom" | "jina"
19
+ | "firecrawl" | "perplexity" | "searxng" | "ollama",
20
+ })
21
+ ```
22
+
23
+ `max_results` is **clamped**, not rejected: values below `1` become `1`, values
24
+ above `10` become `10`, and an omitted value becomes `5`.
25
+
26
+ ### Result
27
+
28
+ ```ts
29
+ {
30
+ content: [{ type: "text", text: string }], // "**Search results for \"<query>\":**"
31
+ // then a numbered list of
32
+ // "**title**\n url\n snippet"
33
+ details: {
34
+ query: string,
35
+ backend: string, // the provider that actually ran
36
+ resultCount: number,
37
+ results?: Array<{ title: string, url: string, snippet: string }>,
38
+ }
39
+ }
40
+ ```
41
+
42
+ When the provider returns zero results, the envelope collapses to
43
+ `content: [{ type: "text", text: 'No results found for "<query>".' }]` with
44
+ `details.resultCount = 0` and no `results` array.
45
+
46
+ ### Throws
47
+
48
+ | Condition | Message shape |
49
+ | --- | --- |
50
+ | Resolved provider has no key | `EXA_API_KEY is not set. Run /web-tools to configure, or export the env var.` |
51
+ | Unknown provider name | `Unknown web_search provider: "<name>". Valid providers: brave, tavily, serper, exa, youcom, jina, firecrawl, perplexity, searxng, ollama.` |
52
+ | Provider API returns non-2xx | vendor-specific, with the status code |
53
+
54
+ ### Per-call `provider` override
55
+
56
+ The optional `provider` parameter routes a single call to a different backend
57
+ without mutating persisted config and without a session restart. The named
58
+ provider must have its own credentials — the override does **not** inherit the
59
+ active provider's key, and an unconfigured target throws the usual `… is not
60
+ set` error rather than silently falling back, so the caller can detect the
61
+ misconfiguration.
62
+
63
+ An override also short-circuits the `WEB_SEARCH_PROVIDER` environment variable
64
+ entirely: that tier is neither read nor validated when an override is present,
65
+ so a bogus env var cannot defeat a valid per-call override. Full four-tier
66
+ resolution is documented in [providers.md](providers.md#active-provider).
67
+
68
+ Use it for provider comparison inside one session, or to retry against a second
69
+ backend when the active one returns poor results.
70
+
71
+ ## `web_fetch`
72
+
73
+ Registered as tool name `web_fetch`, label `Web Fetch`. Reads an http/https URL
74
+ and returns its text.
75
+
76
+ ### Parameters
77
+
78
+ ```ts
79
+ web_fetch({
80
+ url: string, // required — http or https only
81
+ raw?: boolean, // true → raw response body; default false → text
82
+ })
83
+ ```
84
+
85
+ ### Result
86
+
87
+ ```ts
88
+ {
89
+ content: [{ type: "text", text: string }], // header block + body
90
+ details: {
91
+ url: string,
92
+ title?: string, // <title> element, when present
93
+ contentType?: string,
94
+ contentLength?: number, // from the Content-Length header
95
+ truncation?: TruncationResult, // present only when the body was truncated
96
+ fullOutputPath?: string, // temp file holding the un-truncated body
97
+ }
98
+ }
99
+ ```
100
+
101
+ The text content is prefixed with a header block before the body:
102
+
103
+ ```
104
+ **Fetched:** <url>
105
+ **Title:** <title>
106
+ **Content-Type:** <content-type>
107
+ ```
108
+
109
+ ### Dispatch order
110
+
111
+ `web_fetch` resolves the body through three tiers, first hit wins:
112
+
113
+ 1. **URL interceptors** — currently only the opt-in GitHub interceptor, which
114
+ returns `null` for anything that isn't a github.com code URL. The chain is
115
+ empty when the interceptor is disabled. See
116
+ [github-interceptor.md](github-interceptor.md).
117
+ 2. **The active provider's native fetch** — Tavily, Exa, You.com, Jina,
118
+ Firecrawl and Ollama carry vendor extraction endpoints.
119
+ 3. **The built-in HTTP + HTML-to-text pipeline** — used for search-only
120
+ providers (Brave, Serper, Perplexity, SearXNG) and whenever the active
121
+ provider has no `fetch` method. This path needs no API key at all, so
122
+ `web_fetch` still works when the active provider is an unkeyed search-only
123
+ backend. An unkeyed extraction provider (Tavily, Exa, You.com, Jina,
124
+ Firecrawl) throws instead, because its native fetch runs first and never
125
+ reaches this tier.
126
+
127
+ `raw: true` is honoured by tier 3 (raw response instead of extracted text).
128
+ Extraction providers always return their own parsed text.
129
+
130
+ ### Truncation and spillover
131
+
132
+ Bodies are truncated to 2000 lines / 50 KB. When truncation occurs the **full**
133
+ body is written to a temp file under `$TMPDIR/rpiv-fetch-XXXXXX/content.txt`,
134
+ the path is recorded in `details.fullOutputPath`, and a footer is appended to
135
+ the content telling the model exactly what was omitted:
136
+
137
+ ```
138
+ [Content truncated: showing 64 of 988 lines (3.2 KB of 61.4 KB).
139
+ 924 lines (58.2 KB) omitted. Full content saved to: /tmp/rpiv-fetch-Xa0k/content.txt]
140
+ ```
141
+
142
+ The model can then read the temp file to recover the rest.
143
+
144
+ ### Host guard
145
+
146
+ `web_fetch` parses the URL and refuses it before any network call when the
147
+ protocol is not `http:`/`https:`, or when the host literal falls in a
148
+ private/loopback range:
149
+
150
+ | Class | Refused hosts |
151
+ | --- | --- |
152
+ | Loopback / unspecified | `localhost`, `*.localhost`, `0.0.0.0/8`, `127.0.0.0/8`, `::1`, `::` |
153
+ | RFC 1918 | `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16` |
154
+ | Link-local | `169.254.0.0/16` (including cloud metadata at `169.254.169.254`), `fe80::/10` |
155
+ | IPv6 unique-local | `fc00::/7` (`fc…`, `fd…`) |
156
+
157
+ Refusals surface as `Refusing to fetch private/loopback address: <host>`. The
158
+ guard runs **before** the interceptor chain, so a private host cannot bypass it
159
+ via a github.com-shaped path.
160
+
161
+ The guard is **host-literal only** — it does not resolve DNS and does not
162
+ validate redirects. A public hostname that resolves to a private IP, or a public
163
+ URL that 302-redirects to one, still reaches the target. For untrusted
164
+ automation environments, layer an egress proxy or firewall on top.
165
+
166
+ The guard applies to URLs `web_fetch` retrieves on the model's behalf, not to
167
+ provider endpoints: a `SEARXNG_URL` or `OLLAMA_HOST` pointing at
168
+ `http://localhost` is intentionally reachable.
169
+
170
+ ### Throws
171
+
172
+ Invalid URL, unsupported protocol, a refused private/loopback host, a non-2xx
173
+ response, or an `image/` / `video/` / `audio/` content type. Extraction
174
+ providers additionally throw on an empty body or a vendor-level failure (for
175
+ example Firecrawl `success: false`, Tavily `failed_results`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-web-tools",
3
- "version": "1.20.0",
3
+ "version": "2.1.0",
4
4
  "description": "Pi extension. Web search and fetch for the model with pluggable providers (Brave, Tavily, Serper, Exa, You.com, Jina, Firecrawl, Perplexity, SearXNG, Ollama).",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -50,8 +50,13 @@
50
50
  "index.ts",
51
51
  "web-tools.ts",
52
52
  "providers/",
53
+ "docs/",
54
+ "!docs/*.png",
55
+ "!docs/*.jpg",
56
+ "!docs/*.svg",
53
57
  "README.md",
54
- "LICENSE"
58
+ "LICENSE",
59
+ "!**/*.test.ts"
55
60
  ],
56
61
  "pi": {
57
62
  "extensions": [
@@ -59,11 +64,11 @@
59
64
  ]
60
65
  },
61
66
  "dependencies": {
62
- "@juicesharp/rpiv-config": "^1.20.0"
67
+ "@juicesharp/rpiv-config": "^2.1.0",
68
+ "typebox": "^1.1.24"
63
69
  },
64
70
  "peerDependencies": {
65
71
  "@earendil-works/pi-coding-agent": "*",
66
- "@earendil-works/pi-tui": "*",
67
- "typebox": "*"
72
+ "@earendil-works/pi-tui": "*"
68
73
  }
69
74
  }
@@ -13,7 +13,12 @@
13
13
  * startup."
14
14
  */
15
15
 
16
- import { configPath, GuidanceFieldsSchema, loadJsonConfig, saveJsonConfig } from "@juicesharp/rpiv-config";
16
+ import {
17
+ configPath,
18
+ GuidanceFieldsSchema,
19
+ loadJsonConfigWithLegacyFallback,
20
+ saveJsonConfig,
21
+ } from "@juicesharp/rpiv-config";
17
22
  import { type Static, Type } from "typebox";
18
23
  import { Value } from "typebox/value";
19
24
 
@@ -76,7 +81,7 @@ export function getConfigPath(): string {
76
81
  // `Value.Clean` (would strip unknown fields like the released `otherField`
77
82
  // pass-through contract).
78
83
  export function readConfig(): WebToolsConfig {
79
- const raw = loadJsonConfig<unknown>(CONFIG_PATH);
84
+ const raw = loadJsonConfigWithLegacyFallback<unknown>("rpiv-web-tools");
80
85
  if (!Value.Check(WebToolsConfigSchema, raw)) {
81
86
  return {} as WebToolsConfig;
82
87
  }
package/providers/exa.ts CHANGED
@@ -10,7 +10,13 @@ export const EXA_PROVIDER_META = {
10
10
  roles: ["search", "fetch"] as const,
11
11
  } as const;
12
12
  const EXA_MAX_SNIPPET_CHARACTERS = 300;
13
- const EXA_MAX_FETCH_CHARACTERS = 10000;
13
+ // Exa's documented maximum is 10 000 characters (OpenAPI schema has
14
+ // `maximum: 10000`), but the live API accepts up to 1 000 000.
15
+ // Using the higher value lets rpiv-web-tools' own truncation
16
+ // (DEFAULT_MAX_BYTES = 50 KiB) take over, which appends a
17
+ // truncation footer and spills full content to a temp file so
18
+ // the model can recover it with the read tool.
19
+ const EXA_MAX_FETCH_CHARACTERS = 1_000_000;
14
20
 
15
21
  interface ExaRawResult {
16
22
  title?: string;
package/web-tools.ts CHANGED
@@ -130,13 +130,68 @@ function resolveProviderBaseUrl(meta: ProviderMeta, config: WebToolsConfig): str
130
130
  return meta.defaultBaseUrl ?? "";
131
131
  }
132
132
 
133
- // Centralized instantiation: load active provider name + creds, build via
134
- // the factory. Called by both registerWebSearchTool and registerWebFetchTool.
135
- function instantiateActiveProvider(config: WebToolsConfig): {
133
+ // Known provider names — derived once from PROVIDERS so the schema enum,
134
+ // the per-call override validation, and the error messages all stay in sync
135
+ // when a provider is added or removed.
136
+ const KNOWN_PROVIDER_NAMES = PROVIDERS.map((p) => p.name) as readonly string[];
137
+
138
+ // Uniform "unknown provider" error for both the per-call override path and the
139
+ // WEB_SEARCH_PROVIDER env path so misconfiguration surfaces the same shape.
140
+ function assertKnownProvider(name: string): void {
141
+ if (!KNOWN_PROVIDER_NAMES.includes(name)) {
142
+ throw new Error(`Unknown web_search provider: "${name}". Valid providers: ${KNOWN_PROVIDER_NAMES.join(", ")}.`);
143
+ }
144
+ }
145
+
146
+ // Active-provider resolution for display + selection surfaces (env over config
147
+ // over default). Returns the raw name + its source — does NOT validate. A bogus
148
+ // WEB_SEARCH_PROVIDER renders in --show/picker (honest display) and only throws
149
+ // on the next web_search, via instantiateProvider's assertKnownProvider.
150
+ function resolveActiveProviderName(config: WebToolsConfig): {
151
+ name: string;
152
+ source: "env" | "config" | "default";
153
+ } {
154
+ const envProvider = process.env.WEB_SEARCH_PROVIDER?.trim();
155
+ if (envProvider) return { name: envProvider, source: "env" };
156
+ if (config.provider) return { name: config.provider, source: "config" };
157
+ return { name: DEFAULT_PROVIDER_NAME, source: "default" };
158
+ }
159
+
160
+ // Centralized instantiation: resolve provider name + creds, build via the
161
+ // factory. Called by both registerWebSearchTool and registerWebFetchTool.
162
+ //
163
+ // `override` lets a single tool call target a different provider than the
164
+ // active one without mutating persisted state. Resolution (4-tier, first wins):
165
+ // providerName = override ?? WEB_SEARCH_PROVIDER ?? config.provider ?? DEFAULT_PROVIDER_NAME
166
+ // 1. override (per-call `provider` param) — validated against PROVIDERS;
167
+ // unknown names throw so callers can detect misconfiguration.
168
+ // 2. WEB_SEARCH_PROVIDER env var — validated like the override, but ONLY
169
+ // when it is the resolving tier: an override wins without consulting
170
+ // (or validating) the env, so a bogus env var cannot defeat a valid
171
+ // per-call override. Lets an operator pin a backend without editing
172
+ // config.json.
173
+ // 3. config.provider (the /web-tools-selected default)
174
+ // 4. DEFAULT_PROVIDER_NAME ("brave")
175
+ // Key/baseURL resolution always reads from env/config under the resolved
176
+ // provider name, so an override/env pin still needs its own credentials.
177
+ function instantiateProvider(
178
+ config: WebToolsConfig,
179
+ override?: string,
180
+ ): {
136
181
  providerName: string;
137
182
  provider: SearchProvider | FullProvider;
138
183
  } {
139
- const providerName = config.provider ?? DEFAULT_PROVIDER_NAME;
184
+ let providerName: string;
185
+ if (override !== undefined) {
186
+ assertKnownProvider(override);
187
+ providerName = override;
188
+ } else {
189
+ // Single env read via the shared resolver (one snapshot — no double
190
+ // read), validated only when env actually won the resolution.
191
+ const active = resolveActiveProviderName(config);
192
+ if (active.source === "env") assertKnownProvider(active.name);
193
+ providerName = active.name;
194
+ }
140
195
  const apiKey = resolveProviderApiKey(providerName, config);
141
196
  const meta = PROVIDERS.find((p) => p.name === providerName);
142
197
  const baseUrl = meta?.baseUrlEnvVar ? resolveProviderBaseUrl(meta, config) : undefined;
@@ -275,12 +330,23 @@ export function registerWebSearchTool(pi: ExtensionAPI): void {
275
330
  maximum: MAX_SEARCH_RESULTS,
276
331
  }),
277
332
  ),
333
+ provider: Type.Optional(
334
+ Type.Union(
335
+ KNOWN_PROVIDER_NAMES.map((name) => Type.Literal(name)),
336
+ {
337
+ description:
338
+ "Search provider to use for this call only, overriding the active provider set via /web-tools. " +
339
+ `Valid values: ${KNOWN_PROVIDER_NAMES.join(", ")}. ` +
340
+ "Omit to use the configured active provider. The named provider must have its API key/URL configured (via env var or /web-tools) or the call throws — there is no silent fallback.",
341
+ },
342
+ ),
343
+ ),
278
344
  }),
279
345
 
280
346
  async execute(_toolCallId, params, signal, onUpdate, _ctx) {
281
347
  const maxResults = clampSearchResultCount(params.max_results);
282
348
  const config = loadConfig();
283
- const { providerName, provider } = instantiateActiveProvider(config);
349
+ const { providerName, provider } = instantiateProvider(config, params.provider);
284
350
 
285
351
  onUpdate?.({
286
352
  content: [{ type: "text", text: `Searching ${provider.label} for: "${params.query}"...` }],
@@ -307,6 +373,9 @@ export function registerWebSearchTool(pi: ExtensionAPI): void {
307
373
  renderCall(args, theme, _context) {
308
374
  let text = theme.fg("toolTitle", theme.bold("WebSearch "));
309
375
  text += theme.fg("accent", `"${args.query}"`);
376
+ if (args.provider) {
377
+ text += theme.fg("dim", ` via ${args.provider}`);
378
+ }
310
379
  return new Text(text, 0, 0);
311
380
  },
312
381
 
@@ -368,7 +437,7 @@ export function registerWebFetchTool(pi: ExtensionAPI): void {
368
437
  });
369
438
 
370
439
  const config = loadConfig();
371
- const { provider } = instantiateActiveProvider(config);
440
+ const { provider } = instantiateProvider(config);
372
441
 
373
442
  // Three-way capability dispatch:
374
443
  // 1. URL interceptors (currently just GitHub) — opt-in URL specialists
@@ -465,8 +534,8 @@ function renderFetchedContentPreview(content: string, theme: Theme): string {
465
534
  function formatShowConfigMessage(current: WebToolsConfig): string {
466
535
  const lines = ["Web search config:", ` config file: ${CONFIG_PATH}`];
467
536
 
468
- const providerName = current.provider ?? DEFAULT_PROVIDER_NAME;
469
- lines.push(` active provider: ${providerName}`);
537
+ const { name: providerName, source: providerSource } = resolveActiveProviderName(current);
538
+ lines.push(` active provider: ${providerName} (source: ${providerSource})`);
470
539
 
471
540
  for (const meta of PROVIDERS) {
472
541
  const envKey = meta.envVar ? process.env[meta.envVar]?.trim() : undefined;
@@ -524,7 +593,7 @@ export function registerWebSearchConfigCommand(pi: ExtensionAPI): void {
524
593
  return;
525
594
  }
526
595
 
527
- const activeProvider = current.provider ?? DEFAULT_PROVIDER_NAME;
596
+ const activeProvider = resolveActiveProviderName(current).name;
528
597
  const orderedMetas = [
529
598
  ...PROVIDERS.filter((p) => p.name === activeProvider),
530
599
  ...PROVIDERS.filter((p) => p.name !== activeProvider),