diff --git a/README.md b/README.md
index 4ebcc67b..f4e02b55 100644
--- a/README.md
+++ b/README.md
@@ -67,6 +67,7 @@ Codemode is a Bun workspace. It was called runline through 0.45; see [Migrate fr
| [`packages/codemode-powershell`](packages/codemode-powershell) | The `powershell` plugin as a package, published as `@shiftlabs/codemode-powershell` |
| [`packages/codemode-duckdb`](packages/codemode-duckdb) | The `duckdb` plugin as a package, published as `@shiftlabs/codemode-duckdb` |
| [`packages/codemode-node`](packages/codemode-node) | The `node` plugin as a package, published as `@shiftlabs/codemode-node` |
+| [`packages/codemode-websearch`](packages/codemode-websearch) | The `websearch` plugin as a package, published as `@shiftlabs/codemode-websearch` |
| [`packages/package-tests`](packages/package-tests) | What the tests of those packages share. Not published |
| [`packages/runline`](packages/runline) | The `runline` package on npm, which forwards to codemode until 0.48.0 |
diff --git a/biome.json b/biome.json
index 682f9c13..13ec75de 100644
--- a/biome.json
+++ b/biome.json
@@ -134,7 +134,6 @@
"!packages/codemode-plugins/oura",
"!packages/codemode-plugins/paddle",
"!packages/codemode-plugins/pagerduty",
- "!packages/codemode-plugins/parallel",
"!packages/codemode-plugins/paypal",
"!packages/codemode-plugins/peekalink",
"!packages/codemode-plugins/phantombuster",
diff --git a/bun.lock b/bun.lock
index 16f1c613..5a6d3fc1 100644
--- a/bun.lock
+++ b/bun.lock
@@ -133,6 +133,21 @@
"@shiftlabs/codemode": ">0.46.0",
},
},
+ "packages/codemode-websearch": {
+ "name": "@shiftlabs/codemode-websearch",
+ "version": "0.1.0",
+ "devDependencies": {
+ "@shiftlabs/codemode": "workspace:*",
+ "@types/bun": "^1.2.17",
+ "@types/node": "^25.5.0",
+ "typebox": "^1.1.35",
+ "typescript": "^5.8.0",
+ },
+ "peerDependencies": {
+ "@shiftlabs/codemode": ">0.46.0",
+ "typebox": "*",
+ },
+ },
"packages/package-tests": {
"name": "codemode-package-tests",
"version": "0.0.0",
@@ -276,6 +291,8 @@
"@shiftlabs/codemode-powershell": ["@shiftlabs/codemode-powershell@workspace:packages/codemode-powershell"],
+ "@shiftlabs/codemode-websearch": ["@shiftlabs/codemode-websearch@workspace:packages/codemode-websearch"],
+
"@types/bun": ["@types/bun@1.3.12", "", { "dependencies": { "bun-types": "1.3.12" } }, "sha512-DBv81elK+/VSwXHDlnH3Qduw+KxkTIWi7TXkAeh24zpi5l0B2kUg9Ga3tb4nJaPcOFswflgi/yAvMVBPrxMB+A=="],
"@types/node": ["@types/node@25.6.0", "", { "dependencies": { "undici-types": "~7.19.0" } }, "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ=="],
diff --git a/docs/bundled-plugins.md b/docs/bundled-plugins.md
index ca03ad7c..832f11b6 100644
--- a/docs/bundled-plugins.md
+++ b/docs/bundled-plugins.md
@@ -2,7 +2,7 @@
Codemode ships with plugins for SaaS, DevOps, productivity, and image-generation APIs. They are part of the `codemode` package and need no installation.
-Host capabilities are separate packages to install: [`codemode-node`](../packages/codemode-node/README.md) for Node.js scripts, [`codemode-bash`](../packages/codemode-bash/README.md) and [`codemode-powershell`](../packages/codemode-powershell/README.md) for commands, and [`codemode-duckdb`](../packages/codemode-duckdb/README.md) for SQL.
+Host capabilities are separate packages to install: [`codemode-node`](../packages/codemode-node/README.md) for Node.js scripts, [`codemode-bash`](../packages/codemode-bash/README.md) and [`codemode-powershell`](../packages/codemode-powershell/README.md) for commands, and [`codemode-duckdb`](../packages/codemode-duckdb/README.md) for SQL. Web search across providers is the [`codemode-websearch`](../packages/codemode-websearch/README.md) package.
A bundled plugin becomes available to `codemode exec` once it has a connection. The last column lists each required connection field and, in parentheses, the environment variable that can supply it:
@@ -159,7 +159,6 @@ A plugin that uses OAuth shows the `codemode auth` command that connects it. See
|
**oura** | 4 | profile, summary | `accessToken` (`OURA_ACCESS_TOKEN`) |
|
**paddle** | 9 | coupon, payment, plan, product, user | `vendorId` (`PADDLE_VENDOR_ID`), `vendorAuthCode` (`PADDLE_VENDOR_AUTH_CODE`) |
|
**pagerduty** | 9 | incident, incidentNote, logEntry, user | `apiToken` (`PAGERDUTY_API_TOKEN`) |
-|
**parallel** | 1 | search | `apiKey` (`PARALLEL_API_KEY`) |
|
**paypal** | 4 | payout, payoutItem | `clientId` (`PAYPAL_CLIENT_ID`), `secret` (`PAYPAL_SECRET`) |
|
**peekalink** | 2 | link | `apiKey` (`PEEKALINK_API_KEY`) |
|
**phantombuster** | 5 | agent | `apiKey` (`PHANTOMBUSTER_API_KEY`) |
diff --git a/docs/migrating-from-runline.md b/docs/migrating-from-runline.md
index e33a6f08..9791e95e 100644
--- a/docs/migrating-from-runline.md
+++ b/docs/migrating-from-runline.md
@@ -89,6 +89,20 @@ codemode install npm:@shiftlabs/codemode-node
- The actions that each wrapped one function, such as `node.fs.readFile`, `node.path.join`, and `node.fetch`, are gone. Run a script that calls the function instead: `node.run({ command: 'console.log(require("node:fs").readFileSync("notes.txt", "utf8"))' })`.
- `node.process.exec` and `node.process.execFile` are gone. Run commands with `bash.run` from [`codemode-bash`](../packages/codemode-bash/README.md) or `powershell.run` from [`codemode-powershell`](../packages/codemode-powershell/README.md).
+## Install web search
+
+After 0.46.0 the bundled `parallel` plugin is gone. Web search is a package that searches through Parallel and eleven other providers:
+
+```bash
+codemode install npm:@shiftlabs/codemode-websearch
+```
+
+- `PARALLEL_API_KEY` keeps working. A `parallel` connection belongs to the removed plugin: add the key again with `codemode connection add websearch --plugin websearch --set parallelApiKey=$PARALLEL_API_KEY`.
+- `parallel.search({ objective, search_queries })` becomes `websearch.query({ query })`, which takes one query and answers `{ provider, results }`. Each result has `title`, `url`, and `content`, where `parallel.search` answered `excerpts`.
+- `processor` and `max_chars_per_result` have no counterpart. `max_results` is `numResults`.
+
+See [`codemode-websearch`](../packages/codemode-websearch/README.md).
+
## Understand what did not move
`pi-runline`, the Pi extension, keeps its name and lives at [Michaelliv/pi-runline](https://github.com/Michaelliv/pi-runline). It runs runline 0.45 and reads only `.runline` folders, so keep a project's folder named `.runline` while you use the project from Pi.
diff --git a/packages/codemode-plugins/icons/parallel.svg b/packages/codemode-plugins/icons/parallel.svg
deleted file mode 100644
index 248ec7f6..00000000
--- a/packages/codemode-plugins/icons/parallel.svg
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/packages/codemode-plugins/parallel/src/credentials.ts b/packages/codemode-plugins/parallel/src/credentials.ts
deleted file mode 100644
index bfbf31e7..00000000
--- a/packages/codemode-plugins/parallel/src/credentials.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { httpsBase, staticCredential } from "@shiftlabs/codemode";
-
-export const DEFAULT_BASE = "https://api.parallel.ai";
-
-/**
- * An API key, sent as the x-api-key header to the configured Parallel.ai
- * API base (api.parallel.ai unless overridden). The base URL is public
- * config and must be HTTPS.
- */
-export const parallelCredential = staticCredential({
- id: "parallel",
- auth: { kind: "apiKey", header: "x-api-key" },
- local: { secret: "apiKey" },
- targets: (config) => ({
- api: {
- baseUrl: httpsBase(config.baseUrl ?? DEFAULT_BASE, "v1beta/"),
- methods: ["POST"],
- },
- }),
-});
diff --git a/packages/codemode-plugins/parallel/src/index.ts b/packages/codemode-plugins/parallel/src/index.ts
deleted file mode 100644
index 5e0a9ddc..00000000
--- a/packages/codemode-plugins/parallel/src/index.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * Parallel.ai web search/research plugin for codemode.
- *
- * Wraps the Parallel Search API (https://api.parallel.ai/v1beta/search): give it
- * an objective and/or explicit queries and it returns ranked, freshly-fetched
- * web results with extracted excerpts — built for agents that need to ground an
- * answer in the live web rather than training data.
- *
- * Auth: a Parallel API key (header `x-api-key`), via the `apiKey` connection
- * field (env `PARALLEL_API_KEY`).
- *
- * await parallel.search({ objective: "latest Israel construction permit reform" })
- * await parallel.search({ search_queries: ["tel aviv office vacancy rate 2026"], processor: "pro" })
- */
-import { credentialJson, type CodemodePluginAPI } from "@shiftlabs/codemode";
-import { DEFAULT_BASE, parallelCredential } from "./credentials.js";
-
-const NAME = "parallel";
-
-interface SearchResult {
- url?: string;
- title?: string;
- excerpts?: string[];
-}
-
-interface SearchAnswer {
- search_id?: string;
- results?: SearchResult[];
- warnings?: unknown;
-}
-
-export default function parallel(rl: CodemodePluginAPI): void {
- rl.setName(NAME);
- rl.setVersion("0.1.0");
- rl.setCredential(parallelCredential);
-
- rl.setConnectionSchema({
- apiKey: {
- type: "string",
- required: true,
- env: "PARALLEL_API_KEY",
- description:
- "Parallel.ai API key (sent as the x-api-key header). Store only in secrets.",
- },
- baseUrl: {
- type: "string",
- required: false,
- env: "PARALLEL_API_BASE",
- default: DEFAULT_BASE,
- description: "Parallel.ai API base URL.",
- },
- });
-
- rl.registerAction("search", {
- access: "read",
- description:
- "Search the live web with Parallel.ai and get ranked results with extracted excerpts. Use this to ground answers in current web content (news, prices, regulations, company info) instead of stale knowledge. Provide an `objective` (natural-language goal) and/or explicit `search_queries`.",
- inputSchema: {
- objective: {
- type: "string",
- required: false,
- description:
- "Natural-language description of what you're trying to find. Recommended; can be used with or instead of search_queries.",
- },
- search_queries: {
- type: "array",
- required: false,
- description:
- 'Optional explicit query strings to run (e.g. ["x vacancy rate 2026"]). Provide objective and/or this.',
- },
- processor: {
- type: "string",
- required: false,
- default: "base",
- description: "base (fast, default) or pro (deeper, slower/costlier).",
- },
- max_results: {
- type: "number",
- required: false,
- default: 5,
- description: "Max results to return (default 5).",
- },
- max_chars_per_result: {
- type: "number",
- required: false,
- description: "Optional cap on extracted characters per result.",
- },
- },
- async execute(input, ctx) {
- const p = (input ?? {}) as Record;
- const objective =
- typeof p.objective === "string" ? p.objective.trim() : "";
- const queries = Array.isArray(p.search_queries)
- ? p.search_queries.map((q) => String(q)).filter((q) => q.trim())
- : [];
- if (!objective && !queries.length) {
- throw new Error("Provide objective and/or search_queries");
- }
-
- const body: Record = {
- processor: String(p.processor || "base"),
- max_results:
- Number(p.max_results) > 0 ? Math.floor(Number(p.max_results)) : 5,
- };
- if (objective) body.objective = objective;
- if (queries.length) body.search_queries = queries;
- if (Number(p.max_chars_per_result) > 0) {
- body.max_chars_per_result = Math.floor(Number(p.max_chars_per_result));
- }
-
- const data = await credentialJson(
- ctx,
- parallelCredential,
- NAME,
- {
- target: "api",
- path: "search",
- method: "POST",
- json: body,
- },
- );
- const results = (data.results ?? []).map((r) => ({
- url: r.url,
- title: r.title,
- excerpts: r.excerpts ?? [],
- }));
- return {
- searchId: data.search_id,
- count: results.length,
- results,
- warnings: data.warnings ?? undefined,
- source: "parallel.search",
- };
- },
- });
-}
diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md
new file mode 100644
index 00000000..40e6f11c
--- /dev/null
+++ b/packages/codemode-websearch/README.md
@@ -0,0 +1,177 @@
+# codemode-websearch
+
+A [codemode](../../README.md) package with one plugin, `websearch`, whose one action searches the web through the search provider you have a key for.
+
+Code calls `websearch.query` the same way whichever provider answers, and gets results in one shape. Code never names a provider: the connection chooses it, so changing provider changes a key or a setting, not the code.
+
+## Install
+
+Install the package and set the key of one provider:
+
+```bash
+codemode install npm:@shiftlabs/codemode-websearch
+export BRAVE_API_KEY=...
+```
+
+It needs a codemode newer than 0.46.0.
+
+## Search
+
+`websearch.query` returns the results and the provider that gave them:
+
+```bash
+codemode exec 'return await websearch.query({ query: "duckdb 1.4 release notes", numResults: 2 })'
+```
+
+```json
+{
+ "provider": "brave",
+ "results": [
+ {
+ "title": "Announcing DuckDB 1.4.0",
+ "url": "https://duckdb.org/2025/09/16/announcing-duckdb-140.html",
+ "content": "We are releasing DuckDB version 1.4.0, codenamed Andium...",
+ "publishedDate": "2025-09-16T00:00:00"
+ }
+ ]
+}
+```
+
+| Input | Meaning |
+|---|---|
+| `query` | What to search for |
+| `numResults` | The most results to return. The default is 10 |
+| `country` | A country to prefer results from |
+| `language` | A language to prefer results in |
+| `includeDomains` | Return results from these sites only |
+| `excludeDomains` | Leave results from these sites out |
+| `freshness` | Return only pages published this recently |
+
+Each input has one form, and a value in another form is refused before any request:
+
+| Input | Form | Example |
+|---|---|---|
+| `query` | Text of 1 to 400 characters | `"duckdb window functions"` |
+| `numResults` | A whole number from 1 to 20 | `10` |
+| `country` | An ISO 3166-1 alpha-2 code | `"DE"` |
+| `language` | An ISO 639-1 code | `"de"` |
+| `includeDomains`, `excludeDomains` | 1 to 20 hostnames, without `https://` or a path | `["duckdb.org"]` |
+| `freshness` | `"day"`, `"week"`, `"month"`, or `"year"` | `"week"` |
+
+A code or a hostname means the same in upper and lower case. Codemode turns each value into what the provider's API takes: `"DE"` reaches Parallel as `de`, Tavily as `germany`, and Brave as `DE`. The inputs are the same for every provider, and a search names no parameter of a provider's own.
+
+| Result field | Contents |
+|---|---|
+| `title`, `url` | The page |
+| `content` | The text the provider returned for the page: a snippet, excerpts, or the page itself |
+| `publishedDate`, `author`, `sourceType` | Present when the provider gives them |
+
+## Choose a provider
+
+The connection chooses the provider, and a search has no input for it. A search goes to the connection's `provider` when it names one:
+
+```bash
+codemode connection add websearch --plugin websearch --set provider=tavily
+```
+
+Without one, a search goes to the first provider in this table that has a key and can apply the search's filters:
+
+| Provider | Key | `country` | `language` | Filters |
+|---|---|---|---|---|
+| `parallel` | `PARALLEL_API_KEY` | Yes | No | Yes |
+| `brave` | `BRAVE_API_KEY` | Yes | Yes | Yes |
+| `exa` | `EXA_API_KEY` | Yes | No | Yes |
+| `you` | `YOU_API_KEY` | Yes | Yes | Yes |
+| `tavily` | `TAVILY_API_KEY` | Yes | Yes | Yes |
+| `firecrawl` | `FIRECRAWL_API_KEY` | Yes | No | Yes |
+| `jina` | `JINA_API_KEY` | Yes | Yes | No |
+| `linkup` | `LINKUP_API_KEY` | No | No | Yes |
+| `valyu` | `VALYU_API_KEY` | Yes | No | Yes |
+| `perplexity` | `PERPLEXITY_API_KEY` | Yes | Yes | Yes |
+| `serper` | `SERPER_API_KEY` | Yes | Yes | Yes |
+| `serpapi` | `SERPAPI_API_KEY` | Yes | Yes | Yes |
+
+The result's `provider` says which one answered.
+
+## Narrow a search
+
+`includeDomains`, `excludeDomains`, and `freshness` are filters. Every result meets them, or the call is refused. A connection that names no provider sends a filtered search to a provider that applies the filter:
+
+```js
+await websearch.query({
+ query: "window functions",
+ includeDomains: ["duckdb.org", "postgresql.org"],
+ freshness: "year",
+});
+
+await websearch.query({ query: "duckdb benchmarks", excludeDomains: ["medium.com"] });
+```
+
+Set sites to search or sites to leave out, not both.
+
+`country` and `language` are preferences. A provider that cannot localize searches without them, as the table above shows. Brave, You.com, and Valyu localize for 36 or 37 countries, and a search for another country reaches them without one.
+
+## Configure the connection
+
+Add a connection to keep keys in codemode, or to choose the provider. Every field is optional:
+
+```bash
+codemode connection add websearch --plugin websearch --set exaApiKey=$EXA_API_KEY --set tavilyApiKey=$TAVILY_API_KEY --set provider=tavily
+```
+
+| Field | Meaning |
+|---|---|
+| `provider` | The provider every search goes to. The default is the first with a key that can apply the search's filters |
+| `ApiKey` | The provider's key, such as `braveApiKey`. The default is its environment variable |
+| `firecrawlUrl` | A Firecrawl of your own, by its HTTPS address. The default is `FIRECRAWL_URL`, then `https://api.firecrawl.dev` |
+
+Each key is declared with the one host that may receive it. A search through one provider sends no other provider's key, and codemode refuses a request to any other host.
+
+## Add a provider
+
+A host that embeds codemode builds the plugin from its own list of providers. A provider is its key's place in a request, the one HTTPS address that may receive the key, the parameters a search becomes, and how its answer reads as results:
+
+```typescript
+import { Codemode } from "@shiftlabs/codemode";
+import { PROVIDERS, type SearchProvider, websearch } from "@shiftlabs/codemode-websearch";
+
+const acme: SearchProvider = {
+ name: "acme",
+ env: "ACME_SEARCH_KEY",
+ key: { header: "X-Acme-Key" },
+ baseUrl: "https://search.acme.example/api/",
+ method: "GET",
+ path: "find",
+ params: ({ query, numResults }) => ({ q: query, n: numResults }),
+ results: (answer) =>
+ (answer as { hits: Array<{ name: string; href: string; text: string }> }).hits.map(
+ (hit) => ({ title: hit.name, url: hit.href, content: hit.text }),
+ ),
+};
+
+const codemode = Codemode.create({ plugins: [websearch([acme, ...PROVIDERS])] });
+```
+
+The list's order is the order a provider is chosen in. Parameters go in the query of a `GET` and the JSON body of a `POST`. The package is TypeScript source, so the host imports it with a runtime that runs TypeScript, such as Bun.
+
+## Handle failures
+
+| Outcome | Result |
+|---|---|
+| No provider has a key | The call rejects and names the environment variables |
+| The connection's provider has no key | The call rejects and names its environment variable |
+| The connection's provider, or every provider with a key, cannot apply a filter | The call rejects and names the filter to search without |
+| The provider refuses the request | The call rejects with `websearch.: request failed (HTTP )` |
+| The provider answers without results | Returns `results: []` |
+
+A provider's error text is not included in the message, because it can repeat the key it was sent.
+
+## Understand the limits
+
+- Results are what the provider returns. Their length and freshness differ from provider to provider.
+- Jina applies no filter. A filtered search goes to another provider with a key, and is refused when Jina is the connection's provider or holds the only key.
+- Brave, Serper, and SerpAPI filter by site with `site:` operators added to the query. Brave takes a query of 600 characters, so a long query with many long hostnames can pass it and be refused.
+- `freshness` reaches back 1, 7, 31, or 365 days, by the date a provider holds for a page.
+- Serper and SerpAPI can return a first result with an empty `url`: what Google's results page says about the thing searched for.
+- SerpAPI takes no number of results. It answers one page of Google's results, of which the first `numResults` are returned.
+- A request to a provider is not ended when the run ends. It ends by itself within 60 seconds.
diff --git a/packages/codemode-websearch/package.json b/packages/codemode-websearch/package.json
new file mode 100644
index 00000000..b1ac2f7e
--- /dev/null
+++ b/packages/codemode-websearch/package.json
@@ -0,0 +1,51 @@
+{
+ "name": "@shiftlabs/codemode-websearch",
+ "version": "0.1.0",
+ "description": "Search the web from codemode through one action, whichever search provider you have a key for",
+ "type": "module",
+ "keywords": [
+ "codemode-plugin",
+ "web-search",
+ "search",
+ "brave",
+ "exa",
+ "tavily",
+ "parallel",
+ "perplexity"
+ ],
+ "codemode": {
+ "plugins": [
+ "./src/index.ts"
+ ]
+ },
+ "files": [
+ "src",
+ "README.md"
+ ],
+ "scripts": {
+ "test": "bun test tests",
+ "typecheck": "tsc --noEmit -p ."
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/shift-labs-ai/codemode.git",
+ "directory": "packages/codemode-websearch"
+ },
+ "homepage": "https://github.com/shift-labs-ai/codemode/tree/main/packages/codemode-websearch#readme",
+ "bugs": {
+ "url": "https://github.com/shift-labs-ai/codemode/issues"
+ },
+ "license": "MIT",
+ "peerDependencies": {
+ "@shiftlabs/codemode": ">0.46.0",
+ "typebox": "*"
+ },
+ "devDependencies": {
+ "@shiftlabs/codemode": "workspace:*",
+ "@types/bun": "^1.2.17",
+ "@types/node": "^25.5.0",
+ "typebox": "^1.1.35",
+ "typescript": "^5.8.0"
+ },
+ "exports": "./src/index.ts"
+}
diff --git a/packages/codemode-websearch/src/codes.ts b/packages/codemode-websearch/src/codes.ts
new file mode 100644
index 00000000..a78f812a
--- /dev/null
+++ b/packages/codemode-websearch/src/codes.ts
@@ -0,0 +1,235 @@
+/**
+ * The codes each provider documents for a country or a language, as its
+ * reference lists them. A search states a country as an ISO 3166-1 alpha-2
+ * code and a language as an ISO 639-1 code; a provider is sent one only when
+ * its list has it.
+ */
+
+function codes(list: string): ReadonlySet {
+ return new Set(list.split(" "));
+}
+
+/** The countries Brave localizes for. */
+export const BRAVE_COUNTRIES = codes(
+ "AR AU AT BE BR CA CL DK FI FR DE GR HK IN ID IT JP KR MY MX NL NZ NO CN " +
+ "PL PT PH RU SA ZA ES SE CH TW TR GB US",
+);
+
+/** The countries You.com and Valyu localize for: the two publish the same list. */
+export const YOU_COUNTRIES = codes(
+ "AR AU AT BE BR CA CL DK FI FR DE HK IN ID IT JP KR MY MX NL NZ NO CN PL " +
+ "PT PH RU SA ZA ES SE CH TW TR GB US",
+);
+
+/** The languages Brave and You.com take as a plain two-letter code. */
+export const BRAVE_LANGUAGES = codes(
+ "ar eu bn bg ca hr cs da nl en et fi fr gl de el gu he hi hu is it ja kn " +
+ "ko lv lt ms ml mr nb pl pa ro ru sr sk sl es sv ta te th tr uk vi",
+);
+
+/** The languages Brave and You.com take only with a script or a region. */
+export const BRAVE_LANGUAGE_VARIANTS: Readonly> = {
+ zh: "zh-hans",
+ pt: "pt-br",
+ no: "nb",
+};
+
+/** The countries Google searches for (`gl`), which Serper, SerpAPI and Jina pass on. */
+export const GOOGLE_COUNTRIES = codes(
+ "AF AL DZ AS AD AO AI AQ AG AR AM AW AU AT AZ BS BH BD BB BY BE BZ BJ BM " +
+ "BT BO BA BW BV BR IO BN BG BF BI KH CM CA CV KY CF TD CL CN CX CC CO KM " +
+ "CG CD CK CR CI HR CU CY CZ DK DJ DM DO EC EG SV GQ ER EE ET FK FO FJ FI " +
+ "FR GF PF TF GA GM GE DE GH GI GR GL GD GP GU GT GG GN GW GY HT HM VA HN " +
+ "HK HU IS IN ID IR IQ IE IM IL IT JE JM JP JO KZ KE KI KP KR KW KG LA LV " +
+ "LB LS LR LY LI LT LU MO MK MG MW MY MV ML MT MH MQ MR MU YT MX FM MD MC " +
+ "MN ME MS MA MZ MM NA NR NP NL AN NC NZ NI NE NG NU NF MP NO OM PK PW PS " +
+ "PA PG PY PE PH PN PL PT PR QA RE RO RU RW SH KN LC PM VC WS SM ST SA SN " +
+ "RS SC SL SG SK SI SB SO ZA GS ES LK SD SR SJ SZ SE CH SY TW TJ TZ TH TL " +
+ "TG TK TO TT TN TR TM TC TV UG UA AE UK GB US UM UY UZ VU VE VN VG VI WF " +
+ "EH YE ZM ZW",
+);
+
+/** The languages Google takes as a two-letter code (`hl`). */
+export const GOOGLE_LANGUAGES = codes(
+ "af ak sq ws am ar hy az eu be bn bh bs br bg bt km ca ny co hr cs da nl " +
+ "en eo et ee fo tl fi fr fy gl ka de el kl gn gu ht ha iw he hi hu is ig " +
+ "id ia ga it ja jw kn kk rw rn kg ko ku ky lo la lv ln lt lg mk mg ms ml " +
+ "mt mv mi mr mo mn my ne no nn oc or om ps fa pl pt pa qu ro rm ru gd sr " +
+ "sh st tn sn sd si sk sl so es su sw sv tg ta tt te th ti to tr tk tw ug " +
+ "uk ur uz vu vi cy wo xh yi yo zu",
+);
+
+/** The languages Google takes only with a region. */
+export const GOOGLE_LANGUAGE_VARIANTS: Readonly> = {
+ zh: "zh-cn",
+};
+
+/** Tavily names a country in English, in lower case. These are the names it lists, by country code. */
+export const TAVILY_COUNTRIES: Readonly> = {
+ AD: "andorra",
+ AE: "united arab emirates",
+ AF: "afghanistan",
+ AL: "albania",
+ AM: "armenia",
+ AO: "angola",
+ AR: "argentina",
+ AT: "austria",
+ AU: "australia",
+ AZ: "azerbaijan",
+ BA: "bosnia and herzegovina",
+ BB: "barbados",
+ BD: "bangladesh",
+ BE: "belgium",
+ BF: "burkina faso",
+ BG: "bulgaria",
+ BH: "bahrain",
+ BI: "burundi",
+ BJ: "benin",
+ BN: "brunei",
+ BO: "bolivia",
+ BR: "brazil",
+ BS: "bahamas",
+ BT: "bhutan",
+ BW: "botswana",
+ BY: "belarus",
+ BZ: "belize",
+ CA: "canada",
+ CF: "central african republic",
+ CG: "congo",
+ CH: "switzerland",
+ CL: "chile",
+ CM: "cameroon",
+ CN: "china",
+ CO: "colombia",
+ CR: "costa rica",
+ CU: "cuba",
+ CV: "cape verde",
+ CY: "cyprus",
+ CZ: "czech republic",
+ DE: "germany",
+ DJ: "djibouti",
+ DK: "denmark",
+ DO: "dominican republic",
+ DZ: "algeria",
+ EC: "ecuador",
+ EE: "estonia",
+ EG: "egypt",
+ ER: "eritrea",
+ ES: "spain",
+ ET: "ethiopia",
+ FI: "finland",
+ FJ: "fiji",
+ FR: "france",
+ GA: "gabon",
+ GB: "united kingdom",
+ GE: "georgia",
+ GH: "ghana",
+ GM: "gambia",
+ GN: "guinea",
+ GQ: "equatorial guinea",
+ GR: "greece",
+ GT: "guatemala",
+ HN: "honduras",
+ HR: "croatia",
+ HT: "haiti",
+ HU: "hungary",
+ ID: "indonesia",
+ IE: "ireland",
+ IL: "israel",
+ IN: "india",
+ IQ: "iraq",
+ IR: "iran",
+ IS: "iceland",
+ IT: "italy",
+ JM: "jamaica",
+ JO: "jordan",
+ JP: "japan",
+ KE: "kenya",
+ KG: "kyrgyzstan",
+ KH: "cambodia",
+ KM: "comoros",
+ KP: "north korea",
+ KR: "south korea",
+ KW: "kuwait",
+ KZ: "kazakhstan",
+ LB: "lebanon",
+ LI: "liechtenstein",
+ LK: "sri lanka",
+ LR: "liberia",
+ LS: "lesotho",
+ LT: "lithuania",
+ LU: "luxembourg",
+ LV: "latvia",
+ LY: "libya",
+ MA: "morocco",
+ MC: "monaco",
+ MD: "moldova",
+ ME: "montenegro",
+ MG: "madagascar",
+ MK: "north macedonia",
+ ML: "mali",
+ MM: "myanmar",
+ MN: "mongolia",
+ MR: "mauritania",
+ MT: "malta",
+ MU: "mauritius",
+ MV: "maldives",
+ MW: "malawi",
+ MX: "mexico",
+ MY: "malaysia",
+ MZ: "mozambique",
+ NA: "namibia",
+ NE: "niger",
+ NG: "nigeria",
+ NI: "nicaragua",
+ NL: "netherlands",
+ NO: "norway",
+ NP: "nepal",
+ NZ: "new zealand",
+ OM: "oman",
+ PA: "panama",
+ PE: "peru",
+ PG: "papua new guinea",
+ PH: "philippines",
+ PK: "pakistan",
+ PL: "poland",
+ PT: "portugal",
+ PY: "paraguay",
+ QA: "qatar",
+ RO: "romania",
+ RS: "serbia",
+ RU: "russia",
+ RW: "rwanda",
+ SA: "saudi arabia",
+ SD: "sudan",
+ SE: "sweden",
+ SG: "singapore",
+ SI: "slovenia",
+ SK: "slovakia",
+ SN: "senegal",
+ SO: "somalia",
+ SS: "south sudan",
+ SV: "el salvador",
+ SY: "syria",
+ TD: "chad",
+ TG: "togo",
+ TH: "thailand",
+ TJ: "tajikistan",
+ TM: "turkmenistan",
+ TN: "tunisia",
+ TR: "turkey",
+ TT: "trinidad and tobago",
+ TW: "taiwan",
+ TZ: "tanzania",
+ UA: "ukraine",
+ UG: "uganda",
+ US: "united states",
+ UY: "uruguay",
+ UZ: "uzbekistan",
+ VE: "venezuela",
+ VN: "vietnam",
+ YE: "yemen",
+ ZA: "south africa",
+ ZM: "zambia",
+ ZW: "zimbabwe",
+};
diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts
new file mode 100644
index 00000000..b2fe1cc6
--- /dev/null
+++ b/packages/codemode-websearch/src/index.ts
@@ -0,0 +1,396 @@
+/**
+ * Web search for codemode: one action that searches the web through the
+ * provider the connection chooses, and answers results in one shape
+ * whichever provider that was. Code never names a provider.
+ *
+ * const { results } = await websearch.query({ query: "duckdb 1.4 release notes" })
+ *
+ * A connection holds a key per provider. Each key is declared with the one
+ * host that may receive it, so a search through one provider sends no other
+ * provider's key.
+ */
+
+import {
+ type CodemodePluginAPI,
+ type CredentialDeclaration,
+ type CredentialTarget,
+ credentialJson,
+ type PluginFunction,
+ staticCredential,
+} from "@shiftlabs/codemode";
+import { packageVersion } from "@shiftlabs/codemode/utils/cli";
+import * as t from "typebox";
+import {
+ type Freshness,
+ PROVIDERS,
+ type SearchProvider,
+ type SearchRequest,
+} from "./providers.js";
+
+export * from "./providers.js";
+
+const NAME = "websearch";
+const DEFAULT_RESULTS = 10;
+const MAX_RESULTS = 20;
+const MAX_DOMAINS = 20;
+/** The longest query every provider takes, with room for the sites a filter adds to it. */
+const MAX_QUERY = 400;
+/** A search that reads pages can take longer than the transport waits by default. */
+const TIMEOUT_MS = 60_000;
+/** How many days back each freshness reaches. */
+const FRESHNESS_DAYS: Record = {
+ day: 1,
+ week: 7,
+ month: 31,
+ year: 365,
+};
+/** The inputs that narrow a search. A search goes only to a provider that applies those it sets. */
+const FILTERS = ["includeDomains", "excludeDomains", "freshness"] as const;
+/** A hostname, such as `duckdb.org`: no scheme, path or spaces. */
+const DOMAIN = "^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$";
+
+/** The connection field that holds a provider's key. */
+function keyField(provider: SearchProvider): string {
+ return `${provider.name}ApiKey`;
+}
+
+/** Whether the connection holds a key for the provider. */
+function hasKey(
+ provider: SearchProvider,
+ config: Readonly>,
+): boolean {
+ return Boolean(config[keyField(provider)]);
+}
+
+/**
+ * One credential for every provider: a part per provider, each optional and
+ * each placed only on that provider's target, so a connection holds the keys
+ * it has and a key is sent to its own provider alone. A target is the
+ * provider's address, the method a search uses and the headers it carries.
+ */
+function credentialOf(providers: SearchProvider[]): CredentialDeclaration {
+ const names = providers.map((provider) => provider.name);
+ return staticCredential({
+ id: "codemodeWebsearch",
+ auth: {
+ kind: "static",
+ parts: names,
+ optionalParts: names,
+ placements: providers.map(({ name, key }) =>
+ "query" in key
+ ? { in: "query", part: name, name: key.query, targets: [name] }
+ : {
+ in: "header",
+ part: name,
+ name: key.header,
+ ...(key.prefix === undefined ? {} : { prefix: key.prefix }),
+ targets: [name],
+ },
+ ),
+ },
+ local: Object.fromEntries(
+ providers.map((provider) => [provider.name, keyField(provider)]),
+ ),
+ targets: (config) =>
+ Object.fromEntries(
+ providers.map(
+ ({ name, baseUrl, method, headers }): [string, CredentialTarget] => [
+ name,
+ {
+ baseUrl:
+ typeof baseUrl === "function" ? baseUrl(config) : baseUrl,
+ methods: [method],
+ ...(headers ? { allowedHeaders: Object.keys(headers) } : {}),
+ timeoutMs: TIMEOUT_MS,
+ },
+ ],
+ ),
+ ),
+ });
+}
+
+/**
+ * The filters of a search that a provider does not apply: those whose
+ * removal leaves the request the provider would send unchanged.
+ */
+function unapplied(provider: SearchProvider, search: SearchRequest): string[] {
+ const sent = JSON.stringify(provider.params(search));
+ return FILTERS.filter(
+ (filter) =>
+ search[filter] !== undefined &&
+ sent ===
+ JSON.stringify(
+ provider.params({
+ ...search,
+ [filter]: undefined,
+ ...(filter === "freshness" ? { publishedAfter: undefined } : {}),
+ }),
+ ),
+ );
+}
+
+/**
+ * The provider a search goes to. The connection decides, never the call:
+ * its `provider` when it names one, else the first provider it has a key
+ * for that applies the search's filters. A host that signs requests keeps
+ * the keys, so only a connection that signs for itself (`signsItself`) is
+ * asked to hold the key of the provider it names.
+ */
+function chosen(
+ providers: SearchProvider[],
+ config: Readonly>,
+ signsItself: boolean,
+ search: SearchRequest,
+): SearchProvider {
+ const name = config.provider;
+ if (name === undefined) {
+ const keyed = providers.filter((candidate) => hasKey(candidate, config));
+ if (!keyed.length)
+ throw new Error(
+ `${NAME}: no search provider has a key. Set one of ${providers.map((candidate) => candidate.env).join(", ")}, or the connection's "provider" when the host keeps the keys.`,
+ );
+ const able = keyed.find(
+ (candidate) => !unapplied(candidate, search).length,
+ );
+ if (able) return able;
+ const set = FILTERS.filter((filter) => search[filter] !== undefined);
+ throw new Error(
+ `${NAME}: no provider with a key can filter by ${set.join(" and ")}. Search without one of them.`,
+ );
+ }
+ const provider = providers.find((candidate) => candidate.name === name);
+ if (!provider)
+ throw new Error(
+ `${NAME}: the connection names the provider ${JSON.stringify(name)}. The providers are ${providers.map((candidate) => candidate.name).join(", ")}.`,
+ );
+ if (signsItself && !hasKey(provider, config))
+ throw new Error(
+ `${NAME}: no key for ${provider.name}, the connection's provider. Set ${provider.env}.`,
+ );
+ const refused = unapplied(provider, search);
+ if (refused.length)
+ throw new Error(
+ `${NAME}: ${provider.name}, the connection's provider, cannot filter by ${refused.join(" or ")}. Search without it.`,
+ );
+ return provider;
+}
+
+/** The codes that name something, by what they name. */
+const CODES = {
+ country: {
+ names: new Intl.DisplayNames(["en"], { type: "region", fallback: "none" }),
+ standard: "ISO 3166-1 alpha-2",
+ example: "US",
+ },
+ language: {
+ names: new Intl.DisplayNames(["en"], {
+ type: "language",
+ fallback: "none",
+ }),
+ standard: "ISO 639-1",
+ example: "en",
+ },
+};
+
+/** Refuse a code in the right form that names no country, or no language. */
+function checkCode(kind: keyof typeof CODES, code: string | undefined): void {
+ const { names, standard, example } = CODES[kind];
+ if (code !== undefined && !names.of(code))
+ throw new Error(
+ `${NAME}: ${code} is not a ${kind}. Pass an ${standard} code, such as ${example}.`,
+ );
+}
+
+const lowerCase = (value: string) => value.toLowerCase();
+
+/** The day `days` before today, as `YYYY-MM-DD`. */
+function dayBefore(days: number): string {
+ return new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10);
+}
+
+/** `params` without the entries that have no value. */
+function defined(params: Record): Record {
+ return Object.fromEntries(
+ Object.entries(params).filter(([, value]) => value !== undefined),
+ );
+}
+
+/**
+ * The `websearch` plugin over `providers`, in the order one is chosen when
+ * the connection names none. A host adds a provider of its own by passing a
+ * list that includes it.
+ */
+export function websearch(
+ providers: SearchProvider[] = PROVIDERS,
+): PluginFunction {
+ const credential = credentialOf(providers);
+ const names = providers.map((provider) => provider.name);
+
+ return function plugin(rl: CodemodePluginAPI): void {
+ rl.setName(NAME);
+ rl.setVersion(packageVersion(import.meta.url));
+ rl.setDescription(
+ "Search the web through the search provider the connection chooses.",
+ );
+ rl.setCredential(credential);
+ rl.setConnectionSchema(
+ t.Object({
+ provider: t.Optional(
+ t.String({
+ enum: names,
+ description:
+ "The provider every search goes to. The default is the first provider with a key that can apply the search's filters",
+ }),
+ ),
+ ...Object.fromEntries(
+ providers.map((provider) => [
+ keyField(provider),
+ t.Optional(
+ t.String({
+ env: provider.env,
+ description: `API key for ${provider.name}`,
+ }),
+ ),
+ ]),
+ ),
+ ...Object.assign({}, ...providers.map((provider) => provider.fields)),
+ }),
+ );
+
+ rl.registerAction("query", {
+ access: "read",
+ description:
+ "Search the web. Returns results with a title, a URL and the text the provider returned for the page.",
+ hints: { openWorld: true },
+ inputSchema: t.Object(
+ {
+ query: t.String({
+ minLength: 1,
+ maxLength: MAX_QUERY,
+ description: `What to search for, in up to ${MAX_QUERY} characters. Be specific and descriptive`,
+ }),
+ numResults: t.Optional(
+ t.Integer({
+ minimum: 1,
+ maximum: MAX_RESULTS,
+ description: `The most results to return, from 1 to ${MAX_RESULTS}. The default is ${DEFAULT_RESULTS}`,
+ }),
+ ),
+ country: t.Optional(
+ t.String({
+ pattern: "^[A-Za-z]{2}$",
+ description:
+ "Country to prefer results from: an ISO 3166-1 alpha-2 code, such as US, GB, DE",
+ }),
+ ),
+ language: t.Optional(
+ t.String({
+ pattern: "^[A-Za-z]{2}$",
+ description:
+ "Language to prefer results in: an ISO 639-1 code, such as en, es, fr",
+ }),
+ ),
+ includeDomains: t.Optional(
+ t.Array(t.String({ pattern: DOMAIN }), {
+ minItems: 1,
+ maxItems: MAX_DOMAINS,
+ description:
+ 'Return results from these sites only: hostnames without https:// or a path, such as ["duckdb.org", "github.com"]. Not together with excludeDomains',
+ }),
+ ),
+ excludeDomains: t.Optional(
+ t.Array(t.String({ pattern: DOMAIN }), {
+ minItems: 1,
+ maxItems: MAX_DOMAINS,
+ description:
+ 'Leave results from these sites out: hostnames in the same form, such as ["pinterest.com"]. Not together with includeDomains',
+ }),
+ ),
+ freshness: t.Optional(
+ t.String({
+ enum: Object.keys(FRESHNESS_DAYS),
+ description:
+ "Return only pages published within the last day, week, month or year",
+ }),
+ ),
+ },
+ { additionalProperties: false },
+ ),
+ outputSchema: {
+ type: "object",
+ properties: {
+ provider: { type: "string" },
+ results: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ url: { type: "string" },
+ content: { type: "string" },
+ publishedDate: { type: "string" },
+ author: { type: "string" },
+ sourceType: { type: "string" },
+ },
+ required: ["title", "url", "content"],
+ },
+ },
+ },
+ required: ["provider", "results"],
+ },
+ async execute(input, ctx) {
+ if (input.includeDomains && input.excludeDomains)
+ throw new Error(
+ `${NAME}: set includeDomains or excludeDomains, not both.`,
+ );
+ // A code or a hostname means the same in either case, so each is put
+ // in the one case the providers are written against.
+ const country = input.country?.toUpperCase();
+ const language = input.language?.toLowerCase();
+ checkCode("country", country);
+ checkCode("language", language);
+ const numResults = input.numResults ?? DEFAULT_RESULTS;
+ const freshness = input.freshness as Freshness | undefined;
+ const search: SearchRequest = {
+ query: input.query,
+ numResults,
+ country,
+ language,
+ includeDomains: input.includeDomains?.map(lowerCase),
+ excludeDomains: input.excludeDomains?.map(lowerCase),
+ freshness,
+ publishedAfter: freshness && dayBefore(FRESHNESS_DAYS[freshness]),
+ };
+ const provider = chosen(
+ providers,
+ ctx.connection.config,
+ !ctx.credentials,
+ search,
+ );
+ const params = defined(provider.params(search));
+ const answer = await credentialJson(
+ ctx,
+ credential,
+ `${NAME}.${provider.name}`,
+ {
+ target: provider.name,
+ path: provider.path,
+ method: provider.method,
+ ...(provider.method === "GET"
+ ? { query: params }
+ : { json: params }),
+ ...(provider.headers ? { headers: provider.headers } : {}),
+ },
+ );
+ // A provider that takes no number of results, or returns more than
+ // it was asked for, is held to the number here.
+ return {
+ provider: provider.name,
+ results: provider.results(answer).slice(0, numResults),
+ };
+ },
+ });
+ };
+}
+
+export default websearch();
diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts
new file mode 100644
index 00000000..07c8c1bc
--- /dev/null
+++ b/packages/codemode-websearch/src/providers.ts
@@ -0,0 +1,561 @@
+/**
+ * The search providers: for each, where its key goes, the request a search
+ * becomes, and how its answer reads as results. A provider is data and two
+ * pure functions; the plugin sends the request.
+ */
+
+import { httpsBase } from "@shiftlabs/codemode";
+import * as t from "typebox";
+import {
+ BRAVE_COUNTRIES,
+ BRAVE_LANGUAGE_VARIANTS,
+ BRAVE_LANGUAGES,
+ GOOGLE_COUNTRIES,
+ GOOGLE_LANGUAGE_VARIANTS,
+ GOOGLE_LANGUAGES,
+ TAVILY_COUNTRIES,
+ YOU_COUNTRIES,
+} from "./codes.js";
+
+/** How recently a page was published: within the last day, week, month or year. */
+export type Freshness = "day" | "week" | "month" | "year";
+
+/** A search as every provider receives it. */
+export interface SearchRequest {
+ query: string;
+ /** The most results wanted. The plugin returns no more, whatever a provider answers. */
+ numResults: number;
+ /**
+ * ISO 3166-1 alpha-2 country code, upper case, such as `US`. A preference:
+ * a provider that does not localize for it searches without it.
+ */
+ country?: string;
+ /** ISO 639-1 language code, lower case, such as `en`. A preference, like `country`. */
+ language?: string;
+ /** Hostnames in lower case to return results from, and no other. Never set with `excludeDomains`. */
+ includeDomains?: string[];
+ /** Hostnames in lower case to leave out of the results. Never set with `includeDomains`. */
+ excludeDomains?: string[];
+ /** Return only pages published this recently. */
+ freshness?: Freshness;
+ /** The day `freshness` reaches back to, as `YYYY-MM-DD`, for a provider that takes a date. */
+ publishedAfter?: string;
+}
+
+/** One result, in the shape every provider's answer is read into. */
+export interface SearchResult {
+ title: string;
+ url: string;
+ /** The text the provider returned for the page: a snippet, excerpts or the page itself. */
+ content: string;
+ publishedDate?: string;
+ author?: string;
+ sourceType?: string;
+}
+
+/** A search API: where it is, where its key goes, and how a search reads to and from it. */
+export interface SearchProvider {
+ /** The name a connection gives as its `provider`, and the stem of the key's connection field. */
+ name: string;
+ /** The environment variable that fills the key. */
+ env: string;
+ /** Where the key goes in a request: a header, or a query parameter. */
+ key: { header: string; prefix?: string } | { query: string };
+ /**
+ * The HTTPS address the key may be sent beneath, ending in `/`: fixed, or
+ * from the connection's config.
+ */
+ baseUrl: string | ((config: Readonly>) => string);
+ /** Connection fields of the provider's own, beside its key. */
+ fields?: Record;
+ /** How a search is sent: parameters in the query of a GET, or the JSON body of a POST. */
+ method: "GET" | "POST";
+ /** The path of the search endpoint beneath `baseUrl`. */
+ path: string;
+ /** Headers every request carries. */
+ headers?: Record;
+ /**
+ * The provider's parameters for a search, under the names its API gives
+ * them. A domain or freshness filter that changes nothing here is one the
+ * provider cannot apply, and the plugin sends it no search that sets it.
+ */
+ params(search: SearchRequest): Record;
+ /** The results in the provider's answer. */
+ results(answer: unknown): SearchResult[];
+}
+
+type Json = Record;
+
+function object(value: unknown): Json {
+ return value && typeof value === "object" ? (value as Json) : {};
+}
+
+function list(value: unknown): Json[] {
+ return Array.isArray(value) ? value.map(object) : [];
+}
+
+function text(value: unknown): string {
+ return typeof value === "string" ? value : "";
+}
+
+/** The strings among `parts`, joined as paragraphs. */
+function paragraphs(...parts: unknown[]): string {
+ return parts.flat().filter(text).join("\n\n");
+}
+
+/** A result, with each optional field the provider gave as a string. */
+function result(fields: {
+ title: string;
+ url: string;
+ content: string;
+ publishedDate?: unknown;
+ author?: unknown;
+ sourceType?: unknown;
+}): SearchResult {
+ const { title, url, content } = fields;
+ const found: SearchResult = { title, url, content };
+ for (const name of ["publishedDate", "author", "sourceType"] as const) {
+ const value = text(fields[name]);
+ if (value) found[name] = value;
+ }
+ return found;
+}
+
+/**
+ * What a Google results page says about the thing searched for, as a first
+ * result: Serper and SerpAPI return it beside the links.
+ */
+function knowledgeGraph(graph: unknown): SearchResult[] {
+ const { title, description } = object(graph);
+ return text(description)
+ ? [
+ {
+ title: `Knowledge Graph: ${text(title)}`,
+ url: "",
+ content: text(description),
+ },
+ ]
+ : [];
+}
+
+/** `code` when the provider's list has it. */
+function listed(list: ReadonlySet, code?: string): string | undefined {
+ return code !== undefined && list.has(code) ? code : undefined;
+}
+
+/** A language as Brave and You.com name it, when they take it. */
+function braveLanguage(language?: string): string | undefined {
+ return (
+ language &&
+ (BRAVE_LANGUAGE_VARIANTS[language] ?? listed(BRAVE_LANGUAGES, language))
+ );
+}
+
+/** A country as Google names it (`gl`), when it searches for it. */
+function googleCountry(country?: string): string | undefined {
+ return listed(GOOGLE_COUNTRIES, country)?.toLowerCase();
+}
+
+/** A language as Google names it (`hl`), when it takes it. */
+function googleLanguage(language?: string): string | undefined {
+ return (
+ language &&
+ (GOOGLE_LANGUAGE_VARIANTS[language] ?? listed(GOOGLE_LANGUAGES, language))
+ );
+}
+
+/** `fields` when one of them has a value, so an empty object is never sent. */
+function some(fields: T): T | undefined {
+ return Object.values(fields).some((value) => value !== undefined)
+ ? fields
+ : undefined;
+}
+
+/**
+ * The query with its domain filter written as `site:` operators, for a
+ * provider that filters by domain in the query itself.
+ */
+function withSites({
+ query,
+ includeDomains,
+ excludeDomains,
+}: SearchRequest): string {
+ const only = includeDomains?.map((domain) => `site:${domain}`).join(" OR ");
+ const without = excludeDomains?.map((domain) => `-site:${domain}`).join(" ");
+ return [
+ query,
+ only && includeDomains?.length !== 1 ? `(${only})` : only,
+ without,
+ ]
+ .filter(Boolean)
+ .join(" ");
+}
+
+/** Google's `tbs` value for a freshness, which the providers that search Google take. */
+function googleRecency(freshness?: Freshness): string | undefined {
+ return freshness && `qdr:${freshness[0]}`;
+}
+
+export const parallel: SearchProvider = {
+ name: "parallel",
+ env: "PARALLEL_API_KEY",
+ key: { header: "x-api-key" },
+ baseUrl: "https://api.parallel.ai/v1/",
+ method: "POST",
+ path: "search",
+ params: (search) => ({
+ objective: search.query,
+ search_queries: [search.query],
+ mode: "fast",
+ advanced_settings: {
+ max_results: search.numResults,
+ location: search.country?.toLowerCase(),
+ source_policy: some({
+ include_domains: search.includeDomains,
+ exclude_domains: search.excludeDomains,
+ after_date: search.publishedAfter,
+ }),
+ },
+ }),
+ results: (answer) =>
+ list(object(answer).results).map((r) =>
+ result({
+ title: text(r.title) || text(r.url),
+ url: text(r.url),
+ content: paragraphs(r.excerpts),
+ publishedDate: r.publish_date,
+ }),
+ ),
+};
+
+export const brave: SearchProvider = {
+ name: "brave",
+ env: "BRAVE_API_KEY",
+ key: { header: "X-Subscription-Token" },
+ baseUrl: "https://api.search.brave.com/res/v1/",
+ method: "GET",
+ path: "web/search",
+ params: (search) => ({
+ q: withSites(search),
+ count: search.numResults,
+ country: listed(BRAVE_COUNTRIES, search.country),
+ search_lang: braveLanguage(search.language),
+ freshness: search.freshness && `p${search.freshness[0]}`,
+ }),
+ results: (answer) =>
+ list(object(object(answer).web).results).map((r) =>
+ result({
+ title: text(r.title),
+ url: text(r.url),
+ content: paragraphs(r.description, r.extra_snippets),
+ publishedDate: r.page_age,
+ }),
+ ),
+};
+
+export const exa: SearchProvider = {
+ name: "exa",
+ env: "EXA_API_KEY",
+ key: { header: "x-api-key" },
+ baseUrl: "https://api.exa.ai/",
+ method: "POST",
+ path: "search",
+ params: (search) => ({
+ query: search.query,
+ numResults: search.numResults,
+ type: "auto",
+ contents: { text: { maxCharacters: 3000 }, highlights: true },
+ userLocation: search.country,
+ includeDomains: search.includeDomains,
+ excludeDomains: search.excludeDomains,
+ startPublishedDate:
+ search.publishedAfter && `${search.publishedAfter}T00:00:00.000Z`,
+ }),
+ results: (answer) =>
+ list(object(answer).results).map((r) =>
+ result({
+ title: text(r.title) || text(r.url),
+ url: text(r.url),
+ content: paragraphs(r.text, r.highlights),
+ publishedDate: r.publishedDate,
+ author: r.author,
+ }),
+ ),
+};
+
+export const you: SearchProvider = {
+ name: "you",
+ env: "YOU_API_KEY",
+ key: { header: "X-API-Key" },
+ baseUrl: "https://ydc-index.io/v1/",
+ method: "POST",
+ path: "search",
+ params: (search) => ({
+ query: search.query,
+ count: search.numResults,
+ country: listed(YOU_COUNTRIES, search.country),
+ language: braveLanguage(search.language)?.toUpperCase(),
+ include_domains: search.includeDomains,
+ exclude_domains: search.excludeDomains,
+ freshness: search.freshness,
+ }),
+ results: (answer) =>
+ list(object(object(answer).results).web).map((r) =>
+ result({
+ title: text(r.title),
+ url: text(r.url),
+ content:
+ paragraphs(object(r.contents).highlights) ||
+ paragraphs(r.snippets) ||
+ text(r.description),
+ publishedDate: r.page_age,
+ }),
+ ),
+};
+
+export const tavily: SearchProvider = {
+ name: "tavily",
+ env: "TAVILY_API_KEY",
+ key: { header: "Authorization", prefix: "Bearer " },
+ baseUrl: "https://api.tavily.com/",
+ method: "POST",
+ path: "search",
+ params: (search) => ({
+ query: search.query,
+ max_results: search.numResults,
+ search_depth: "basic",
+ country: search.country && TAVILY_COUNTRIES[search.country],
+ language: search.language,
+ include_domains: search.includeDomains,
+ exclude_domains: search.excludeDomains,
+ time_range: search.freshness,
+ }),
+ results: (answer) =>
+ list(object(answer).results).map((r) =>
+ result({
+ title: text(r.title),
+ url: text(r.url),
+ content: text(r.content),
+ publishedDate: r.published_date,
+ }),
+ ),
+};
+
+const FIRECRAWL = "https://api.firecrawl.dev";
+
+export const firecrawl: SearchProvider = {
+ name: "firecrawl",
+ env: "FIRECRAWL_API_KEY",
+ key: { header: "Authorization", prefix: "Bearer " },
+ baseUrl: (config) => httpsBase(config.firecrawlUrl ?? FIRECRAWL, "v2/"),
+ method: "POST",
+ fields: {
+ firecrawlUrl: t.Optional(
+ t.String({
+ env: "FIRECRAWL_URL",
+ description: `A Firecrawl of your own, by its HTTPS address. The default is ${FIRECRAWL}`,
+ }),
+ ),
+ },
+ path: "search",
+ params: (search) => ({
+ query: search.query,
+ limit: search.numResults,
+ country: search.country,
+ includeDomains: search.includeDomains,
+ excludeDomains: search.excludeDomains,
+ tbs: googleRecency(search.freshness),
+ }),
+ results: (answer) =>
+ list(object(object(answer).data).web).map((r) =>
+ result({
+ title: text(r.title) || text(r.url),
+ url: text(r.url),
+ content: text(r.markdown) || text(r.description),
+ }),
+ ),
+};
+
+export const jina: SearchProvider = {
+ name: "jina",
+ env: "JINA_API_KEY",
+ key: { header: "Authorization", prefix: "Bearer " },
+ baseUrl: "https://s.jina.ai/",
+ method: "POST",
+ path: "",
+ headers: { "X-Retain-Images": "none" },
+ // Jina's search takes no list of domains and no date, so neither filter is applied.
+ params: ({ query, numResults, country, language }) => ({
+ q: query,
+ num: numResults,
+ gl: googleCountry(country),
+ hl: googleLanguage(language),
+ }),
+ results: (answer) =>
+ list(object(answer).data).map((r) =>
+ result({
+ title: text(r.title),
+ url: text(r.url),
+ content: text(r.content) || text(r.description),
+ }),
+ ),
+};
+
+export const linkup: SearchProvider = {
+ name: "linkup",
+ env: "LINKUP_API_KEY",
+ key: { header: "Authorization", prefix: "Bearer " },
+ baseUrl: "https://api.linkup.so/v1/",
+ method: "POST",
+ path: "search",
+ params: (search) => ({
+ q: search.query,
+ depth: "standard",
+ outputType: "searchResults",
+ includeImages: false,
+ maxResults: search.numResults,
+ includeDomains: search.includeDomains,
+ excludeDomains: search.excludeDomains,
+ fromDate: search.publishedAfter,
+ }),
+ results: (answer) =>
+ list(object(answer).results).map((r) =>
+ result({
+ title: text(r.name),
+ url: text(r.url),
+ content: text(r.content),
+ }),
+ ),
+};
+
+export const valyu: SearchProvider = {
+ name: "valyu",
+ env: "VALYU_API_KEY",
+ key: { header: "X-API-Key" },
+ baseUrl: "https://api.valyu.ai/v1/",
+ method: "POST",
+ path: "search",
+ params: (search) => ({
+ query: search.query,
+ search_type: "all",
+ max_num_results: search.numResults,
+ country_code: listed(YOU_COUNTRIES, search.country),
+ included_sources: search.includeDomains,
+ excluded_sources: search.excludeDomains,
+ start_date: search.publishedAfter,
+ }),
+ results: (answer) =>
+ list(object(answer).results).map((r) =>
+ result({
+ title: text(r.title),
+ url: text(r.url),
+ content: text(r.content),
+ publishedDate: r.publication_date,
+ sourceType: r.source_type,
+ }),
+ ),
+};
+
+export const perplexity: SearchProvider = {
+ name: "perplexity",
+ env: "PERPLEXITY_API_KEY",
+ key: { header: "Authorization", prefix: "Bearer " },
+ baseUrl: "https://api.perplexity.ai/",
+ method: "POST",
+ path: "search",
+ params: (search) => ({
+ query: search.query,
+ max_results: search.numResults,
+ country: search.country,
+ search_language_filter: search.language && [search.language],
+ // One list holds both: a domain to leave out carries a `-` before it.
+ search_domain_filter:
+ search.includeDomains ??
+ search.excludeDomains?.map((domain) => `-${domain}`),
+ search_recency_filter: search.freshness,
+ }),
+ results: (answer) =>
+ list(object(answer).results).map((r) =>
+ result({
+ title: text(r.title),
+ url: text(r.url),
+ content: text(r.snippet),
+ publishedDate: r.date,
+ }),
+ ),
+};
+
+export const serper: SearchProvider = {
+ name: "serper",
+ env: "SERPER_API_KEY",
+ key: { header: "X-API-KEY" },
+ baseUrl: "https://google.serper.dev/",
+ method: "POST",
+ path: "search",
+ params: (search) => ({
+ q: withSites(search),
+ num: search.numResults,
+ gl: googleCountry(search.country),
+ hl: googleLanguage(search.language),
+ tbs: googleRecency(search.freshness),
+ }),
+ results: (answer) => [
+ ...knowledgeGraph(object(answer).knowledgeGraph),
+ ...list(object(answer).organic).map((r) =>
+ result({
+ title: text(r.title),
+ url: text(r.link),
+ content: text(r.snippet),
+ publishedDate: r.date,
+ }),
+ ),
+ ],
+};
+
+export const serpapi: SearchProvider = {
+ name: "serpapi",
+ env: "SERPAPI_API_KEY",
+ key: { query: "api_key" },
+ baseUrl: "https://serpapi.com/",
+ method: "GET",
+ path: "search.json",
+ // SerpAPI's Google search takes no number of results: it answers a page.
+ params: (search) => ({
+ q: withSites(search),
+ engine: "google",
+ gl: googleCountry(search.country),
+ hl: googleLanguage(search.language),
+ tbs: googleRecency(search.freshness),
+ }),
+ results: (answer) => [
+ ...knowledgeGraph(object(answer).knowledge_graph),
+ ...list(object(answer).organic_results).map((r) =>
+ result({
+ title: text(r.title),
+ url: text(r.link),
+ content: text(r.snippet),
+ publishedDate: r.date,
+ }),
+ ),
+ ],
+};
+
+/**
+ * Every provider, in the order one is chosen when the connection names none:
+ * providers with an index of their own, then those that read pages for a
+ * search, then those that return Google's results.
+ */
+export const PROVIDERS: SearchProvider[] = [
+ parallel,
+ brave,
+ exa,
+ you,
+ tavily,
+ firecrawl,
+ jina,
+ linkup,
+ valyu,
+ perplexity,
+ serper,
+ serpapi,
+];
diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts
new file mode 100644
index 00000000..82e51cf3
--- /dev/null
+++ b/packages/codemode-websearch/tests/websearch.test.ts
@@ -0,0 +1,1075 @@
+/**
+ * The web search package: its one action through a real engine with the
+ * providers' hosts stood in for, and the package as codemode's package
+ * manager loads it.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { afterEach, describe, it } from "node:test";
+import { fileURLToPath } from "node:url";
+import { isDeepStrictEqual } from "node:util";
+import { Codemode } from "@shiftlabs/codemode";
+import { stubFetch } from "../../codemode/src/tests/helpers/plugin.js";
+import { describePackage, pluginHarness } from "../../package-tests/harness.js";
+import plugin, {
+ PROVIDERS,
+ type SearchProvider,
+ type SearchResult,
+ websearch,
+} from "../src/index.js";
+
+const PACKAGE = fileURLToPath(new URL("..", import.meta.url));
+
+interface Sent {
+ method: string;
+ url: string;
+ headers: Record;
+ body: unknown;
+}
+
+const originalFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+/** Answer every request with `answer`, and collect what was sent. */
+function provider(answer: unknown, status = 200): Sent[] {
+ const sent: Sent[] = [];
+ stubFetch(async (url, init) => {
+ const body = init?.body;
+ sent.push({
+ method: init?.method ?? "GET",
+ url: String(url),
+ headers: Object.fromEntries(new Headers(init?.headers)),
+ body: body
+ ? JSON.parse(Buffer.from(body as Uint8Array).toString())
+ : null,
+ });
+ return Response.json(answer, { status });
+ });
+ return sent;
+}
+
+interface Found {
+ provider: string;
+ results: SearchResult[];
+}
+
+const harness = pluginHarness(plugin, "websearch");
+const search = (
+ input: Record,
+ config: Record,
+) => harness.call("query", input, config);
+
+/** A failed search's error text. */
+async function refused(
+ input: Record,
+ config: Record,
+): Promise {
+ const { error } = await harness
+ .codemode(config)
+ .execute(`return await websearch.query(${JSON.stringify(input)})`);
+ assert.ok(error, "the search should fail");
+ return error;
+}
+
+/** A connection with a key for every provider. */
+const ALL_KEYS = Object.fromEntries(
+ PROVIDERS.map(({ name }) => [`${name}ApiKey`, `KEY-${name}`]),
+);
+
+/** A connection with a key for every provider, whose provider is `name`. */
+const through = (name: string) => ({ ...ALL_KEYS, provider: name });
+
+const SEARCH = {
+ query: "duckdb release",
+ numResults: 3,
+ country: "DE",
+ language: "de",
+};
+
+/**
+ * For each provider: the request a search becomes, an answer in the shape
+ * its reference documents, and the results that answer reads as.
+ */
+const CASES: Record<
+ string,
+ {
+ request: Omit & { key: [string, string] | "query" };
+ answer: unknown;
+ results: SearchResult[];
+ }
+> = {
+ parallel: {
+ request: {
+ method: "POST",
+ url: "https://api.parallel.ai/v1/search",
+ key: ["x-api-key", "KEY-parallel"],
+ body: {
+ objective: "duckdb release",
+ search_queries: ["duckdb release"],
+ mode: "fast",
+ advanced_settings: { max_results: 3, location: "de" },
+ },
+ },
+ answer: {
+ search_id: "search_1",
+ results: [
+ {
+ url: "https://a.example/1",
+ title: "One",
+ publish_date: "2026-01-15",
+ excerpts: ["first", "second"],
+ },
+ { url: "https://a.example/2", title: null, excerpts: [] },
+ ],
+ },
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ content: "first\n\nsecond",
+ publishedDate: "2026-01-15",
+ },
+ { title: "https://a.example/2", url: "https://a.example/2", content: "" },
+ ],
+ },
+ brave: {
+ request: {
+ method: "GET",
+ url: "https://api.search.brave.com/res/v1/web/search?q=duckdb+release&count=3&country=DE&search_lang=de",
+ key: ["x-subscription-token", "KEY-brave"],
+ body: null,
+ },
+ answer: {
+ web: {
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ description: "about",
+ extra_snippets: ["more"],
+ page_age: "2026-02-01T00:00:00",
+ },
+ ],
+ },
+ },
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ content: "about\n\nmore",
+ publishedDate: "2026-02-01T00:00:00",
+ },
+ ],
+ },
+ exa: {
+ request: {
+ method: "POST",
+ url: "https://api.exa.ai/search",
+ key: ["x-api-key", "KEY-exa"],
+ body: {
+ query: "duckdb release",
+ numResults: 3,
+ type: "auto",
+ contents: { text: { maxCharacters: 3000 }, highlights: true },
+ userLocation: "DE",
+ },
+ },
+ answer: {
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ text: "body",
+ highlights: ["key line"],
+ publishedDate: "2026-03-01",
+ author: "Ada",
+ },
+ ],
+ },
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ content: "body\n\nkey line",
+ publishedDate: "2026-03-01",
+ author: "Ada",
+ },
+ ],
+ },
+ you: {
+ request: {
+ method: "POST",
+ url: "https://ydc-index.io/v1/search",
+ key: ["x-api-key", "KEY-you"],
+ body: {
+ query: "duckdb release",
+ count: 3,
+ country: "DE",
+ language: "DE",
+ },
+ },
+ answer: {
+ results: {
+ web: [
+ {
+ url: "https://a.example/1",
+ title: "One",
+ description: "about",
+ page_age: "2026-02-16T21:26:51",
+ contents: { highlights: ["h1", "h2"] },
+ },
+ { url: "https://a.example/2", title: "Two", snippets: ["s1"] },
+ { url: "https://a.example/3", title: "Three", description: "d3" },
+ ],
+ },
+ },
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ content: "h1\n\nh2",
+ publishedDate: "2026-02-16T21:26:51",
+ },
+ { title: "Two", url: "https://a.example/2", content: "s1" },
+ { title: "Three", url: "https://a.example/3", content: "d3" },
+ ],
+ },
+ tavily: {
+ request: {
+ method: "POST",
+ url: "https://api.tavily.com/search",
+ key: ["authorization", "Bearer KEY-tavily"],
+ body: {
+ query: "duckdb release",
+ max_results: 3,
+ search_depth: "basic",
+ country: "germany",
+ language: "de",
+ },
+ },
+ answer: {
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ content: "about",
+ score: 0.9,
+ },
+ ],
+ },
+ results: [{ title: "One", url: "https://a.example/1", content: "about" }],
+ },
+ firecrawl: {
+ request: {
+ method: "POST",
+ url: "https://api.firecrawl.dev/v2/search",
+ key: ["authorization", "Bearer KEY-firecrawl"],
+ body: { query: "duckdb release", limit: 3, country: "DE" },
+ },
+ answer: {
+ success: true,
+ data: {
+ web: [
+ { title: "One", url: "https://a.example/1", description: "about" },
+ { url: "https://a.example/2", markdown: "# Two" },
+ ],
+ },
+ },
+ results: [
+ { title: "One", url: "https://a.example/1", content: "about" },
+ {
+ title: "https://a.example/2",
+ url: "https://a.example/2",
+ content: "# Two",
+ },
+ ],
+ },
+ jina: {
+ request: {
+ method: "POST",
+ url: "https://s.jina.ai/",
+ key: ["authorization", "Bearer KEY-jina"],
+ body: { q: "duckdb release", num: 3, gl: "de", hl: "de" },
+ },
+ answer: {
+ data: [
+ { title: "One", url: "https://a.example/1", content: "page" },
+ { title: "Two", url: "https://a.example/2", description: "about" },
+ ],
+ },
+ results: [
+ { title: "One", url: "https://a.example/1", content: "page" },
+ { title: "Two", url: "https://a.example/2", content: "about" },
+ ],
+ },
+ linkup: {
+ request: {
+ method: "POST",
+ url: "https://api.linkup.so/v1/search",
+ key: ["authorization", "Bearer KEY-linkup"],
+ body: {
+ q: "duckdb release",
+ depth: "standard",
+ outputType: "searchResults",
+ includeImages: false,
+ maxResults: 3,
+ },
+ },
+ answer: {
+ results: [
+ {
+ type: "text",
+ name: "One",
+ url: "https://a.example/1",
+ content: "about",
+ },
+ ],
+ },
+ results: [{ title: "One", url: "https://a.example/1", content: "about" }],
+ },
+ valyu: {
+ request: {
+ method: "POST",
+ url: "https://api.valyu.ai/v1/search",
+ key: ["x-api-key", "KEY-valyu"],
+ body: {
+ query: "duckdb release",
+ search_type: "all",
+ max_num_results: 3,
+ country_code: "DE",
+ },
+ },
+ answer: {
+ success: true,
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ content: "about",
+ source_type: "paper",
+ publication_date: "",
+ },
+ ],
+ },
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ content: "about",
+ sourceType: "paper",
+ },
+ ],
+ },
+ perplexity: {
+ request: {
+ method: "POST",
+ url: "https://api.perplexity.ai/search",
+ key: ["authorization", "Bearer KEY-perplexity"],
+ body: {
+ query: "duckdb release",
+ max_results: 3,
+ country: "DE",
+ search_language_filter: ["de"],
+ },
+ },
+ answer: {
+ id: "r1",
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ snippet: "about",
+ date: "2026-06-10",
+ last_updated: "2026-11-18",
+ },
+ ],
+ },
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ content: "about",
+ publishedDate: "2026-06-10",
+ },
+ ],
+ },
+ serper: {
+ request: {
+ method: "POST",
+ url: "https://google.serper.dev/search",
+ key: ["x-api-key", "KEY-serper"],
+ body: { q: "duckdb release", num: 3, gl: "de", hl: "de" },
+ },
+ answer: {
+ knowledgeGraph: { title: "DuckDB", description: "A database" },
+ organic: [
+ { title: "One", link: "https://a.example/1", snippet: "about" },
+ ],
+ },
+ results: [
+ { title: "Knowledge Graph: DuckDB", url: "", content: "A database" },
+ { title: "One", url: "https://a.example/1", content: "about" },
+ ],
+ },
+ serpapi: {
+ request: {
+ method: "GET",
+ url: "https://serpapi.com/search.json?q=duckdb+release&engine=google&gl=de&hl=de&api_key=KEY-serpapi",
+ key: "query",
+ body: null,
+ },
+ answer: {
+ organic_results: [
+ {
+ title: "One",
+ link: "https://a.example/1",
+ snippet: "about",
+ date: "Mar 1, 2026",
+ },
+ ],
+ },
+ results: [
+ {
+ title: "One",
+ url: "https://a.example/1",
+ content: "about",
+ publishedDate: "Mar 1, 2026",
+ },
+ ],
+ },
+};
+
+describe("websearch.query through each provider", () => {
+ it("has a case for every provider", () => {
+ assert.deepEqual(
+ Object.keys(CASES),
+ PROVIDERS.map(({ name }) => name),
+ );
+ });
+
+ for (const [name, { request, answer, results }] of Object.entries(CASES)) {
+ it(`${name}: sends its API's request with its own key alone, and reads its answer`, async () => {
+ const sent = provider(answer);
+ const found = await search(SEARCH, through(name));
+ assert.deepEqual(found, { provider: name, results });
+ assert.equal(sent.length, 1);
+ const [{ method, url, headers, body }] = sent;
+ assert.deepEqual(
+ { method, url, body },
+ {
+ method: request.method,
+ url: request.url,
+ body: request.body,
+ },
+ );
+ if (request.key !== "query")
+ assert.equal(headers[request.key[0]], request.key[1]);
+ const everything = JSON.stringify(sent);
+ for (const other of PROVIDERS)
+ assert.equal(
+ everything.includes(`KEY-${other.name}`),
+ other.name === name,
+ `${other.name}'s key in a request to ${name}`,
+ );
+ });
+ }
+
+ it("sends only what a search sets", async () => {
+ const sent = provider({ web: { results: [] } });
+ const found = await search({ query: "plain" }, { braveApiKey: "k" });
+ assert.deepEqual(found, { provider: "brave", results: [] });
+ assert.equal(
+ sent[0].url,
+ "https://api.search.brave.com/res/v1/web/search?q=plain&count=10",
+ );
+ });
+
+ it("returns no more results than were asked for, whatever the provider answers", async () => {
+ provider({
+ organic_results: [1, 2, 3, 4].map((n) => ({
+ title: `T${n}`,
+ link: `https://a.example/${n}`,
+ snippet: "s",
+ })),
+ });
+ const found = await search(
+ { query: "q", numResults: 2 },
+ through("serpapi"),
+ );
+ assert.deepEqual(
+ found.results.map(({ title }) => title),
+ ["T1", "T2"],
+ );
+ });
+
+ it("carries the headers a provider always sends", async () => {
+ const sent = provider({ data: [] });
+ await search({ query: "plain" }, { jinaApiKey: "k" });
+ assert.equal(sent[0].headers["x-retain-images"], "none");
+ });
+});
+
+describe("the provider a search uses", () => {
+ it("is the first with a key, in the providers' order", async () => {
+ provider({ results: [] });
+ const found = await search(
+ { query: "q" },
+ { tavilyApiKey: "t", exaApiKey: "e", serperApiKey: "s" },
+ );
+ assert.equal(found.provider, "exa");
+ });
+
+ it("is the connection's, when it names one", async () => {
+ const sent = provider({ results: [] });
+ assert.equal(
+ (await search({ query: "q" }, through("tavily"))).provider,
+ "tavily",
+ );
+ assert.equal(new URL(sent[0].url).host, "api.tavily.com");
+ });
+
+ it("is never the call's: a search has no input that names one", async () => {
+ const sent = provider({ results: [] });
+ assert.match(
+ await refused({ query: "q", provider: "exa" }, ALL_KEYS),
+ /Invalid input for websearch\.query/,
+ );
+ assert.equal(sent.length, 0);
+ });
+
+ it("says which keys to set when there is none", async () => {
+ const sent = provider({});
+ const error = await refused({ query: "q" }, {});
+ assert.match(
+ error,
+ /websearch: no search provider has a key\. Set one of /,
+ );
+ for (const { env } of PROVIDERS) assert.ok(error.includes(env), env);
+ assert.equal(sent.length, 0);
+ });
+
+ it("is refused before any request when the connection names one it has no key for", async () => {
+ const sent = provider({});
+ const error = await refused(
+ { query: "q" },
+ { exaApiKey: "e", provider: "brave" },
+ );
+ assert.equal(
+ error.split("\n")[0],
+ "Error: websearch: no key for brave, the connection's provider. Set BRAVE_API_KEY.",
+ );
+ assert.equal(sent.length, 0);
+ });
+
+ it("is refused when the connection names one that does not exist", async () => {
+ const sent = provider({});
+ assert.match(
+ await refused({ query: "q" }, through("altavista")),
+ /websearch: the connection names the provider "altavista"\. The providers are parallel, brave, /,
+ );
+ assert.equal(sent.length, 0);
+ });
+});
+
+/** The day `days` before today, as the plugin writes it. */
+const dayBefore = (days: number) =>
+ new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10);
+
+/**
+ * For each provider that filters: what a search for the last week on two
+ * sites adds to its request, and what leaving one site out adds instead.
+ * `WEEK_AGO` stands for the day a week back.
+ */
+const FILTERED: Record = {
+ parallel: {
+ only: {
+ advanced_settings: {
+ max_results: 10,
+ source_policy: {
+ include_domains: ["a.example", "b.example"],
+ after_date: "WEEK_AGO",
+ },
+ },
+ },
+ without: {
+ advanced_settings: {
+ max_results: 10,
+ source_policy: { exclude_domains: ["c.example"] },
+ },
+ },
+ },
+ brave: {
+ only: { q: "q (site:a.example OR site:b.example)", freshness: "pw" },
+ without: { q: "q -site:c.example" },
+ },
+ exa: {
+ only: {
+ includeDomains: ["a.example", "b.example"],
+ startPublishedDate: "WEEK_AGOT00:00:00.000Z",
+ },
+ without: { excludeDomains: ["c.example"] },
+ },
+ you: {
+ only: { include_domains: ["a.example", "b.example"], freshness: "week" },
+ without: { exclude_domains: ["c.example"] },
+ },
+ tavily: {
+ only: { include_domains: ["a.example", "b.example"], time_range: "week" },
+ without: { exclude_domains: ["c.example"] },
+ },
+ firecrawl: {
+ only: { includeDomains: ["a.example", "b.example"], tbs: "qdr:w" },
+ without: { excludeDomains: ["c.example"] },
+ },
+ linkup: {
+ only: { includeDomains: ["a.example", "b.example"], fromDate: "WEEK_AGO" },
+ without: { excludeDomains: ["c.example"] },
+ },
+ valyu: {
+ only: {
+ included_sources: ["a.example", "b.example"],
+ start_date: "WEEK_AGO",
+ },
+ without: { excluded_sources: ["c.example"] },
+ },
+ perplexity: {
+ only: {
+ search_domain_filter: ["a.example", "b.example"],
+ search_recency_filter: "week",
+ },
+ without: { search_domain_filter: ["-c.example"] },
+ },
+ serper: {
+ only: { q: "q (site:a.example OR site:b.example)", tbs: "qdr:w" },
+ without: { q: "q -site:c.example" },
+ },
+ serpapi: {
+ only: { q: "q (site:a.example OR site:b.example)", tbs: "qdr:w" },
+ without: { q: "q -site:c.example" },
+ },
+};
+
+/** What was sent as parameters: the query of a GET, the body of a POST. */
+function parameters({ method, url, body }: Sent): Record {
+ if (method !== "GET") return body as Record;
+ const { api_key: _, ...query } = Object.fromEntries(
+ new URL(url).searchParams,
+ );
+ return query;
+}
+
+describe("the filters of a search", () => {
+ it("has a case for every provider but jina, which has no filters", () => {
+ assert.deepEqual(
+ Object.keys(FILTERED),
+ PROVIDERS.map(({ name }) => name).filter((name) => name !== "jina"),
+ );
+ });
+
+ for (const [name, { only, without }] of Object.entries(FILTERED)) {
+ it(`${name}: sends sites and freshness as its API names them`, async () => {
+ const sent = provider({});
+ const before = dayBefore(7);
+ await search({ query: "q" }, through(name));
+ await search(
+ {
+ query: "q",
+ includeDomains: ["a.example", "b.example"],
+ freshness: "week",
+ },
+ through(name),
+ );
+ await search(
+ { query: "q", excludeDomains: ["c.example"] },
+ through(name),
+ );
+ const [plain, narrowed, excluded] = sent.map(parameters);
+ // The day a week back is the one before the search, or the one after
+ // it when midnight fell between.
+ const expected = [before, dayBefore(7)].map((weekAgo) => ({
+ ...plain,
+ ...JSON.parse(JSON.stringify(only).replaceAll("WEEK_AGO", weekAgo)),
+ }));
+ assert.ok(
+ expected.some((one) => isDeepStrictEqual(narrowed, one)),
+ JSON.stringify(narrowed),
+ );
+ assert.deepEqual(excluded, { ...plain, ...without });
+ });
+ }
+
+ it("writes one site without brackets", async () => {
+ const sent = provider({});
+ await search(
+ { query: "q", includeDomains: ["a.example"] },
+ through("brave"),
+ );
+ assert.equal(
+ new URL(sent[0].url).searchParams.get("q"),
+ "q site:a.example",
+ );
+ });
+
+ it("go to the first provider with a key that applies them, when the connection names none", async () => {
+ const sent = provider({});
+ const keys = { jinaApiKey: "j", serperApiKey: "s" };
+ assert.equal((await search({ query: "q" }, keys)).provider, "jina");
+ assert.equal(
+ (await search({ query: "q", freshness: "day" }, keys)).provider,
+ "serper",
+ );
+ assert.deepEqual(
+ sent.map(({ url }) => new URL(url).host),
+ ["s.jina.ai", "google.serper.dev"],
+ );
+ });
+
+ it("are refused when no provider with a key applies them", async () => {
+ const sent = provider({});
+ assert.equal(
+ (
+ await refused(
+ { query: "q", includeDomains: ["a.example"], freshness: "day" },
+ { jinaApiKey: "j" },
+ )
+ ).split("\n")[0],
+ "Error: websearch: no provider with a key can filter by includeDomains and freshness. Search without one of them.",
+ );
+ assert.equal(sent.length, 0);
+ });
+
+ it("are refused when the connection's provider does not apply them", async () => {
+ const sent = provider({});
+ assert.equal(
+ (await refused({ query: "q", freshness: "day" }, through("jina"))).split(
+ "\n",
+ )[0],
+ "Error: websearch: jina, the connection's provider, cannot filter by freshness. Search without it.",
+ );
+ assert.equal(sent.length, 0);
+ });
+
+ it("takes sites to search or sites to leave out, not both", async () => {
+ const sent = provider({});
+ assert.match(
+ await refused(
+ {
+ query: "q",
+ includeDomains: ["a.example"],
+ excludeDomains: ["b.example"],
+ },
+ ALL_KEYS,
+ ),
+ /websearch: set includeDomains or excludeDomains, not both\./,
+ );
+ assert.equal(sent.length, 0);
+ });
+});
+
+describe("a country and a language", () => {
+ /** What each of these providers is sent for a search with these codes. */
+ const sentFor = async (
+ name: string,
+ input: Record,
+ ): Promise> => {
+ const sent = provider({});
+ await search({ query: "q", ...input }, through(name));
+ return parameters(sent[0]);
+ };
+
+ it("reach each provider in the form its API documents", async () => {
+ const codes = { country: "GB", language: "pt" };
+ assert.deepEqual(
+ {
+ parallel: (await sentFor("parallel", codes)).advanced_settings,
+ brave: await sentFor("brave", codes),
+ you: await sentFor("you", codes),
+ tavily: await sentFor("tavily", codes),
+ serper: await sentFor("serper", codes),
+ },
+ {
+ parallel: { max_results: 10, location: "gb" },
+ brave: { q: "q", count: "10", country: "GB", search_lang: "pt-br" },
+ you: { query: "q", count: 10, country: "GB", language: "PT-BR" },
+ tavily: {
+ query: "q",
+ max_results: 10,
+ search_depth: "basic",
+ country: "united kingdom",
+ language: "pt",
+ },
+ serper: { q: "q", num: 10, gl: "gb", hl: "pt" },
+ },
+ );
+ });
+
+ it("name a language as the provider does where it takes one only with a script or a region", async () => {
+ const chinese = { language: "zh" };
+ assert.deepEqual(
+ [
+ (await sentFor("brave", chinese)).search_lang,
+ (await sentFor("you", chinese)).language,
+ (await sentFor("serpapi", chinese)).hl,
+ (await sentFor("tavily", chinese)).language,
+ ],
+ ["zh-hans", "ZH-HANS", "zh-cn", "zh"],
+ );
+ });
+
+ it("are left out for a provider whose list does not have them", async () => {
+ // Israel and Tibetan: real codes that Brave, You.com, Valyu and Google's
+ // language list do not carry.
+ const codes = { country: "IL", language: "bo" };
+ assert.deepEqual(await sentFor("brave", codes), { q: "q", count: "10" });
+ assert.deepEqual(await sentFor("you", codes), { query: "q", count: 10 });
+ assert.deepEqual(await sentFor("valyu", codes), {
+ query: "q",
+ search_type: "all",
+ max_num_results: 10,
+ });
+ assert.deepEqual(await sentFor("serpapi", codes), {
+ q: "q",
+ engine: "google",
+ gl: "il",
+ });
+ assert.deepEqual(await sentFor("perplexity", codes), {
+ query: "q",
+ max_results: 10,
+ country: "IL",
+ search_language_filter: ["bo"],
+ });
+ });
+
+ it("mean the same in either case, as a hostname does", async () => {
+ assert.deepEqual(
+ await sentFor("perplexity", {
+ country: "gb",
+ language: "PT",
+ includeDomains: ["DuckDB.org"],
+ }),
+ {
+ query: "q",
+ max_results: 10,
+ country: "GB",
+ search_language_filter: ["pt"],
+ search_domain_filter: ["duckdb.org"],
+ },
+ );
+ assert.deepEqual(
+ await sentFor("brave", { excludeDomains: ["Medium.COM"] }),
+ { q: "q -site:medium.com", count: "10" },
+ );
+ });
+
+ it("are refused when they name no country or language", async () => {
+ const sent = provider({});
+ assert.match(
+ await refused({ query: "q", country: "XX" }, ALL_KEYS),
+ /websearch: XX is not a country\. Pass an ISO 3166-1 alpha-2 code, such as US\./,
+ );
+ assert.match(
+ await refused({ query: "q", language: "xx" }, ALL_KEYS),
+ /websearch: xx is not a language\. Pass an ISO 639-1 code, such as en\./,
+ );
+ assert.equal(sent.length, 0);
+ });
+});
+
+describe("what a search accepts", () => {
+ it("refuses a value in another form than the one each input has, and an input it does not have", async () => {
+ const sent = provider({});
+ for (const input of [
+ { query: "q", numResults: 0 },
+ { query: "q", numResults: 21 },
+ { query: "q", numResults: 2.5 },
+ { query: "q", country: "germany" },
+ { query: "q", language: "eng" },
+ { query: "x".repeat(401) },
+ { query: "" },
+ { query: "q", depth: "deep" },
+ { query: "q", options: { freshness: "pw" } },
+ { query: "q", freshness: "fortnight" },
+ { query: "q", includeDomains: [] },
+ { query: "q", includeDomains: ["https://a.example/docs"] },
+ { query: "q", excludeDomains: ["a example"] },
+ ])
+ assert.match(
+ await refused(input, ALL_KEYS),
+ /Invalid input for websearch\.query/,
+ JSON.stringify(input),
+ );
+ assert.equal(sent.length, 0);
+ });
+});
+
+describe("a provider that fails", () => {
+ it("is reported by provider and status, without what it answered", async () => {
+ provider({ error: "the key KEY-brave is not valid" }, 401);
+ const error = await refused({ query: "q" }, through("brave"));
+ assert.match(error, /websearch\.brave: request failed \(HTTP 401\)/);
+ assert.ok(!error.includes("KEY-brave"));
+ });
+
+ it("reads an answer without results as none", async () => {
+ provider({ unexpected: true });
+ for (const { name } of PROVIDERS)
+ assert.deepEqual(await search({ query: "q" }, through(name)), {
+ provider: name,
+ results: [],
+ });
+ });
+});
+
+describe("a Firecrawl of the host's own", () => {
+ it("is searched at its address", async () => {
+ const sent = provider({ data: { web: [] } });
+ await search(
+ { query: "q" },
+ { firecrawlApiKey: "k", firecrawlUrl: "https://crawl.acme.example" },
+ );
+ assert.equal(sent[0].url, "https://crawl.acme.example/v2/search");
+ });
+
+ it("is refused over plain HTTP, where the key would travel in the clear", async () => {
+ const sent = provider({});
+ assert.match(
+ await refused(
+ { query: "q" },
+ { firecrawlApiKey: "k", firecrawlUrl: "http://crawl.acme.example" },
+ ),
+ /Missing or invalid authentication credentials/,
+ );
+ assert.equal(sent.length, 0);
+ });
+});
+
+describe("a provider a host adds", () => {
+ const acme: SearchProvider = {
+ name: "acme",
+ env: "ACME_SEARCH_KEY",
+ key: { header: "X-Acme-Key" },
+ baseUrl: "https://search.acme.example/api/",
+ method: "GET",
+ path: "find",
+ params: ({ query, numResults }) => ({ q: query, n: numResults }),
+ results: (answer) =>
+ (answer as { hits: Array<{ name: string; href: string }> }).hits.map(
+ ({ name, href }) => ({ title: name, url: href, content: "" }),
+ ),
+ };
+ const extended = pluginHarness(websearch([acme, ...PROVIDERS]), "websearch");
+
+ it("is searched like the others, with a key of its own", async () => {
+ const sent = provider({
+ hits: [{ name: "One", href: "https://a.example" }],
+ });
+ const found = await extended.call(
+ "query",
+ { query: "q" },
+ { ...ALL_KEYS, acmeApiKey: "KEY-acme" },
+ );
+ assert.deepEqual(found, {
+ provider: "acme",
+ results: [{ title: "One", url: "https://a.example", content: "" }],
+ });
+ assert.equal(sent[0].url, "https://search.acme.example/api/find?q=q&n=10");
+ assert.equal(sent[0].headers["x-acme-key"], "KEY-acme");
+ assert.ok(!JSON.stringify(sent).includes("KEY-parallel"));
+ });
+});
+
+describe("a host that keeps the keys", () => {
+ it("is asked to sign the request for the connection's provider, which holds no key", async () => {
+ const sent = provider({});
+ const requests: unknown[] = [];
+ const codemode = Codemode.create({
+ plugins: [plugin],
+ connections: [
+ {
+ name: "websearch",
+ plugin: "websearch",
+ config: { provider: "exa" },
+ },
+ ],
+ credentialBroker: () => ({
+ request: async (request) => {
+ requests.push(request);
+ return Response.json({
+ results: [{ title: "One", url: "https://a.example/1", text: "t" }],
+ });
+ },
+ probe: async () => ({ outcome: "unverified" }),
+ }),
+ });
+ try {
+ const { result, error } = await codemode.execute(
+ 'return await websearch.query({ query: "q" })',
+ );
+ assert.equal(error, undefined);
+ assert.deepEqual(result, {
+ provider: "exa",
+ results: [{ title: "One", url: "https://a.example/1", content: "t" }],
+ });
+ assert.deepEqual(requests, [
+ {
+ target: "exa",
+ path: "search",
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Accept: "application/json",
+ },
+ body: JSON.stringify({
+ query: "q",
+ numResults: 10,
+ type: "auto",
+ contents: { text: { maxCharacters: 3000 }, highlights: true },
+ }),
+ },
+ ]);
+ assert.equal(sent.length, 0);
+ } finally {
+ codemode.dispose();
+ }
+ });
+});
+
+describe("the README", () => {
+ it("lists the providers in their order, with each key, what a search sends it and whether it filters", () => {
+ const readme = readFileSync(join(PACKAGE, "README.md"), "utf8");
+ const rows = [
+ ...readme.matchAll(
+ /^\| `(\w+)` \| `(\w+)` \| (Yes|No) \| (Yes|No) \| (Yes|No) \|$/gm,
+ ),
+ ].map(([, ...row]) => row);
+ assert.deepEqual(
+ rows,
+ PROVIDERS.map(({ name, env, params }) => {
+ const plain = { query: "q", numResults: 5 };
+ const changes = (more: object) =>
+ JSON.stringify(params({ ...plain, ...more })) ===
+ JSON.stringify(params(plain))
+ ? "No"
+ : "Yes";
+ return [
+ name,
+ env,
+ changes({ country: "DE" }),
+ changes({ language: "de" }),
+ changes({ includeDomains: ["a.example"] }),
+ ];
+ }),
+ );
+ });
+});
+
+describePackage(PACKAGE, {
+ package: "@shiftlabs/codemode-websearch",
+ plugin: "websearch",
+ actions: 1,
+ write: 0,
+});
diff --git a/packages/codemode-websearch/tsconfig.json b/packages/codemode-websearch/tsconfig.json
new file mode 100644
index 00000000..956f602c
--- /dev/null
+++ b/packages/codemode-websearch/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "compilerOptions": {
+ "target": "esnext",
+ "module": "nodenext",
+ "moduleResolution": "nodenext",
+ "noEmit": true,
+ "strict": true,
+ "skipLibCheck": true,
+ "types": ["node", "bun"]
+ },
+ "include": ["src", "tests"]
+}
diff --git a/packages/codemode/src/tests/credential-fixtures/parallel.ts b/packages/codemode/src/tests/credential-fixtures/parallel.ts
deleted file mode 100644
index 05a86e54..00000000
--- a/packages/codemode/src/tests/credential-fixtures/parallel.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import parallel from "../../../../codemode-plugins/parallel/src/index.js";
-import type { CredentialFixture } from "./fixture.js";
-
-export default {
- plugin: parallel,
- name: "parallel",
- config: { apiKey: "par_key" },
- secrets: ["apiKey"],
- action: "search",
- input: { objective: "office vacancy rates" },
- response: { search_id: "s1", results: [] },
- target: "api",
- wire: {
- url: "https://api.parallel.ai/v1beta/search",
- header: ["x-api-key", "par_key"],
- },
-} satisfies CredentialFixture;