# Configuration, credentials and data handling

For an overview, see the [README](../README.md).

## Classifier API

Optional classification adds judgments to `effort: "thorough"` calls. Fast web search can use a separate off-topic fallback check.

- **Rank:** favor relevant, self-contained excerpts and penalize off-topic results.
- **Filter:** suppress confidently flagged prompt injection, phishing, or harmful content.
- **Check coverage:** judge whether the retrieved evidence is enough to answer the query.

### Architecture and model support

`Retrieval → Pi classifier API → ranking/filtering policy → cited results`

The classifier receives the query and candidate titles, URLs, and excerpts as state, plus typed boolean and choice questions. It returns probabilities; code applies weights and thresholds. Pi owns the catalog, authentication, and `classify()`. This package pins one exact `provider`/`model`.

| Classifier | Support |
| --- | --- |
| **Jev** via TypeSafe, Vercel AI Gateway, or OpenRouter | Available now; reuses Pi authentication. |
| **Any Pi classifier** including llama.cpp | Pin its exact `provider`/`model`. |
| **OpenAI Decisions and other decision models** | Supported when registered as a classifier in Pi; pin the exact provider/model. |

The provider-independent boundary makes other classifiers possible without rewriting retrieval or ranking. Pin any registered Pi classifier with `/web-search classifier`.

### Try Jev with your existing Pi login

For OpenRouter:

1. Run `/login openrouter` **only if Pi isn't already authenticated**.
2. Run `/web-search classifier` and pick `openrouter/~typesafe/jev-latest`, or `/web-search classifier openrouter/~typesafe/jev-latest`.
3. In `/web-search`, turn on Multi-source, or merge `{"research":{"enabled":true}}` into `web-search.json`.
4. Ask: “Use search with effort thorough to search the web for AbortSignal.timeout.”

| Use | Setup command | Default model |
| --- | --- | --- |
| TypeSafe | `/web-search classifier typesafe/jev-latest` | `jev-latest` |
| Vercel AI Gateway | `/web-search classifier vercel-ai-gateway/typesafe-ai/jev` | `typesafe-ai/jev` |
| OpenRouter | `/web-search classifier openrouter/~typesafe/jev-latest` | `~typesafe/jev-latest` |
| OpenCode | `/web-search classifier opencode/jev-1.13` | `jev-1.13` |
| OpenAI Decisions | `/web-search classifier vercel-ai-gateway/openai/gpt-6-luna-decisions` | `openai/gpt-6-luna-decisions` |
| Cloudflare Workers AI | `/web-search classifier` and pick a listed Clef/Jev model | catalog |

`/web-search classifier` lists every classifier Pi currently registers, plus **None**. Classifiers do not appear in `/model`; this picker is the search-specific pin. Pinning enables judgment; turn on Multi-source separately for thorough search. Settings are read on the next search. **No second API key is needed.** Pi reuses its stored, environment, runtime, or model authentication. If needed, use Pi's `/login` for that provider.

`/web-search classifier none` disables judgment; search stays on. Hosted classification is billed to the pinned account.

Classification is off by default. When enabled without an explicit provider/model pair, it uses **Jev** (`vercel-ai-gateway/typesafe-ai/jev`). Other Pi classifiers can be pinned explicitly. Failures keep retrieved evidence with warnings. Hosted classifiers receive excerpts before output clipping; safety judgments are not a security boundary. See [all settings and limits](research.md).

### Read more without another network request

Searches return bounded previews and a session-local `resultId` when evidence can be stored. The bare ID lists saved results. Each hit has a full ref such as `<resultId>:1` that reads its stored passage.

```js
const index = await tools.search({ ref: "<returned handle>" });
text(index);
const passage = await tools.search({ ref: "<returned handle>:1", find: "timeout" });
text(passage);
```

Refs are one-based on the wire (`<resultId>:1` is the first stored result). Omit `find` and use `cursor` to continue a paginated read. Handles expire after 10 idle minutes (successful reads refresh this, up to a 60-minute maximum), eviction, shutdown, or reload. Nothing is written to disk. Stored evidence is bounded and may already have been truncated by the provider; it is **not guaranteed full-page content**. Direct callers can copy the returned `search({ref, cursor})` continuation call; codemode is not required. See [efficiency and limits](efficiency.md).

### Code qualifiers

`repo:<owner/name>` and `language:<name>` are the documented common subset. On grep.app and Sourcegraph, these are extracted into filters; quote qualifier values containing spaces. The first nonempty `repo:` value is used, and repeated languages are deduplicated. **grep.app language filtering is unreliable** and always adds a warning when used; avoid it for a first search, and treat zero hits as inconclusive.

Other qualifiers are provider-dependent: grep.app leaves `path:`, `filename:`, and similar syntax in the literal pattern, while GitHub receives the original query unchanged and interprets its own syntax. A zero-hit warning suggests possible remedies, not a confirmed cause or proof that code does not exist. grep.app and public Sourcegraph do not index every GitHub repository; `repo:facebook/react` often misses on those sources.

## Configuration

The config path is `<agent-dir>/web-search.json`, normally `~/.pi/agent/web-search.json`. `PI_WEB_SEARCH_CONFIG` overrides this path. `PI_CODING_AGENT_DIR` changes Pi's agent directory.

The extension does not automatically read project `.pi/web-search.json` or merge Pi's `settings.json`. Project-local installation does not change the config location.

A missing file uses these defaults:

```json
{
  "web": { "provider": "exa", "fallback": ["parallel"] },
  "code": { "provider": "grep", "fallback": ["sourcegraph", "github"] },
  "research": { "enabled": false },
  "fetch": { "jinaFallback": true },
  "brave": { "mode": "context" },
  "timeoutMs": 20000,
  "maxResults": 8
}
```

All fields are optional. Merge changes into the existing file. Network operations read config each time; ref reads stay local even when config is malformed.

- `web` accepts `exa`, `parallel`, and `brave`. `code` accepts `grep`, `sourcegraph`, `github`, and `context7`.
- `brave.mode` selects `context` or `web`. `fetch.jinaFallback` controls fallback from direct URL reading to Jina Reader.
- `maxResults` truncates to an integer, then clamps to **1–20**. It limits provider requests and the returned preview count per query or URL call. Requested URL extracts are prioritized; additional admitted evidence is available through `search({ref})`. Providers may return fewer results or ignore the requested limit.
- `timeoutMs` truncates to integer milliseconds. Positive values have a **1,000 ms minimum**. Nonpositive values use **20,000 ms**. These numeric adjustments emit no warnings.
- Invalid JSON, unknown fields/providers, and malformed blocks produce `invalid_config`. Wrong-family providers trigger warnings and defaults or removal. Some invalid classifier values trigger defaults with warnings. Only literal `true` enables `classifier.enabled`.

See the [configuration resolver](../src/providers/config.ts) for validation details.

### Optional off-topic fallback

To let fast web search try the next configured provider when the current response is off-topic, merge these settings into `web-search.json`:

```json
{
  "web": { "fallbackOnOffTopic": true },
  "classifier": { "provider": "vercel-ai-gateway", "model": "typesafe-ai/jev" }
}
```

The feature is off by default and requires the calibrated `vercel-ai-gateway/typesafe-ai/jev` classifier through Pi authentication. A check sends the query and up to ten result titles, URLs, and excerpts to this billed classifier. A classifier failure or timeout keeps the current response with a warning. If fallback yields no usable response, the first off-topic response is returned with warnings. Code searches, URL reads, and ref reads make no off-topic classifier calls. Selecting **None** under `/web-search classifier` or switching to a different classifier disables fast off-topic fallback.

### Optional thorough search and Jev

1. Run `/web-search` to identify the config path.
2. Merge `{"research":{"enabled":true}}` into that file.

`effort: "thorough"` sends the same query concurrently to the eligible sources in `scope`. Fan-out is bounded: at most **two actual transports per family** in configured order, and at most four for one query with `both`. A batch runs at most six transports at a time. `fallback: []` does not exclude eligible defaults. It does not check agreement or initiate further searches. `scope: "both"` defaults to thorough; explicit `effort: "fast"` with `both` is rejected, and `research.enabled` must be true. Fast calls never fan out deliberately.

Jev requires a separate opt-in. Anonymous retrieval needs no classifier credentials. See [classifier setup](research.md#enable-external-judgment), [tuning](research.md#all-classifier-settings), and [failure behavior](research.md#outcomes-and-limits).

## Credentials

Exa MCP, Parallel MCP, grep.app, and Sourcegraph need no search key. Jina Reader is a keyless fallback for URL extraction. Brave requires its own key. Anonymous Parallel has lower server-controlled rate limits. A Parallel key is optional.

Search credentials use the first nonblank environment alias before `<agent-dir>/auth.json`. GitHub then tries an existing `gh auth login` token.

| Stored ID | Environment aliases, highest precedence first | Behavior |
| --- | --- | --- |
| `exa` | `EXA_API_KEY` | Selects REST instead of keyless MCP. |
| `parallel` | `PARALLEL_API_KEY` | Adds a Bearer header for higher limits. |
| `github` | `GITHUB_TOKEN`, `GH_TOKEN` | Requires a token. Returns only verified public results. |
| `brave` | `BRAVE_API_KEY`, `BRAVE_SEARCH_API_KEY` | Requires a Brave Search key. |
| `context7` | `CONTEXT7_API_KEY` | Optional key for higher Context7 limits. |

- Set environment variables **before starting Pi**. Exports in another shell cannot change a running Pi process. Restart Pi with the changed environment.
- The extension resolves stored retrieval keys on each operation.

Merge this entry into existing `auth.json` without replacing other credentials:

```json
{ "parallel": { "type": "api_key", "key": "<your-api-key>" } }
```

- Replace the placeholder privately.
- Exclude auth files from version control.
- Use narrowly scoped keys/tokens.

The [retrieval credential resolver](../src/env.ts) reads literal `.key` strings, not shell commands, embedded environment references, or OAuth refresh credentials. Unreadable/malformed auth means no stored key.

`/web-search provider` adds or modifies a retrieval key in `auth.json` and shows where to create one. Keys are never command arguments, never written to `web-search.json`, and never displayed after you type them. Environment aliases still win over the stored value.

Pi supplies optional host peers. This package does not install another Pi copy. See the [npm advisory notes](release-validation.md#npm-advisory-and-host-dependencies).

Pi alone resolves classifier authentication at judgment time. Jev needs no separate key.

Each provider controls quotas and billing. Keys do not guarantee quota or price changes. Additional sources do not guarantee results or availability.

`/web-search` shows an authentication snapshot, not a live key-validity test. It never displays keys.

### Optional Brave search

Run `/web-search provider brave` to store a key privately, then merge this into `web-search.json`:

```json
{ "web": { "provider": "brave", "fallback": ["exa", "parallel"] } }
```

Brave defaults to LLM Context and returns passages from cited pages. Set `"brave": {"mode":"web"}` to use the standard Web Search endpoint and its shorter snippets. Each mode validates its query length before sending it.

### Context7 documentation

Select `context7` in `code.provider` or `code.fallback` to search documentation using the full query. To select an exact library and version, use `search({ query: "middleware API library:/vercel/next.js@v15", scope: "code" })`. An explicit library qualifier routes the code portion of the query to Context7 even outside the configured chain. Remove the qualifier and keep Context7 out of the code chain to use other code providers.

## Provider behavior and limits

- Default chains: **Exa → Parallel** and **grep.app → Sourcegraph → GitHub**.
- Keyless Exa uses native domain and publication-date filters on filtered calls. Anonymous Parallel uses site hints and applies domain filters locally. It warns when it cannot apply recency.
- Empty results and retryable failures continue through the configured [provider chain](../src/providers/index.ts). An empty provider is named in the warnings.
- Results contain links and excerpts, not guaranteed full pages. Exact duplicate evidence is collapsed, while distinct passages and code anchors remain. Search snippets show up to 400 characters of query-relevant evidence in both outputs. The shared budget is 8,000 characters per output path, including batches. Oversized citations are omitted whole with a notice, never shortened. Stored passages can be read in bounded windows with refs and cursors. See [structured output](../src/format.ts).
- Direct HTTP retrieval has bounded 30-second session reuse and in-flight deduplication. Rate-limited providers enter a short cooldown. See [efficiency and limits](efficiency.md).

## Timeouts, fallback, and errors

Retrieval and judgment share a default **20-second** budget. Cleanup can take longer. Jev failures return unjudged evidence with warnings. If the deadline expires during optional judgment or off-topic fallback, the tool keeps the evidence it already retrieved. Caller cancellation stops the search.

Check warnings and the provider settings under `/web-search`.

## Data handling

Search providers receive the queries routed to them. A `library:` qualifier sends the code query to Context7 even when it is outside the configured chain. Remove the qualifier and keep Context7 out of the code chain to avoid sending it. Optional Jev receives the query and candidate titles, URLs, and excerpts. Fast off-topic fallback sends at most ten excerpts of up to 400 characters each, within the classifier state limit.

URL reading sends requests from your machine to each public URL. The tool validates redirect targets and blocks private and local network addresses. The download and decompression limit is 5 MiB. PDFs are not extracted. Eligible failures can send the original URL to Jina Reader. Set `fetch.jinaFallback` to `false` to keep URL reading direct. GitHub requests may use GitHub credentials for public repository metadata and limits.

Retrieved content is untrusted. Jev is not a prompt-injection firewall or truth guarantee.

The extension does not send workspace files or session history as search payloads. Pi can retain tool calls in session history.

Queries, URLs, errors, and excerpts can contain sensitive text.
