From 48216b6f9750a73c44071a21c3bc6da8ed348d1c Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:02:00 +0200 Subject: [PATCH 01/14] feat: codemode-websearch package, one web.search across twelve providers (SHFT-2967) --- README.md | 1 + bun.lock | 17 + docs/bundled-plugins.md | 2 +- packages/codemode-websearch/README.md | 159 ++++ packages/codemode-websearch/package.json | 51 ++ packages/codemode-websearch/src/index.ts | 266 +++++++ packages/codemode-websearch/src/providers.ts | 434 +++++++++++ .../tests/websearch.test.ts | 681 ++++++++++++++++++ packages/codemode-websearch/tsconfig.json | 12 + 9 files changed, 1622 insertions(+), 1 deletion(-) create mode 100644 packages/codemode-websearch/README.md create mode 100644 packages/codemode-websearch/package.json create mode 100644 packages/codemode-websearch/src/index.ts create mode 100644 packages/codemode-websearch/src/providers.ts create mode 100644 packages/codemode-websearch/tests/websearch.test.ts create mode 100644 packages/codemode-websearch/tsconfig.json diff --git a/README.md b/README.md index 4ebcc67b..5cd42a34 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 `web` 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/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..e49c0305 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: diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md new file mode 100644 index 00000000..e4ffdf1a --- /dev/null +++ b/packages/codemode-websearch/README.md @@ -0,0 +1,159 @@ +# codemode-websearch + +A [codemode](../../README.md) package with one plugin, `web`, whose one action searches the web through the search provider you have a key for. + +Code calls `web.search` the same way whichever provider answers, and gets results in one shape. Changing provider changes a key, 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 + +`web.search` returns the results and the provider that gave them: + +```bash +codemode exec 'return await web.search({ 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` | How many results to return, from 1 to 20. The default is 5 | +| `country` | Two-letter country code to localize results, such as `de` | +| `language` | Two-letter language code of the results, such as `de` | +| `provider` | The provider to search with. The default is the connection's | +| `options` | Parameters of the provider's own search API | + +| 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 | + +A provider that does not take a country or a language searches without it. + +## Choose a provider + +A search uses the provider it names, else the connection's `provider`, else the first provider in this table that has a key: + +| Provider | Key | Sends `country` | Sends `language` | +|---|---|---|---| +| `parallel` | `PARALLEL_API_KEY` | Yes | No | +| `brave` | `BRAVE_API_KEY` | Yes | Yes | +| `exa` | `EXA_API_KEY` | Yes | No | +| `you` | `YOU_API_KEY` | Yes | Yes | +| `tavily` | `TAVILY_API_KEY` | No | Yes | +| `firecrawl` | `FIRECRAWL_API_KEY` | Yes | No | +| `jina` | `JINA_API_KEY` | Yes | Yes | +| `linkup` | `LINKUP_API_KEY` | No | No | +| `valyu` | `VALYU_API_KEY` | Yes | No | +| `perplexity` | `PERPLEXITY_API_KEY` | Yes | Yes | +| `serper` | `SERPER_API_KEY` | Yes | Yes | +| `serpapi` | `SERPAPI_API_KEY` | Yes | Yes | + +Name a provider to search with it for one call: + +```js +const { results } = await web.search({ query: "duckdb", provider: "exa" }); +``` + +## Pass a provider's own parameters + +`options` holds parameters of the provider's search API, under the names that API gives them. They are added to the request, and replace what the search would send under the same name: + +```js +await web.search({ + query: "duckdb extensions", + provider: "exa", + options: { type: "deep", includeDomains: ["duckdb.org"] }, +}); + +await web.search({ + query: "duckdb", + provider: "brave", + options: { freshness: "pw" }, +}); +``` + +Name the provider in a call that passes `options`, because another provider gives its parameters other names. + +## Configure the connection + +Add a connection to keep keys in codemode, or to set the default provider. Every field is optional: + +```bash +codemode connection add web --plugin web --set exaApiKey=$EXA_API_KEY --set tavilyApiKey=$TAVILY_API_KEY --set provider=tavily +``` + +| Field | Meaning | +|---|---| +| `provider` | The provider a search uses when it names none | +| `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 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" }, + target: { baseUrl: "https://search.acme.example/api/", methods: ["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. The first method of `target.methods` is the one a search uses: 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 provider named has no key | The call rejects and names its environment variable | +| The provider refuses the request | The call rejects with `web.: 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. +- Serper and SerpAPI can return a first result with an empty `url`: what Google's results page says about the thing searched for. +- 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/index.ts b/packages/codemode-websearch/src/index.ts new file mode 100644 index 00000000..6aff5798 --- /dev/null +++ b/packages/codemode-websearch/src/index.ts @@ -0,0 +1,266 @@ +/** + * Web search for codemode: one action that searches the web through + * whichever provider the connection has a key for, and answers results in + * one shape whichever provider that was. + * + * const { results } = await web.search({ 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 { PROVIDERS, type SearchProvider } from "./providers.js"; + +export * from "./providers.js"; + +const NAME = "web"; +const DEFAULT_RESULTS = 5; +const MAX_RESULTS = 20; +/** A search that reads pages can take longer than the transport waits by default. */ +const TIMEOUT_MS = 60_000; + +/** The connection field that holds a provider's key. */ +function keyField(provider: SearchProvider): string { + return `${provider.name}ApiKey`; +} + +/** + * 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. + */ +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, target }): [string, CredentialTarget] => [ + name, + { + timeoutMs: TIMEOUT_MS, + ...(typeof target === "function" ? target(config) : target), + }, + ]), + ), + }); +} + +/** + * The provider a search goes to: the one the call names, else the + * connection's `provider`, else the first with a key in the connection. + */ +function chosen( + providers: SearchProvider[], + config: Record, + named: string | undefined, +): SearchProvider { + const name = named ?? config.provider; + if (name !== undefined) { + const provider = providers.find((candidate) => candidate.name === name); + if (provider) return provider; + throw new Error( + `${NAME}: no provider named ${JSON.stringify(name)}. The providers are ${providers.map((candidate) => candidate.name).join(", ")}.`, + ); + } + const provider = providers.find((candidate) => config[keyField(candidate)]); + if (provider) return provider; + 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.`, + ); +} + +/** `params` without the entries that have no value. */ +function defined(params: Record): Record { + return Object.fromEntries( + Object.entries(params).filter(([, value]) => value !== undefined), + ); +} + +/** + * The `web` plugin over `providers`, in the order one is chosen when a + * search 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 web(rl: CodemodePluginAPI): void { + rl.setName(NAME); + rl.setVersion(packageVersion(import.meta.url)); + rl.setDescription( + "Search the web through the search provider the connection has a key for.", + ); + rl.setCredential(credential); + rl.setConnectionSchema( + t.Object({ + provider: t.Optional( + t.String({ + enum: names, + description: + "The provider a search uses when it names none. The default is the first provider with a key", + }), + ), + ...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("search", { + 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, + description: "What to search for. Be specific and descriptive", + }), + numResults: t.Optional( + t.Integer({ + minimum: 1, + maximum: MAX_RESULTS, + description: `How many results to return, from 1 to ${MAX_RESULTS}. The default is ${DEFAULT_RESULTS}`, + }), + ), + country: t.Optional( + t.String({ + pattern: "^[A-Za-z]{2}$", + description: + "Two-letter country code to localize results, such as us, gb, de", + }), + ), + language: t.Optional( + t.String({ + pattern: "^[A-Za-z]{2}$", + description: + "Two-letter language code of the results, such as en, es, fr", + }), + ), + provider: t.Optional( + t.String({ + enum: names, + description: + "The provider to search with. The default is the connection's", + }), + ), + options: t.Optional( + t.Record(t.String(), t.Unknown(), { + description: + "Parameters of the provider's own search API, under the names it gives them. They replace what the search would send under the same name", + }), + ), + }, + { 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) { + const provider = chosen( + providers, + ctx.connection.config, + input.provider, + ); + // A host that signs requests keeps the keys, so only a connection + // that signs for itself is asked for one here. + if (!ctx.credentials && !ctx.connection.config[keyField(provider)]) + throw new Error( + `${NAME}: no key for ${provider.name}. Set ${provider.env}, or search with a provider that has one.`, + ); + const method = ( + typeof provider.target === "function" + ? provider.target(ctx.connection.config) + : provider.target + ).methods[0]; + const params = defined({ + ...provider.params({ + query: input.query, + numResults: input.numResults ?? DEFAULT_RESULTS, + country: input.country?.toLowerCase(), + language: input.language?.toLowerCase(), + }), + ...input.options, + }); + const answer = await credentialJson( + ctx, + credential, + `${NAME}.${provider.name}`, + { + target: provider.name, + path: provider.path, + method, + ...(method === "GET" ? { query: params } : { json: params }), + ...(provider.headers ? { headers: provider.headers } : {}), + }, + ); + return { provider: provider.name, results: provider.results(answer) }; + }, + }); + }; +} + +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..000655e5 --- /dev/null +++ b/packages/codemode-websearch/src/providers.ts @@ -0,0 +1,434 @@ +/** + * 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 { type CredentialTarget, httpsBase } from "@shiftlabs/codemode"; +import * as t from "typebox"; + +/** A search as every provider receives it. */ +export interface SearchRequest { + query: string; + numResults: number; + /** Two-letter country code, lower case. */ + country?: string; + /** Two-letter language code, lower case. */ + language?: 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; +} + +export interface SearchProvider { + /** The name code passes as `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 one place the key may be sent. */ + target: + | CredentialTarget + | ((config: Record) => CredentialTarget); + /** Connection fields of the provider's own, beside its key. */ + fields?: Record; + /** The path of the search endpoint beneath the target. */ + path: string; + /** Headers every request carries. The target allows them. */ + headers?: Record; + /** + * The provider's parameters for a search, under the names its API gives + * them: the query of a GET, the JSON body of a POST. + */ + 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), + }, + ] + : []; +} + +const upper = (code?: string) => code?.toUpperCase(); + +export const parallel: SearchProvider = { + name: "parallel", + env: "PARALLEL_API_KEY", + key: { header: "x-api-key" }, + target: { baseUrl: "https://api.parallel.ai/v1/", methods: ["POST"] }, + path: "search", + params: ({ query, numResults, country }) => ({ + objective: query, + search_queries: [query], + mode: "fast", + advanced_settings: { max_results: numResults, location: country }, + }), + 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" }, + target: { baseUrl: "https://api.search.brave.com/res/v1/", methods: ["GET"] }, + path: "web/search", + params: ({ query, numResults, country, language }) => ({ + q: query, + count: numResults, + country: upper(country), + search_lang: language, + }), + 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" }, + target: { baseUrl: "https://api.exa.ai/", methods: ["POST"] }, + path: "search", + params: ({ query, numResults, country }) => ({ + query, + numResults, + type: "auto", + contents: { text: { maxCharacters: 3000 }, highlights: true }, + userLocation: upper(country), + }), + 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" }, + target: { baseUrl: "https://ydc-index.io/v1/", methods: ["POST"] }, + path: "search", + params: ({ query, numResults, country, language }) => ({ + query, + count: numResults, + country: upper(country), + language: upper(language), + }), + 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 " }, + target: { baseUrl: "https://api.tavily.com/", methods: ["POST"] }, + path: "search", + // Tavily takes a country by its English name, so a country code is not sent. + params: ({ query, numResults, language }) => ({ + query, + max_results: numResults, + search_depth: "basic", + language, + }), + 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 " }, + target: (config) => ({ + baseUrl: httpsBase(config.firecrawlUrl ?? FIRECRAWL, "v2/"), + methods: ["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: ({ query, numResults, country }) => ({ + query, + limit: numResults, + country: upper(country), + }), + 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 " }, + target: { + baseUrl: "https://s.jina.ai/", + methods: ["POST"], + allowedHeaders: ["X-Retain-Images"], + }, + path: "", + headers: { "X-Retain-Images": "none" }, + params: ({ query, numResults, country, language }) => ({ + q: query, + num: numResults, + gl: country, + hl: 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 " }, + target: { baseUrl: "https://api.linkup.so/v1/", methods: ["POST"] }, + path: "search", + params: ({ query, numResults }) => ({ + q: query, + depth: "standard", + outputType: "searchResults", + includeImages: false, + maxResults: numResults, + }), + 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" }, + target: { baseUrl: "https://api.valyu.ai/v1/", methods: ["POST"] }, + path: "search", + params: ({ query, numResults, country }) => ({ + query, + search_type: "all", + max_num_results: numResults, + country_code: upper(country), + }), + 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 " }, + target: { baseUrl: "https://api.perplexity.ai/", methods: ["POST"] }, + path: "search", + params: ({ query, numResults, country, language }) => ({ + query, + max_results: numResults, + country: upper(country), + search_language_filter: language ? [language] : undefined, + }), + 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" }, + target: { baseUrl: "https://google.serper.dev/", methods: ["POST"] }, + path: "search", + params: ({ query, numResults, country, language }) => ({ + q: query, + num: numResults, + gl: country, + hl: language, + }), + 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" }, + target: { baseUrl: "https://serpapi.com/", methods: ["GET"] }, + path: "search.json", + params: ({ query, numResults, country, language }) => ({ + q: query, + engine: "google", + num: numResults, + gl: country, + hl: language, + }), + 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 a search 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..8e42ac88 --- /dev/null +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -0,0 +1,681 @@ +/** + * 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 { afterEach, describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; +import { stubFetch } from "../../codemode/src/tests/helpers/plugin.js"; +import { describePackage, pluginHarness } from "../../package-tests/harness.js"; +import web, { + 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(web, "web"); +const search = ( + input: Record, + config: Record, +) => harness.call("search", 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 web.search(${JSON.stringify(input)})`); + assert.ok(error, "the search should fail"); + return error; +} + +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", + 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&num=3&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", + }, + ], + }, +}; + +/** A connection with a key for every provider. */ +const ALL_KEYS = Object.fromEntries( + PROVIDERS.map(({ name }) => [`${name}ApiKey`, `KEY-${name}`]), +); + +describe("web.search 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, provider: name }, ALL_KEYS); + 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=5", + ); + }); + + 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, and then the call's", async () => { + const sent = provider({ results: [] }); + const config = { ...ALL_KEYS, provider: "tavily" }; + assert.equal((await search({ query: "q" }, config)).provider, "tavily"); + assert.equal( + (await search({ query: "q", provider: "exa" }, config)).provider, + "exa", + ); + assert.deepEqual( + sent.map(({ url }) => new URL(url).host), + ["api.tavily.com", "api.exa.ai"], + ); + }); + + it("says which keys to set when there is none", async () => { + const sent = provider({}); + const error = await refused({ query: "q" }, {}); + assert.match(error, /web: 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("refuses a provider whose key the connection lacks, before any request", async () => { + const sent = provider({}); + const error = await refused( + { query: "q", provider: "brave" }, + { exaApiKey: "e" }, + ); + assert.equal( + error.split("\n")[0], + "Error: web: no key for brave. Set BRAVE_API_KEY, or search with a provider that has one.", + ); + assert.equal(sent.length, 0); + }); + + it("refuses a provider it does not know", async () => { + const sent = provider({}); + assert.match( + await refused({ query: "q", provider: "altavista" }, ALL_KEYS), + /provider/, + ); + assert.match( + await refused({ query: "q" }, { ...ALL_KEYS, provider: "altavista" }), + /web: no provider named "altavista"\. The providers are parallel, brave, /, + ); + assert.equal(sent.length, 0); + }); +}); + +describe("a provider's own parameters", () => { + it("are sent under its names, over what the search would send", async () => { + const sent = provider({ results: [] }); + await search( + { + query: "q", + provider: "exa", + options: { type: "deep", includeDomains: ["duckdb.org"] }, + }, + ALL_KEYS, + ); + assert.deepEqual(sent[0].body, { + query: "q", + numResults: 5, + type: "deep", + contents: { text: { maxCharacters: 3000 }, highlights: true }, + includeDomains: ["duckdb.org"], + }); + }); + + it("go in the query of a provider that is searched with GET", async () => { + const sent = provider({ web: { results: [] } }); + await search( + { query: "q", provider: "brave", options: { freshness: "pw" } }, + ALL_KEYS, + ); + assert.equal(new URL(sent[0].url).searchParams.get("freshness"), "pw"); + }); + + it("cannot name the parameter that carries the key", async () => { + const sent = provider({}); + await refused( + { query: "q", provider: "serpapi", options: { api_key: "mine" } }, + ALL_KEYS, + ); + assert.equal(sent.length, 0); + }); +}); + +describe("what a search accepts", () => { + it("refuses a number of results outside 1 to 20, and a country that is not a code", 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: "" }, + { query: "q", depth: "deep" }, + ]) + await refused(input, ALL_KEYS); + 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", provider: "brave" }, ALL_KEYS); + assert.match(error, /web\.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", provider: name }, ALL_KEYS), { + 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({}); + await refused( + { query: "q" }, + { firecrawlApiKey: "k", firecrawlUrl: "http://crawl.acme.example" }, + ); + 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" }, + target: { baseUrl: "https://search.acme.example/api/", methods: ["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]), "web"); + + 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( + "search", + { 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=5"); + assert.equal(sent[0].headers["x-acme-key"], "KEY-acme"); + assert.ok(!JSON.stringify(sent).includes("KEY-parallel")); + }); +}); + +describePackage(PACKAGE, { + package: "@shiftlabs/codemode-websearch", + plugin: "web", + 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"] +} From 5c590fbe18a6f9e555c36b59ec5de6a2410ddb40 Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:05:56 +0200 Subject: [PATCH 02/14] refactor: a search provider states its address and method; one check for a key; tests for a signing host and the README table (SHFT-2967) --- packages/codemode-websearch/README.md | 7 +- packages/codemode-websearch/src/index.ts | 77 ++++++++----- packages/codemode-websearch/src/providers.ts | 66 ++++++----- .../tests/websearch.test.ts | 109 ++++++++++++++++-- 4 files changed, 186 insertions(+), 73 deletions(-) diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index e4ffdf1a..e4da7dab 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -117,7 +117,7 @@ Each key is declared with the one host that may receive it. A search through one ## 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 address that may receive the key, the parameters a search becomes, and how its answer reads as results: +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"; @@ -127,7 +127,8 @@ const acme: SearchProvider = { name: "acme", env: "ACME_SEARCH_KEY", key: { header: "X-Acme-Key" }, - target: { baseUrl: "https://search.acme.example/api/", methods: ["GET"] }, + baseUrl: "https://search.acme.example/api/", + method: "GET", path: "find", params: ({ query, numResults }) => ({ q: query, n: numResults }), results: (answer) => @@ -139,7 +140,7 @@ const acme: SearchProvider = { const codemode = Codemode.create({ plugins: [webSearch([acme, ...PROVIDERS])] }); ``` -The list's order is the order a provider is chosen in. The first method of `target.methods` is the one a search uses: 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. +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 diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts index 6aff5798..dc72e86e 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -35,10 +35,19 @@ 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. + * 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); @@ -65,13 +74,18 @@ function credentialOf(providers: SearchProvider[]): CredentialDeclaration { ), targets: (config) => Object.fromEntries( - providers.map(({ name, target }): [string, CredentialTarget] => [ - name, - { - timeoutMs: TIMEOUT_MS, - ...(typeof target === "function" ? target(config) : target), - }, - ]), + 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, + }, + ], + ), ), }); } @@ -79,25 +93,34 @@ function credentialOf(providers: SearchProvider[]): CredentialDeclaration { /** * The provider a search goes to: the one the call names, else the * connection's `provider`, else the first with a key in the connection. + * A host that signs requests keeps the keys, so only a connection that + * signs for itself (`signsItself`) is asked to hold the key of a provider + * that is named. */ function chosen( providers: SearchProvider[], - config: Record, + config: Readonly>, named: string | undefined, + signsItself: boolean, ): SearchProvider { const name = named ?? config.provider; - if (name !== undefined) { - const provider = providers.find((candidate) => candidate.name === name); - if (provider) return provider; + if (name === undefined) { + const first = providers.find((candidate) => hasKey(candidate, config)); + if (first) return first; throw new Error( - `${NAME}: no provider named ${JSON.stringify(name)}. The providers are ${providers.map((candidate) => candidate.name).join(", ")}.`, + `${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 provider = providers.find((candidate) => config[keyField(candidate)]); - if (provider) return provider; - 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 provider = providers.find((candidate) => candidate.name === name); + if (!provider) + throw new Error( + `${NAME}: no provider named ${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}. Set ${provider.env}, or search with a provider that has one.`, + ); + return provider; } /** `params` without the entries that have no value. */ @@ -224,18 +247,8 @@ export function webSearch( providers, ctx.connection.config, input.provider, + !ctx.credentials, ); - // A host that signs requests keeps the keys, so only a connection - // that signs for itself is asked for one here. - if (!ctx.credentials && !ctx.connection.config[keyField(provider)]) - throw new Error( - `${NAME}: no key for ${provider.name}. Set ${provider.env}, or search with a provider that has one.`, - ); - const method = ( - typeof provider.target === "function" - ? provider.target(ctx.connection.config) - : provider.target - ).methods[0]; const params = defined({ ...provider.params({ query: input.query, @@ -252,8 +265,10 @@ export function webSearch( { target: provider.name, path: provider.path, - method, - ...(method === "GET" ? { query: params } : { json: params }), + method: provider.method, + ...(provider.method === "GET" + ? { query: params } + : { json: params }), ...(provider.headers ? { headers: provider.headers } : {}), }, ); diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts index 000655e5..592d9e74 100644 --- a/packages/codemode-websearch/src/providers.ts +++ b/packages/codemode-websearch/src/providers.ts @@ -4,7 +4,7 @@ * pure functions; the plugin sends the request. */ -import { type CredentialTarget, httpsBase } from "@shiftlabs/codemode"; +import { httpsBase } from "@shiftlabs/codemode"; import * as t from "typebox"; /** A search as every provider receives it. */ @@ -28,6 +28,7 @@ export interface SearchResult { 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 code passes as `provider`, and the stem of the key's connection field. */ name: string; @@ -35,20 +36,20 @@ export interface SearchProvider { env: string; /** Where the key goes in a request: a header, or a query parameter. */ key: { header: string; prefix?: string } | { query: string }; - /** The one place the key may be sent. */ - target: - | CredentialTarget - | ((config: Record) => CredentialTarget); + /** + * 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; - /** The path of the search endpoint beneath the target. */ + /** 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. The target allows them. */ + /** Headers every request carries. */ headers?: Record; - /** - * The provider's parameters for a search, under the names its API gives - * them: the query of a GET, the JSON body of a POST. - */ + /** The provider's parameters for a search, under the names its API gives them. */ params(search: SearchRequest): Record; /** The results in the provider's answer. */ results(answer: unknown): SearchResult[]; @@ -114,7 +115,8 @@ export const parallel: SearchProvider = { name: "parallel", env: "PARALLEL_API_KEY", key: { header: "x-api-key" }, - target: { baseUrl: "https://api.parallel.ai/v1/", methods: ["POST"] }, + baseUrl: "https://api.parallel.ai/v1/", + method: "POST", path: "search", params: ({ query, numResults, country }) => ({ objective: query, @@ -137,7 +139,8 @@ export const brave: SearchProvider = { name: "brave", env: "BRAVE_API_KEY", key: { header: "X-Subscription-Token" }, - target: { baseUrl: "https://api.search.brave.com/res/v1/", methods: ["GET"] }, + baseUrl: "https://api.search.brave.com/res/v1/", + method: "GET", path: "web/search", params: ({ query, numResults, country, language }) => ({ q: query, @@ -160,7 +163,8 @@ export const exa: SearchProvider = { name: "exa", env: "EXA_API_KEY", key: { header: "x-api-key" }, - target: { baseUrl: "https://api.exa.ai/", methods: ["POST"] }, + baseUrl: "https://api.exa.ai/", + method: "POST", path: "search", params: ({ query, numResults, country }) => ({ query, @@ -185,7 +189,8 @@ export const you: SearchProvider = { name: "you", env: "YOU_API_KEY", key: { header: "X-API-Key" }, - target: { baseUrl: "https://ydc-index.io/v1/", methods: ["POST"] }, + baseUrl: "https://ydc-index.io/v1/", + method: "POST", path: "search", params: ({ query, numResults, country, language }) => ({ query, @@ -211,7 +216,8 @@ export const tavily: SearchProvider = { name: "tavily", env: "TAVILY_API_KEY", key: { header: "Authorization", prefix: "Bearer " }, - target: { baseUrl: "https://api.tavily.com/", methods: ["POST"] }, + baseUrl: "https://api.tavily.com/", + method: "POST", path: "search", // Tavily takes a country by its English name, so a country code is not sent. params: ({ query, numResults, language }) => ({ @@ -237,10 +243,8 @@ export const firecrawl: SearchProvider = { name: "firecrawl", env: "FIRECRAWL_API_KEY", key: { header: "Authorization", prefix: "Bearer " }, - target: (config) => ({ - baseUrl: httpsBase(config.firecrawlUrl ?? FIRECRAWL, "v2/"), - methods: ["POST"], - }), + baseUrl: (config) => httpsBase(config.firecrawlUrl ?? FIRECRAWL, "v2/"), + method: "POST", fields: { firecrawlUrl: t.Optional( t.String({ @@ -269,11 +273,8 @@ export const jina: SearchProvider = { name: "jina", env: "JINA_API_KEY", key: { header: "Authorization", prefix: "Bearer " }, - target: { - baseUrl: "https://s.jina.ai/", - methods: ["POST"], - allowedHeaders: ["X-Retain-Images"], - }, + baseUrl: "https://s.jina.ai/", + method: "POST", path: "", headers: { "X-Retain-Images": "none" }, params: ({ query, numResults, country, language }) => ({ @@ -296,7 +297,8 @@ export const linkup: SearchProvider = { name: "linkup", env: "LINKUP_API_KEY", key: { header: "Authorization", prefix: "Bearer " }, - target: { baseUrl: "https://api.linkup.so/v1/", methods: ["POST"] }, + baseUrl: "https://api.linkup.so/v1/", + method: "POST", path: "search", params: ({ query, numResults }) => ({ q: query, @@ -319,7 +321,8 @@ export const valyu: SearchProvider = { name: "valyu", env: "VALYU_API_KEY", key: { header: "X-API-Key" }, - target: { baseUrl: "https://api.valyu.ai/v1/", methods: ["POST"] }, + baseUrl: "https://api.valyu.ai/v1/", + method: "POST", path: "search", params: ({ query, numResults, country }) => ({ query, @@ -343,7 +346,8 @@ export const perplexity: SearchProvider = { name: "perplexity", env: "PERPLEXITY_API_KEY", key: { header: "Authorization", prefix: "Bearer " }, - target: { baseUrl: "https://api.perplexity.ai/", methods: ["POST"] }, + baseUrl: "https://api.perplexity.ai/", + method: "POST", path: "search", params: ({ query, numResults, country, language }) => ({ query, @@ -366,7 +370,8 @@ export const serper: SearchProvider = { name: "serper", env: "SERPER_API_KEY", key: { header: "X-API-KEY" }, - target: { baseUrl: "https://google.serper.dev/", methods: ["POST"] }, + baseUrl: "https://google.serper.dev/", + method: "POST", path: "search", params: ({ query, numResults, country, language }) => ({ q: query, @@ -391,7 +396,8 @@ export const serpapi: SearchProvider = { name: "serpapi", env: "SERPAPI_API_KEY", key: { query: "api_key" }, - target: { baseUrl: "https://serpapi.com/", methods: ["GET"] }, + baseUrl: "https://serpapi.com/", + method: "GET", path: "search.json", params: ({ query, numResults, country, language }) => ({ q: query, diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index 8e42ac88..cc078b4f 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -5,8 +5,11 @@ */ 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 { Codemode } from "@shiftlabs/codemode"; import { stubFetch } from "../../codemode/src/tests/helpers/plugin.js"; import { describePackage, pluginHarness } from "../../package-tests/harness.js"; import web, { @@ -536,7 +539,7 @@ describe("the provider a search uses", () => { const sent = provider({}); assert.match( await refused({ query: "q", provider: "altavista" }, ALL_KEYS), - /provider/, + /Invalid input for web\.search.*\/provider must be equal to one of the allowed values/, ); assert.match( await refused({ query: "q" }, { ...ALL_KEYS, provider: "altavista" }), @@ -577,9 +580,12 @@ describe("a provider's own parameters", () => { it("cannot name the parameter that carries the key", async () => { const sent = provider({}); - await refused( - { query: "q", provider: "serpapi", options: { api_key: "mine" } }, - ALL_KEYS, + assert.match( + await refused( + { query: "q", provider: "serpapi", options: { api_key: "mine" } }, + ALL_KEYS, + ), + /outside the approved policy/, ); assert.equal(sent.length, 0); }); @@ -596,7 +602,11 @@ describe("what a search accepts", () => { { query: "" }, { query: "q", depth: "deep" }, ]) - await refused(input, ALL_KEYS); + assert.match( + await refused(input, ALL_KEYS), + /Invalid input for web\.search/, + JSON.stringify(input), + ); assert.equal(sent.length, 0); }); }); @@ -631,9 +641,12 @@ describe("a Firecrawl of the host's own", () => { it("is refused over plain HTTP, where the key would travel in the clear", async () => { const sent = provider({}); - await refused( - { query: "q" }, - { firecrawlApiKey: "k", firecrawlUrl: "http://crawl.acme.example" }, + assert.match( + await refused( + { query: "q" }, + { firecrawlApiKey: "k", firecrawlUrl: "http://crawl.acme.example" }, + ), + /Missing or invalid authentication credentials/, ); assert.equal(sent.length, 0); }); @@ -644,7 +657,8 @@ describe("a provider a host adds", () => { name: "acme", env: "ACME_SEARCH_KEY", key: { header: "X-Acme-Key" }, - target: { baseUrl: "https://search.acme.example/api/", methods: ["GET"] }, + baseUrl: "https://search.acme.example/api/", + method: "GET", path: "find", params: ({ query, numResults }) => ({ q: query, n: numResults }), results: (answer) => @@ -673,6 +687,83 @@ describe("a provider a host adds", () => { }); }); +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: [web], + connections: [ + { name: "web", plugin: "web", 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 web.search({ 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: 5, + 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 and what a search sends it", () => { + const readme = readFileSync(join(PACKAGE, "README.md"), "utf8"); + const rows = [ + ...readme.matchAll( + /^\| `(\w+)` \| `(\w+)` \| (Yes|No) \| (Yes|No) \|$/gm, + ), + ].map(([, name, env, country, language]) => [name, env, country, language]); + assert.deepEqual( + rows, + PROVIDERS.map(({ name, env, params }) => { + const sent = JSON.stringify( + params({ query: "q", numResults: 5, country: "zz", language: "yy" }), + ).toLowerCase(); + return [ + name, + env, + sent.includes('"zz"') ? "Yes" : "No", + sent.includes('"yy"') ? "Yes" : "No", + ]; + }), + ); + }); +}); + describePackage(PACKAGE, { package: "@shiftlabs/codemode-websearch", plugin: "web", From 6203d8da268c7a1ac6aa4b87cc93d117469bef1f Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:14:57 +0200 Subject: [PATCH 03/14] fix: SerpAPI takes no number of results; the plugin caps results itself (SHFT-2967) --- packages/codemode-websearch/README.md | 2 +- packages/codemode-websearch/src/index.ts | 10 ++++++++-- packages/codemode-websearch/src/providers.ts | 4 ++-- .../tests/websearch.test.ts | 20 ++++++++++++++++++- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index e4da7dab..4e95f49b 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -40,7 +40,7 @@ codemode exec 'return await web.search({ query: "duckdb 1.4 release notes", numR | Input | Meaning | |---|---| | `query` | What to search for | -| `numResults` | How many results to return, from 1 to 20. The default is 5 | +| `numResults` | The most results to return, from 1 to 20. The default is 5 | | `country` | Two-letter country code to localize results, such as `de` | | `language` | Two-letter language code of the results, such as `de` | | `provider` | The provider to search with. The default is the connection's | diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts index dc72e86e..511c849d 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -249,10 +249,11 @@ export function webSearch( input.provider, !ctx.credentials, ); + const numResults = input.numResults ?? DEFAULT_RESULTS; const params = defined({ ...provider.params({ query: input.query, - numResults: input.numResults ?? DEFAULT_RESULTS, + numResults, country: input.country?.toLowerCase(), language: input.language?.toLowerCase(), }), @@ -272,7 +273,12 @@ export function webSearch( ...(provider.headers ? { headers: provider.headers } : {}), }, ); - return { provider: provider.name, results: provider.results(answer) }; + // 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), + }; }, }); }; diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts index 592d9e74..fef175fc 100644 --- a/packages/codemode-websearch/src/providers.ts +++ b/packages/codemode-websearch/src/providers.ts @@ -399,10 +399,10 @@ export const serpapi: SearchProvider = { baseUrl: "https://serpapi.com/", method: "GET", path: "search.json", - params: ({ query, numResults, country, language }) => ({ + // SerpAPI's Google search takes no number of results: it answers a page. + params: ({ query, country, language }) => ({ q: query, engine: "google", - num: numResults, gl: country, hl: language, }), diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index cc078b4f..1145be51 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -408,7 +408,7 @@ const CASES: Record< serpapi: { request: { method: "GET", - url: "https://serpapi.com/search.json?q=duckdb+release&engine=google&num=3&gl=de&hl=de&api_key=KEY-serpapi", + url: "https://serpapi.com/search.json?q=duckdb+release&engine=google&gl=de&hl=de&api_key=KEY-serpapi", key: "query", body: null, }, @@ -483,6 +483,24 @@ describe("web.search through each provider", () => { ); }); + 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, provider: "serpapi" }, + ALL_KEYS, + ); + 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" }); From ea664d28bba638e873cea0e07a34b18b7e75617e Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:17:30 +0200 Subject: [PATCH 04/14] docs: the result cap said the same way in the action, the types and the README (SHFT-2967) --- packages/codemode-websearch/README.md | 3 ++- packages/codemode-websearch/src/index.ts | 2 +- packages/codemode-websearch/src/providers.ts | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index 4e95f49b..00f316de 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -97,7 +97,7 @@ await web.search({ }); ``` -Name the provider in a call that passes `options`, because another provider gives its parameters other names. +Name the provider in a call that passes `options`, because another provider gives its parameters other names. A search still returns at most `numResults` results, whatever `options` asks the provider for. ## Configure the connection @@ -157,4 +157,5 @@ A provider's error text is not included in the message, because it can repeat th - Results are what the provider returns. Their length and freshness differ from provider to provider. - 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/src/index.ts b/packages/codemode-websearch/src/index.ts index 511c849d..98a8606b 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -187,7 +187,7 @@ export function webSearch( t.Integer({ minimum: 1, maximum: MAX_RESULTS, - description: `How many results to return, from 1 to ${MAX_RESULTS}. The default is ${DEFAULT_RESULTS}`, + description: `The most results to return, from 1 to ${MAX_RESULTS}. The default is ${DEFAULT_RESULTS}`, }), ), country: t.Optional( diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts index fef175fc..a8839739 100644 --- a/packages/codemode-websearch/src/providers.ts +++ b/packages/codemode-websearch/src/providers.ts @@ -10,6 +10,7 @@ import * as t from "typebox"; /** 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; /** Two-letter country code, lower case. */ country?: string; From 8b4094c2ae31456f3fa52e79246349bb3110f90d Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:26:38 +0200 Subject: [PATCH 05/14] feat!: web.search narrows by site and freshness for every provider; options is gone (SHFT-2967) --- packages/codemode-websearch/README.md | 62 ++--- packages/codemode-websearch/src/index.ts | 105 +++++++-- packages/codemode-websearch/src/providers.ts | 183 ++++++++++----- .../tests/websearch.test.ts | 212 +++++++++++++++--- 4 files changed, 440 insertions(+), 122 deletions(-) diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index 00f316de..e7e7e4e6 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -41,10 +41,12 @@ codemode exec 'return await web.search({ query: "duckdb 1.4 release notes", numR |---|---| | `query` | What to search for | | `numResults` | The most results to return, from 1 to 20. The default is 5 | -| `country` | Two-letter country code to localize results, such as `de` | -| `language` | Two-letter language code of the results, such as `de` | +| `country` | Two-letter country code to prefer results from, such as `de` | +| `language` | Two-letter language code to prefer results in, such as `de` | +| `includeDomains` | Return results from these sites only, such as `["duckdb.org"]` | +| `excludeDomains` | Leave results from these sites out | +| `freshness` | Return only pages published within the last `day`, `week`, `month`, or `year` | | `provider` | The provider to search with. The default is the connection's | -| `options` | Parameters of the provider's own search API | | Result field | Contents | |---|---| @@ -52,26 +54,26 @@ codemode exec 'return await web.search({ query: "duckdb 1.4 release notes", numR | `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 | -A provider that does not take a country or a language searches without it. +The inputs are the same for every provider, and a search names no parameter of a provider's own. ## Choose a provider A search uses the provider it names, else the connection's `provider`, else the first provider in this table that has a key: -| Provider | Key | Sends `country` | Sends `language` | -|---|---|---|---| -| `parallel` | `PARALLEL_API_KEY` | Yes | No | -| `brave` | `BRAVE_API_KEY` | Yes | Yes | -| `exa` | `EXA_API_KEY` | Yes | No | -| `you` | `YOU_API_KEY` | Yes | Yes | -| `tavily` | `TAVILY_API_KEY` | No | Yes | -| `firecrawl` | `FIRECRAWL_API_KEY` | Yes | No | -| `jina` | `JINA_API_KEY` | Yes | Yes | -| `linkup` | `LINKUP_API_KEY` | No | No | -| `valyu` | `VALYU_API_KEY` | Yes | No | -| `perplexity` | `PERPLEXITY_API_KEY` | Yes | Yes | -| `serper` | `SERPER_API_KEY` | Yes | Yes | -| `serpapi` | `SERPAPI_API_KEY` | Yes | Yes | +| 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` | No | 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 | Name a provider to search with it for one call: @@ -79,25 +81,23 @@ Name a provider to search with it for one call: const { results } = await web.search({ query: "duckdb", provider: "exa" }); ``` -## Pass a provider's own parameters +## Narrow a search -`options` holds parameters of the provider's search API, under the names that API gives them. They are added to the request, and replace what the search would send under the same name: +`includeDomains`, `excludeDomains`, and `freshness` are filters. Every result meets them, or the call is refused: ```js await web.search({ - query: "duckdb extensions", - provider: "exa", - options: { type: "deep", includeDomains: ["duckdb.org"] }, + query: "window functions", + includeDomains: ["duckdb.org", "postgresql.org"], + freshness: "year", }); -await web.search({ - query: "duckdb", - provider: "brave", - options: { freshness: "pw" }, -}); +await web.search({ query: "duckdb benchmarks", excludeDomains: ["medium.com"] }); ``` -Name the provider in a call that passes `options`, because another provider gives its parameters other names. A search still returns at most `numResults` results, whatever `options` asks the provider for. +A site is a hostname, without `https://` or a path, and a search takes up to 20. 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. ## Configure the connection @@ -148,6 +148,7 @@ The list's order is the order a provider is chosen in. Parameters go in the quer |---|---| | No provider has a key | The call rejects and names the environment variables | | The provider named has no key | The call rejects and names its environment variable | +| The provider cannot apply a filter | The call rejects and names the providers that can | | The provider refuses the request | The call rejects with `web.: request failed (HTTP )` | | The provider answers without results | Returns `results: []` | @@ -156,6 +157,9 @@ A provider's error text is not included in the message, because it can repeat th ## Understand the limits - Results are what the provider returns. Their length and freshness differ from provider to provider. +- Jina applies no filter, so a search through it with `includeDomains`, `excludeDomains`, or `freshness` is refused. +- Brave, Serper, and SerpAPI filter by site with `site:` operators added to the query. +- `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/src/index.ts b/packages/codemode-websearch/src/index.ts index 98a8606b..ab4b0d4f 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -20,15 +20,32 @@ import { } from "@shiftlabs/codemode"; import { packageVersion } from "@shiftlabs/codemode/utils/cli"; import * as t from "typebox"; -import { PROVIDERS, type SearchProvider } from "./providers.js"; +import { + type Freshness, + PROVIDERS, + type SearchProvider, + type SearchRequest, +} from "./providers.js"; export * from "./providers.js"; const NAME = "web"; const DEFAULT_RESULTS = 5; const MAX_RESULTS = 20; +const MAX_DOMAINS = 20; /** 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 provider applies one or the search is refused. */ +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 { @@ -123,6 +140,31 @@ function chosen( return provider; } +/** 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); +} + +/** + * 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 } : {}), + }), + ), + ); +} + /** `params` without the entries that have no value. */ function defined(params: Record): Record { return Object.fromEntries( @@ -194,14 +236,14 @@ export function webSearch( t.String({ pattern: "^[A-Za-z]{2}$", description: - "Two-letter country code to localize results, such as us, gb, de", + "Two-letter country code to prefer results from, such as us, gb, de. A provider that cannot localize searches without it", }), ), language: t.Optional( t.String({ pattern: "^[A-Za-z]{2}$", description: - "Two-letter language code of the results, such as en, es, fr", + "Two-letter language code to prefer results in, such as en, es, fr. A provider that cannot searches without it", }), ), provider: t.Optional( @@ -211,10 +253,27 @@ export function webSearch( "The provider to search with. The default is the connection's", }), ), - options: t.Optional( - t.Record(t.String(), t.Unknown(), { + includeDomains: t.Optional( + t.Array(t.String({ pattern: DOMAIN }), { + minItems: 1, + maxItems: MAX_DOMAINS, description: - "Parameters of the provider's own search API, under the names it gives them. They replace what the search would send under the same name", + 'Return results from these sites only, 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, 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", }), ), }, @@ -249,16 +308,32 @@ export function webSearch( input.provider, !ctx.credentials, ); + if (input.includeDomains && input.excludeDomains) + throw new Error( + `${NAME}: set includeDomains or excludeDomains, not both.`, + ); const numResults = input.numResults ?? DEFAULT_RESULTS; - const params = defined({ - ...provider.params({ - query: input.query, - numResults, - country: input.country?.toLowerCase(), - language: input.language?.toLowerCase(), - }), - ...input.options, - }); + const freshness = input.freshness as Freshness | undefined; + const search: SearchRequest = { + query: input.query, + numResults, + country: input.country?.toLowerCase(), + language: input.language?.toLowerCase(), + includeDomains: input.includeDomains, + excludeDomains: input.excludeDomains, + freshness, + publishedAfter: freshness && dayBefore(FRESHNESS_DAYS[freshness]), + }; + const refused = unapplied(provider, search); + if (refused.length) { + const able = providers + .filter((candidate) => !unapplied(candidate, search).length) + .map((candidate) => candidate.name); + throw new Error( + `${NAME}: ${provider.name} cannot filter by ${refused.join(" or ")}. Search without it, or with one of: ${able.join(", ")}.`, + ); + } + const params = defined(provider.params(search)); const answer = await credentialJson( ctx, credential, diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts index a8839739..13584493 100644 --- a/packages/codemode-websearch/src/providers.ts +++ b/packages/codemode-websearch/src/providers.ts @@ -7,15 +7,26 @@ import { httpsBase } from "@shiftlabs/codemode"; import * as t from "typebox"; +/** 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; - /** Two-letter country code, lower case. */ + /** Two-letter country code, lower case. A preference: a provider without one searches without it. */ country?: string; - /** Two-letter language code, lower case. */ + /** Two-letter language code, lower case. A preference, like `country`. */ language?: string; + /** Hostnames to return results from, and no other. Never set with `excludeDomains`. */ + includeDomains?: string[]; + /** Hostnames 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. */ @@ -50,7 +61,11 @@ export interface SearchProvider { path: string; /** Headers every request carries. */ headers?: Record; - /** The provider's parameters for a search, under the names its API gives them. */ + /** + * 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 refuses a search that sets it. + */ params(search: SearchRequest): Record; /** The results in the provider's answer. */ results(answer: unknown): SearchResult[]; @@ -112,6 +127,38 @@ function knowledgeGraph(graph: unknown): SearchResult[] { const upper = (code?: string) => code?.toUpperCase(); +/** `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", @@ -119,11 +166,19 @@ export const parallel: SearchProvider = { baseUrl: "https://api.parallel.ai/v1/", method: "POST", path: "search", - params: ({ query, numResults, country }) => ({ - objective: query, - search_queries: [query], + params: (search) => ({ + objective: search.query, + search_queries: [search.query], mode: "fast", - advanced_settings: { max_results: numResults, location: country }, + advanced_settings: { + max_results: search.numResults, + location: search.country, + source_policy: some({ + include_domains: search.includeDomains, + exclude_domains: search.excludeDomains, + after_date: search.publishedAfter, + }), + }, }), results: (answer) => list(object(answer).results).map((r) => @@ -143,11 +198,12 @@ export const brave: SearchProvider = { baseUrl: "https://api.search.brave.com/res/v1/", method: "GET", path: "web/search", - params: ({ query, numResults, country, language }) => ({ - q: query, - count: numResults, - country: upper(country), - search_lang: language, + params: (search) => ({ + q: withSites(search), + count: search.numResults, + country: upper(search.country), + search_lang: search.language, + freshness: search.freshness && `p${search.freshness[0]}`, }), results: (answer) => list(object(object(answer).web).results).map((r) => @@ -167,12 +223,16 @@ export const exa: SearchProvider = { baseUrl: "https://api.exa.ai/", method: "POST", path: "search", - params: ({ query, numResults, country }) => ({ - query, - numResults, + params: (search) => ({ + query: search.query, + numResults: search.numResults, type: "auto", contents: { text: { maxCharacters: 3000 }, highlights: true }, - userLocation: upper(country), + userLocation: upper(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) => @@ -193,11 +253,14 @@ export const you: SearchProvider = { baseUrl: "https://ydc-index.io/v1/", method: "POST", path: "search", - params: ({ query, numResults, country, language }) => ({ - query, - count: numResults, - country: upper(country), - language: upper(language), + params: (search) => ({ + query: search.query, + count: search.numResults, + country: upper(search.country), + language: upper(search.language), + include_domains: search.includeDomains, + exclude_domains: search.excludeDomains, + freshness: search.freshness, }), results: (answer) => list(object(object(answer).results).web).map((r) => @@ -221,11 +284,14 @@ export const tavily: SearchProvider = { method: "POST", path: "search", // Tavily takes a country by its English name, so a country code is not sent. - params: ({ query, numResults, language }) => ({ - query, - max_results: numResults, + params: (search) => ({ + query: search.query, + max_results: search.numResults, search_depth: "basic", - language, + language: search.language, + include_domains: search.includeDomains, + exclude_domains: search.excludeDomains, + time_range: search.freshness, }), results: (answer) => list(object(answer).results).map((r) => @@ -255,10 +321,13 @@ export const firecrawl: SearchProvider = { ), }, path: "search", - params: ({ query, numResults, country }) => ({ - query, - limit: numResults, - country: upper(country), + params: (search) => ({ + query: search.query, + limit: search.numResults, + country: upper(search.country), + includeDomains: search.includeDomains, + excludeDomains: search.excludeDomains, + tbs: googleRecency(search.freshness), }), results: (answer) => list(object(object(answer).data).web).map((r) => @@ -278,6 +347,7 @@ export const jina: SearchProvider = { 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, @@ -301,12 +371,15 @@ export const linkup: SearchProvider = { baseUrl: "https://api.linkup.so/v1/", method: "POST", path: "search", - params: ({ query, numResults }) => ({ - q: query, + params: (search) => ({ + q: search.query, depth: "standard", outputType: "searchResults", includeImages: false, - maxResults: numResults, + maxResults: search.numResults, + includeDomains: search.includeDomains, + excludeDomains: search.excludeDomains, + fromDate: search.publishedAfter, }), results: (answer) => list(object(answer).results).map((r) => @@ -325,11 +398,14 @@ export const valyu: SearchProvider = { baseUrl: "https://api.valyu.ai/v1/", method: "POST", path: "search", - params: ({ query, numResults, country }) => ({ - query, + params: (search) => ({ + query: search.query, search_type: "all", - max_num_results: numResults, - country_code: upper(country), + max_num_results: search.numResults, + country_code: upper(search.country), + included_sources: search.includeDomains, + excluded_sources: search.excludeDomains, + start_date: search.publishedAfter, }), results: (answer) => list(object(answer).results).map((r) => @@ -350,11 +426,16 @@ export const perplexity: SearchProvider = { baseUrl: "https://api.perplexity.ai/", method: "POST", path: "search", - params: ({ query, numResults, country, language }) => ({ - query, - max_results: numResults, - country: upper(country), - search_language_filter: language ? [language] : undefined, + params: (search) => ({ + query: search.query, + max_results: search.numResults, + country: upper(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) => @@ -374,11 +455,12 @@ export const serper: SearchProvider = { baseUrl: "https://google.serper.dev/", method: "POST", path: "search", - params: ({ query, numResults, country, language }) => ({ - q: query, - num: numResults, - gl: country, - hl: language, + params: (search) => ({ + q: withSites(search), + num: search.numResults, + gl: search.country, + hl: search.language, + tbs: googleRecency(search.freshness), }), results: (answer) => [ ...knowledgeGraph(object(answer).knowledgeGraph), @@ -401,11 +483,12 @@ export const serpapi: SearchProvider = { method: "GET", path: "search.json", // SerpAPI's Google search takes no number of results: it answers a page. - params: ({ query, country, language }) => ({ - q: query, + params: (search) => ({ + q: withSites(search), engine: "google", - gl: country, - hl: language, + gl: search.country, + hl: search.language, + tbs: googleRecency(search.freshness), }), results: (answer) => [ ...knowledgeGraph(object(answer).knowledge_graph), diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index 1145be51..787c409f 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -9,6 +9,7 @@ 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"; @@ -567,50 +568,191 @@ describe("the provider a search uses", () => { }); }); -describe("a provider's own parameters", () => { - it("are sent under its names, over what the search would send", async () => { - const sent = provider({ results: [] }); - await search( - { - query: "q", - provider: "exa", - options: { type: "deep", includeDomains: ["duckdb.org"] }, +/** 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: 5, + source_policy: { + include_domains: ["a.example", "b.example"], + after_date: "WEEK_AGO", + }, }, - ALL_KEYS, + }, + without: { + advanced_settings: { + max_results: 5, + 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"), ); - assert.deepEqual(sent[0].body, { - query: "q", - numResults: 5, - type: "deep", - contents: { text: { maxCharacters: 3000 }, highlights: true }, - includeDomains: ["duckdb.org"], - }); }); - it("go in the query of a provider that is searched with GET", async () => { - const sent = provider({ web: { results: [] } }); + 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", provider: name }, ALL_KEYS); + await search( + { + query: "q", + provider: name, + includeDomains: ["a.example", "b.example"], + freshness: "week", + }, + ALL_KEYS, + ); + await search( + { query: "q", provider: name, excludeDomains: ["c.example"] }, + ALL_KEYS, + ); + 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", provider: "brave", options: { freshness: "pw" } }, + { query: "q", provider: "brave", includeDomains: ["a.example"] }, ALL_KEYS, ); - assert.equal(new URL(sent[0].url).searchParams.get("freshness"), "pw"); + assert.equal( + new URL(sent[0].url).searchParams.get("q"), + "q site:a.example", + ); }); - it("cannot name the parameter that carries the key", async () => { + it("refuses a filter the provider cannot apply, and names those that can", async () => { + const sent = provider({}); + assert.equal( + ( + await refused( + { query: "q", provider: "jina", freshness: "day" }, + ALL_KEYS, + ) + ).split("\n")[0], + "Error: web: jina cannot filter by freshness. Search without it, or with one of: parallel, brave, exa, you, tavily, firecrawl, linkup, valyu, perplexity, serper, serpapi.", + ); + assert.match( + await refused( + { + query: "q", + provider: "jina", + includeDomains: ["a.example"], + freshness: "day", + }, + ALL_KEYS, + ), + /jina cannot filter by includeDomains or freshness\./, + ); + 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", provider: "serpapi", options: { api_key: "mine" } }, + { + query: "q", + includeDomains: ["a.example"], + excludeDomains: ["b.example"], + }, ALL_KEYS, ), - /outside the approved policy/, + /web: set includeDomains or excludeDomains, not both\./, ); assert.equal(sent.length, 0); }); }); describe("what a search accepts", () => { - it("refuses a number of results outside 1 to 20, and a country that is not a code", async () => { + it("refuses what is not a search: a number of results outside 1 to 20, a country that is not a code, a site that is not a hostname, an input it does not have", async () => { const sent = provider({}); for (const input of [ { query: "q", numResults: 0 }, @@ -619,6 +761,11 @@ describe("what a search accepts", () => { { query: "q", country: "germany" }, { 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), @@ -758,24 +905,33 @@ describe("a host that keeps the keys", () => { }); describe("the README", () => { - it("lists the providers in their order, with each key and what a search sends it", () => { + 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) \|$/gm, + /^\| `(\w+)` \| `(\w+)` \| (Yes|No) \| (Yes|No) \| (Yes|No) \|$/gm, ), - ].map(([, name, env, country, language]) => [name, env, country, language]); + ].map(([, ...row]) => row); assert.deepEqual( rows, PROVIDERS.map(({ name, env, params }) => { const sent = JSON.stringify( - params({ query: "q", numResults: 5, country: "zz", language: "yy" }), + params({ + query: "q", + numResults: 5, + country: "zz", + language: "yy", + includeDomains: ["xx.example"], + freshness: "week", + publishedAfter: "2026-01-01", + }), ).toLowerCase(); return [ name, env, sent.includes('"zz"') ? "Yes" : "No", sent.includes('"yy"') ? "Yes" : "No", + sent.includes("xx.example") ? "Yes" : "No", ]; }), ); From c8c3e364627c39d63589a8bfd7fe53c7a3e78c2f Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:32:28 +0200 Subject: [PATCH 06/14] feat: one form for each input of web.search, turned into what each provider documents (SHFT-2967) --- packages/codemode-websearch/README.md | 29 ++- packages/codemode-websearch/src/codes.ts | 235 ++++++++++++++++++ packages/codemode-websearch/src/index.ts | 52 +++- packages/codemode-websearch/src/providers.ts | 75 ++++-- .../tests/websearch.test.ts | 106 ++++++-- 5 files changed, 444 insertions(+), 53 deletions(-) create mode 100644 packages/codemode-websearch/src/codes.ts diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index e7e7e4e6..74ca5563 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -40,14 +40,27 @@ codemode exec 'return await web.search({ query: "duckdb 1.4 release notes", numR | Input | Meaning | |---|---| | `query` | What to search for | -| `numResults` | The most results to return, from 1 to 20. The default is 5 | -| `country` | Two-letter country code to prefer results from, such as `de` | -| `language` | Two-letter language code to prefer results in, such as `de` | -| `includeDomains` | Return results from these sites only, such as `["duckdb.org"]` | +| `numResults` | The most results to return. The default is 5 | +| `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 within the last `day`, `week`, `month`, or `year` | +| `freshness` | Return only pages published this recently | | `provider` | The provider to search with. The default is the connection's | +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 in upper case | `"DE"` | +| `language` | An ISO 639-1 code in lower case | `"de"` | +| `includeDomains`, `excludeDomains` | 1 to 20 hostnames in lower case, without `https://` or a path | `["duckdb.org"]` | +| `freshness` | `"day"`, `"week"`, `"month"`, or `"year"` | `"week"` | + +Codemode turns each value into what the provider's API takes: `"DE"` reaches Parallel as `de`, Tavily as `germany`, and Brave as `DE`. + | Result field | Contents | |---|---| | `title`, `url` | The page | @@ -66,7 +79,7 @@ A search uses the provider it names, else the connection's `provider`, else the | `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` | No | 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 | @@ -95,9 +108,9 @@ await web.search({ await web.search({ query: "duckdb benchmarks", excludeDomains: ["medium.com"] }); ``` -A site is a hostname, without `https://` or a path, and a search takes up to 20. Set sites to search or sites to leave out, not both. +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. +`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 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 index ab4b0d4f..237eac01 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -33,6 +33,8 @@ const NAME = "web"; const DEFAULT_RESULTS = 5; 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. */ @@ -44,8 +46,8 @@ const FRESHNESS_DAYS: Record = { }; /** The inputs that narrow a search. A provider applies one or the search is refused. */ 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-]+)+$"; +/** A hostname in lower case, such as `duckdb.org`: no scheme, path or spaces. */ +const DOMAIN = "^[a-z0-9-]+(\\.[a-z0-9-]+)+$"; /** The connection field that holds a provider's key. */ function keyField(provider: SearchProvider): string { @@ -140,6 +142,31 @@ function chosen( return provider; } +const REGION_NAMES = new Intl.DisplayNames(["en"], { + type: "region", + fallback: "none", +}); +const LANGUAGE_NAMES = new Intl.DisplayNames(["en"], { + type: "language", + fallback: "none", +}); + +/** Refuse a code in the right form that names no country. */ +function checkCountry(code: string): void { + if (!REGION_NAMES.of(code)) + throw new Error( + `${NAME}: ${code} is not a country. Pass an ISO 3166-1 alpha-2 code, such as US.`, + ); +} + +/** Refuse a code in the right form that names no language. */ +function checkLanguage(code: string): void { + if (!LANGUAGE_NAMES.of(code)) + throw new Error( + `${NAME}: ${code} is not a language. Pass an ISO 639-1 code, such as en.`, + ); +} + /** 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); @@ -223,7 +250,8 @@ export function webSearch( { query: t.String({ minLength: 1, - description: "What to search for. Be specific and descriptive", + maxLength: MAX_QUERY, + description: `What to search for, in up to ${MAX_QUERY} characters. Be specific and descriptive`, }), numResults: t.Optional( t.Integer({ @@ -234,16 +262,16 @@ export function webSearch( ), country: t.Optional( t.String({ - pattern: "^[A-Za-z]{2}$", + pattern: "^[A-Z]{2}$", description: - "Two-letter country code to prefer results from, such as us, gb, de. A provider that cannot localize searches without it", + "Country to prefer results from: an ISO 3166-1 alpha-2 code in upper case, such as US, GB, DE", }), ), language: t.Optional( t.String({ - pattern: "^[A-Za-z]{2}$", + pattern: "^[a-z]{2}$", description: - "Two-letter language code to prefer results in, such as en, es, fr. A provider that cannot searches without it", + "Language to prefer results in: an ISO 639-1 code in lower case, such as en, es, fr", }), ), provider: t.Optional( @@ -258,7 +286,7 @@ export function webSearch( minItems: 1, maxItems: MAX_DOMAINS, description: - 'Return results from these sites only, such as ["duckdb.org", "github.com"]. Not together with excludeDomains', + 'Return results from these sites only: hostnames in lower case, without https:// or a path, such as ["duckdb.org", "github.com"]. Not together with excludeDomains', }), ), excludeDomains: t.Optional( @@ -266,7 +294,7 @@ export function webSearch( minItems: 1, maxItems: MAX_DOMAINS, description: - 'Leave results from these sites out, such as ["pinterest.com"]. Not together with includeDomains', + 'Leave results from these sites out: hostnames in the same form, such as ["pinterest.com"]. Not together with includeDomains', }), ), freshness: t.Optional( @@ -312,13 +340,15 @@ export function webSearch( throw new Error( `${NAME}: set includeDomains or excludeDomains, not both.`, ); + if (input.country) checkCountry(input.country); + if (input.language) checkLanguage(input.language); const numResults = input.numResults ?? DEFAULT_RESULTS; const freshness = input.freshness as Freshness | undefined; const search: SearchRequest = { query: input.query, numResults, - country: input.country?.toLowerCase(), - language: input.language?.toLowerCase(), + country: input.country, + language: input.language, includeDomains: input.includeDomains, excludeDomains: input.excludeDomains, freshness, diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts index 13584493..db983f60 100644 --- a/packages/codemode-websearch/src/providers.ts +++ b/packages/codemode-websearch/src/providers.ts @@ -6,6 +6,16 @@ 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"; @@ -15,9 +25,12 @@ export interface SearchRequest { query: string; /** The most results wanted. The plugin returns no more, whatever a provider answers. */ numResults: number; - /** Two-letter country code, lower case. A preference: a provider without one searches without it. */ + /** + * 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; - /** Two-letter language code, lower case. A preference, like `country`. */ + /** ISO 639-1 language code, lower case, such as `en`. A preference, like `country`. */ language?: string; /** Hostnames to return results from, and no other. Never set with `excludeDomains`. */ includeDomains?: string[]; @@ -125,7 +138,31 @@ function knowledgeGraph(graph: unknown): SearchResult[] { : []; } -const upper = (code?: string) => code?.toUpperCase(); +/** `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 { @@ -172,7 +209,7 @@ export const parallel: SearchProvider = { mode: "fast", advanced_settings: { max_results: search.numResults, - location: search.country, + location: search.country?.toLowerCase(), source_policy: some({ include_domains: search.includeDomains, exclude_domains: search.excludeDomains, @@ -201,8 +238,8 @@ export const brave: SearchProvider = { params: (search) => ({ q: withSites(search), count: search.numResults, - country: upper(search.country), - search_lang: search.language, + country: listed(BRAVE_COUNTRIES, search.country), + search_lang: braveLanguage(search.language), freshness: search.freshness && `p${search.freshness[0]}`, }), results: (answer) => @@ -228,7 +265,7 @@ export const exa: SearchProvider = { numResults: search.numResults, type: "auto", contents: { text: { maxCharacters: 3000 }, highlights: true }, - userLocation: upper(search.country), + userLocation: search.country, includeDomains: search.includeDomains, excludeDomains: search.excludeDomains, startPublishedDate: @@ -256,8 +293,8 @@ export const you: SearchProvider = { params: (search) => ({ query: search.query, count: search.numResults, - country: upper(search.country), - language: upper(search.language), + country: listed(YOU_COUNTRIES, search.country), + language: braveLanguage(search.language)?.toUpperCase(), include_domains: search.includeDomains, exclude_domains: search.excludeDomains, freshness: search.freshness, @@ -283,11 +320,11 @@ export const tavily: SearchProvider = { baseUrl: "https://api.tavily.com/", method: "POST", path: "search", - // Tavily takes a country by its English name, so a country code is not sent. 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, @@ -324,7 +361,7 @@ export const firecrawl: SearchProvider = { params: (search) => ({ query: search.query, limit: search.numResults, - country: upper(search.country), + country: search.country, includeDomains: search.includeDomains, excludeDomains: search.excludeDomains, tbs: googleRecency(search.freshness), @@ -351,8 +388,8 @@ export const jina: SearchProvider = { params: ({ query, numResults, country, language }) => ({ q: query, num: numResults, - gl: country, - hl: language, + gl: googleCountry(country), + hl: googleLanguage(language), }), results: (answer) => list(object(answer).data).map((r) => @@ -402,7 +439,7 @@ export const valyu: SearchProvider = { query: search.query, search_type: "all", max_num_results: search.numResults, - country_code: upper(search.country), + country_code: listed(YOU_COUNTRIES, search.country), included_sources: search.includeDomains, excluded_sources: search.excludeDomains, start_date: search.publishedAfter, @@ -429,7 +466,7 @@ export const perplexity: SearchProvider = { params: (search) => ({ query: search.query, max_results: search.numResults, - country: upper(search.country), + 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: @@ -458,8 +495,8 @@ export const serper: SearchProvider = { params: (search) => ({ q: withSites(search), num: search.numResults, - gl: search.country, - hl: search.language, + gl: googleCountry(search.country), + hl: googleLanguage(search.language), tbs: googleRecency(search.freshness), }), results: (answer) => [ @@ -486,8 +523,8 @@ export const serpapi: SearchProvider = { params: (search) => ({ q: withSites(search), engine: "google", - gl: search.country, - hl: search.language, + gl: googleCountry(search.country), + hl: googleLanguage(search.language), tbs: googleRecency(search.freshness), }), results: (answer) => [ diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index 787c409f..2ba14e73 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -239,6 +239,7 @@ const CASES: Record< query: "duckdb release", max_results: 3, search_depth: "basic", + country: "germany", language: "de", }, }, @@ -751,14 +752,94 @@ describe("the filters of a search", () => { }); }); +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", provider: name, ...input }, ALL_KEYS); + 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: 5, location: "gb" }, + brave: { q: "q", count: "5", country: "GB", search_lang: "pt-br" }, + you: { query: "q", count: 5, country: "GB", language: "PT-BR" }, + tavily: { + query: "q", + max_results: 5, + search_depth: "basic", + country: "united kingdom", + language: "pt", + }, + serper: { q: "q", num: 5, gl: "gb", hl: "pt" }, + }, + ); + }); + + 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: "5" }); + assert.deepEqual(await sentFor("you", codes), { query: "q", count: 5 }); + assert.deepEqual(await sentFor("valyu", codes), { + query: "q", + search_type: "all", + max_num_results: 5, + }); + assert.deepEqual(await sentFor("serpapi", codes), { + q: "q", + engine: "google", + gl: "il", + }); + assert.deepEqual(await sentFor("perplexity", codes), { + query: "q", + max_results: 5, + country: "IL", + search_language_filter: ["bo"], + }); + }); + + it("are refused when they name no country or language", async () => { + const sent = provider({}); + assert.match( + await refused({ query: "q", country: "XX" }, ALL_KEYS), + /web: 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), + /web: 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 what is not a search: a number of results outside 1 to 20, a country that is not a code, a site that is not a hostname, an input it does not have", async () => { + 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", country: "us" }, + { query: "q", language: "EN" }, + { query: "q", language: "eng" }, + { query: "x".repeat(401) }, + { query: "q", includeDomains: ["DuckDB.org"] }, { query: "" }, { query: "q", depth: "deep" }, { query: "q", options: { freshness: "pw" } }, @@ -915,23 +996,18 @@ describe("the README", () => { assert.deepEqual( rows, PROVIDERS.map(({ name, env, params }) => { - const sent = JSON.stringify( - params({ - query: "q", - numResults: 5, - country: "zz", - language: "yy", - includeDomains: ["xx.example"], - freshness: "week", - publishedAfter: "2026-01-01", - }), - ).toLowerCase(); + const plain = { query: "q", numResults: 5 }; + const changes = (more: object) => + JSON.stringify(params({ ...plain, ...more })) === + JSON.stringify(params(plain)) + ? "No" + : "Yes"; return [ name, env, - sent.includes('"zz"') ? "Yes" : "No", - sent.includes('"yy"') ? "Yes" : "No", - sent.includes("xx.example") ? "Yes" : "No", + changes({ country: "DE" }), + changes({ language: "de" }), + changes({ includeDomains: ["a.example"] }), ]; }), ); From d1503c043d7555704207ce1074b7525ae88415eb Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:34:41 +0200 Subject: [PATCH 07/14] feat: web.search returns up to 10 results by default (SHFT-2967) --- packages/codemode-websearch/README.md | 2 +- packages/codemode-websearch/src/index.ts | 2 +- .../tests/websearch.test.ts | 28 +++++++++---------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index 74ca5563..8f57d6ec 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -40,7 +40,7 @@ codemode exec 'return await web.search({ query: "duckdb 1.4 release notes", numR | Input | Meaning | |---|---| | `query` | What to search for | -| `numResults` | The most results to return. The default is 5 | +| `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 | diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts index 237eac01..223ac08a 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -30,7 +30,7 @@ import { export * from "./providers.js"; const NAME = "web"; -const DEFAULT_RESULTS = 5; +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. */ diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index 2ba14e73..de7a28b4 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -481,7 +481,7 @@ describe("web.search through each provider", () => { assert.deepEqual(found, { provider: "brave", results: [] }); assert.equal( sent[0].url, - "https://api.search.brave.com/res/v1/web/search?q=plain&count=5", + "https://api.search.brave.com/res/v1/web/search?q=plain&count=10", ); }); @@ -582,7 +582,7 @@ const FILTERED: Record = { parallel: { only: { advanced_settings: { - max_results: 5, + max_results: 10, source_policy: { include_domains: ["a.example", "b.example"], after_date: "WEEK_AGO", @@ -591,7 +591,7 @@ const FILTERED: Record = { }, without: { advanced_settings: { - max_results: 5, + max_results: 10, source_policy: { exclude_domains: ["c.example"] }, }, }, @@ -774,17 +774,17 @@ describe("a country and a language", () => { serper: await sentFor("serper", codes), }, { - parallel: { max_results: 5, location: "gb" }, - brave: { q: "q", count: "5", country: "GB", search_lang: "pt-br" }, - you: { query: "q", count: 5, country: "GB", language: "PT-BR" }, + 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: 5, + max_results: 10, search_depth: "basic", country: "united kingdom", language: "pt", }, - serper: { q: "q", num: 5, gl: "gb", hl: "pt" }, + serper: { q: "q", num: 10, gl: "gb", hl: "pt" }, }, ); }); @@ -793,12 +793,12 @@ describe("a country and a language", () => { // 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: "5" }); - assert.deepEqual(await sentFor("you", codes), { query: "q", count: 5 }); + 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: 5, + max_num_results: 10, }); assert.deepEqual(await sentFor("serpapi", codes), { q: "q", @@ -807,7 +807,7 @@ describe("a country and a language", () => { }); assert.deepEqual(await sentFor("perplexity", codes), { query: "q", - max_results: 5, + max_results: 10, country: "IL", search_language_filter: ["bo"], }); @@ -927,7 +927,7 @@ describe("a provider a host adds", () => { provider: "acme", results: [{ title: "One", url: "https://a.example", content: "" }], }); - assert.equal(sent[0].url, "https://search.acme.example/api/find?q=q&n=5"); + 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")); }); @@ -972,7 +972,7 @@ describe("a host that keeps the keys", () => { }, body: JSON.stringify({ query: "q", - numResults: 5, + numResults: 10, type: "auto", contents: { text: { maxCharacters: 3000 }, highlights: true }, }), From f54cca354a87e0d086f388226a442dc10b984d39 Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:37:18 +0200 Subject: [PATCH 08/14] refactor: one check for a country or language code; a test for language variants (SHFT-2967) --- packages/codemode-websearch/README.md | 6 +-- packages/codemode-websearch/src/index.ts | 45 ++++++++++--------- .../tests/websearch.test.ts | 13 ++++++ 3 files changed, 38 insertions(+), 26 deletions(-) diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index 8f57d6ec..838d79d5 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -59,7 +59,7 @@ Each input has one form, and a value in another form is refused before any reque | `includeDomains`, `excludeDomains` | 1 to 20 hostnames in lower case, without `https://` or a path | `["duckdb.org"]` | | `freshness` | `"day"`, `"week"`, `"month"`, or `"year"` | `"week"` | -Codemode turns each value into what the provider's API takes: `"DE"` reaches Parallel as `de`, Tavily as `germany`, and Brave as `DE`. +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 | |---|---| @@ -67,8 +67,6 @@ Codemode turns each value into what the provider's API takes: `"DE"` reaches Par | `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 | -The inputs are the same for every provider, and a search names no parameter of a provider's own. - ## Choose a provider A search uses the provider it names, else the connection's `provider`, else the first provider in this table that has a key: @@ -171,7 +169,7 @@ A provider's error text is not included in the message, because it can repeat th - Results are what the provider returns. Their length and freshness differ from provider to provider. - Jina applies no filter, so a search through it with `includeDomains`, `excludeDomains`, or `freshness` is refused. -- Brave, Serper, and SerpAPI filter by site with `site:` operators added to the query. +- 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. diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts index 223ac08a..b5b1ec5c 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -142,28 +142,29 @@ function chosen( return provider; } -const REGION_NAMES = new Intl.DisplayNames(["en"], { - type: "region", - fallback: "none", -}); -const LANGUAGE_NAMES = new Intl.DisplayNames(["en"], { - type: "language", - fallback: "none", -}); - -/** Refuse a code in the right form that names no country. */ -function checkCountry(code: string): void { - if (!REGION_NAMES.of(code)) - throw new Error( - `${NAME}: ${code} is not a country. Pass an ISO 3166-1 alpha-2 code, such as US.`, - ); -} +/** 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 language. */ -function checkLanguage(code: string): void { - if (!LANGUAGE_NAMES.of(code)) +/** 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 language. Pass an ISO 639-1 code, such as en.`, + `${NAME}: ${code} is not a ${kind}. Pass an ${standard} code, such as ${example}.`, ); } @@ -340,8 +341,8 @@ export function webSearch( throw new Error( `${NAME}: set includeDomains or excludeDomains, not both.`, ); - if (input.country) checkCountry(input.country); - if (input.language) checkLanguage(input.language); + checkCode("country", input.country); + checkCode("language", input.language); const numResults = input.numResults ?? DEFAULT_RESULTS; const freshness = input.freshness as Freshness | undefined; const search: SearchRequest = { diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index de7a28b4..b56c0234 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -789,6 +789,19 @@ describe("a country and a language", () => { ); }); + 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. From 285515725194e7d4537c02f99c857d59eea4e6f7 Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:40:30 +0200 Subject: [PATCH 09/14] feat!: the plugin is websearch and its action is query (SHFT-2967) --- README.md | 2 +- packages/codemode-websearch/README.md | 22 ++++---- packages/codemode-websearch/src/index.ts | 14 ++--- .../tests/websearch.test.ts | 51 +++++++++++-------- 4 files changed, 48 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 5cd42a34..f4e02b55 100644 --- a/README.md +++ b/README.md @@ -67,7 +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 `web` plugin as a package, published as `@shiftlabs/codemode-websearch` | +| [`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/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index 838d79d5..fdbb6f34 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -1,8 +1,8 @@ # codemode-websearch -A [codemode](../../README.md) package with one plugin, `web`, whose one action searches the web through the search provider you have a key for. +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 `web.search` the same way whichever provider answers, and gets results in one shape. Changing provider changes a key, not the code. +Code calls `websearch.query` the same way whichever provider answers, and gets results in one shape. Changing provider changes a key, not the code. ## Install @@ -17,10 +17,10 @@ It needs a codemode newer than 0.46.0. ## Search -`web.search` returns the results and the provider that gave them: +`websearch.query` returns the results and the provider that gave them: ```bash -codemode exec 'return await web.search({ query: "duckdb 1.4 release notes", numResults: 2 })' +codemode exec 'return await websearch.query({ query: "duckdb 1.4 release notes", numResults: 2 })' ``` ```json @@ -89,7 +89,7 @@ A search uses the provider it names, else the connection's `provider`, else the Name a provider to search with it for one call: ```js -const { results } = await web.search({ query: "duckdb", provider: "exa" }); +const { results } = await websearch.query({ query: "duckdb", provider: "exa" }); ``` ## Narrow a search @@ -97,13 +97,13 @@ const { results } = await web.search({ query: "duckdb", provider: "exa" }); `includeDomains`, `excludeDomains`, and `freshness` are filters. Every result meets them, or the call is refused: ```js -await web.search({ +await websearch.query({ query: "window functions", includeDomains: ["duckdb.org", "postgresql.org"], freshness: "year", }); -await web.search({ query: "duckdb benchmarks", excludeDomains: ["medium.com"] }); +await websearch.query({ query: "duckdb benchmarks", excludeDomains: ["medium.com"] }); ``` Set sites to search or sites to leave out, not both. @@ -115,7 +115,7 @@ Set sites to search or sites to leave out, not both. Add a connection to keep keys in codemode, or to set the default provider. Every field is optional: ```bash -codemode connection add web --plugin web --set exaApiKey=$EXA_API_KEY --set tavilyApiKey=$TAVILY_API_KEY --set provider=tavily +codemode connection add websearch --plugin websearch --set exaApiKey=$EXA_API_KEY --set tavilyApiKey=$TAVILY_API_KEY --set provider=tavily ``` | Field | Meaning | @@ -132,7 +132,7 @@ A host that embeds codemode builds the plugin from its own list of providers. A ```typescript import { Codemode } from "@shiftlabs/codemode"; -import { PROVIDERS, type SearchProvider, webSearch } from "@shiftlabs/codemode-websearch"; +import { PROVIDERS, type SearchProvider, websearch } from "@shiftlabs/codemode-websearch"; const acme: SearchProvider = { name: "acme", @@ -148,7 +148,7 @@ const acme: SearchProvider = { ), }; -const codemode = Codemode.create({ plugins: [webSearch([acme, ...PROVIDERS])] }); +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. @@ -160,7 +160,7 @@ The list's order is the order a provider is chosen in. Parameters go in the quer | No provider has a key | The call rejects and names the environment variables | | The provider named has no key | The call rejects and names its environment variable | | The provider cannot apply a filter | The call rejects and names the providers that can | -| The provider refuses the request | The call rejects with `web.: request failed (HTTP )` | +| 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. diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts index b5b1ec5c..740be83c 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -3,7 +3,7 @@ * whichever provider the connection has a key for, and answers results in * one shape whichever provider that was. * - * const { results } = await web.search({ query: "duckdb 1.4 release notes" }) + * 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 @@ -29,7 +29,7 @@ import { export * from "./providers.js"; -const NAME = "web"; +const NAME = "websearch"; const DEFAULT_RESULTS = 10; const MAX_RESULTS = 20; const MAX_DOMAINS = 20; @@ -201,17 +201,17 @@ function defined(params: Record): Record { } /** - * The `web` plugin over `providers`, in the order one is chosen when a + * The `websearch` plugin over `providers`, in the order one is chosen when a * search names none. A host adds a provider of its own by passing a list * that includes it. */ -export function webSearch( +export function websearch( providers: SearchProvider[] = PROVIDERS, ): PluginFunction { const credential = credentialOf(providers); const names = providers.map((provider) => provider.name); - return function web(rl: CodemodePluginAPI): void { + return function plugin(rl: CodemodePluginAPI): void { rl.setName(NAME); rl.setVersion(packageVersion(import.meta.url)); rl.setDescription( @@ -242,7 +242,7 @@ export function webSearch( }), ); - rl.registerAction("search", { + 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.", @@ -390,4 +390,4 @@ export function webSearch( }; } -export default webSearch(); +export default websearch(); diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index b56c0234..2e71d036 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -13,11 +13,11 @@ 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 web, { +import plugin, { PROVIDERS, type SearchProvider, type SearchResult, - webSearch, + websearch, } from "../src/index.js"; const PACKAGE = fileURLToPath(new URL("..", import.meta.url)); @@ -57,11 +57,11 @@ interface Found { results: SearchResult[]; } -const harness = pluginHarness(web, "web"); +const harness = pluginHarness(plugin, "websearch"); const search = ( input: Record, config: Record, -) => harness.call("search", input, config); +) => harness.call("query", input, config); /** A failed search's error text. */ async function refused( @@ -70,7 +70,7 @@ async function refused( ): Promise { const { error } = await harness .codemode(config) - .execute(`return await web.search(${JSON.stringify(input)})`); + .execute(`return await websearch.query(${JSON.stringify(input)})`); assert.ok(error, "the search should fail"); return error; } @@ -440,7 +440,7 @@ const ALL_KEYS = Object.fromEntries( PROVIDERS.map(({ name }) => [`${name}ApiKey`, `KEY-${name}`]), ); -describe("web.search through each provider", () => { +describe("websearch.query through each provider", () => { it("has a case for every provider", () => { assert.deepEqual( Object.keys(CASES), @@ -537,7 +537,10 @@ describe("the provider a search uses", () => { it("says which keys to set when there is none", async () => { const sent = provider({}); const error = await refused({ query: "q" }, {}); - assert.match(error, /web: no search provider has a key\. Set one of /); + 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); }); @@ -550,7 +553,7 @@ describe("the provider a search uses", () => { ); assert.equal( error.split("\n")[0], - "Error: web: no key for brave. Set BRAVE_API_KEY, or search with a provider that has one.", + "Error: websearch: no key for brave. Set BRAVE_API_KEY, or search with a provider that has one.", ); assert.equal(sent.length, 0); }); @@ -559,11 +562,11 @@ describe("the provider a search uses", () => { const sent = provider({}); assert.match( await refused({ query: "q", provider: "altavista" }, ALL_KEYS), - /Invalid input for web\.search.*\/provider must be equal to one of the allowed values/, + /Invalid input for websearch\.query.*\/provider must be equal to one of the allowed values/, ); assert.match( await refused({ query: "q" }, { ...ALL_KEYS, provider: "altavista" }), - /web: no provider named "altavista"\. The providers are parallel, brave, /, + /websearch: no provider named "altavista"\. The providers are parallel, brave, /, ); assert.equal(sent.length, 0); }); @@ -718,7 +721,7 @@ describe("the filters of a search", () => { ALL_KEYS, ) ).split("\n")[0], - "Error: web: jina cannot filter by freshness. Search without it, or with one of: parallel, brave, exa, you, tavily, firecrawl, linkup, valyu, perplexity, serper, serpapi.", + "Error: websearch: jina cannot filter by freshness. Search without it, or with one of: parallel, brave, exa, you, tavily, firecrawl, linkup, valyu, perplexity, serper, serpapi.", ); assert.match( await refused( @@ -746,7 +749,7 @@ describe("the filters of a search", () => { }, ALL_KEYS, ), - /web: set includeDomains or excludeDomains, not both\./, + /websearch: set includeDomains or excludeDomains, not both\./, ); assert.equal(sent.length, 0); }); @@ -830,11 +833,11 @@ describe("a country and a language", () => { const sent = provider({}); assert.match( await refused({ query: "q", country: "XX" }, ALL_KEYS), - /web: XX is not a country\. Pass an ISO 3166-1 alpha-2 code, such as US\./, + /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), - /web: xx is not a language\. Pass an ISO 639-1 code, such as en\./, + /websearch: xx is not a language\. Pass an ISO 639-1 code, such as en\./, ); assert.equal(sent.length, 0); }); @@ -863,7 +866,7 @@ describe("what a search accepts", () => { ]) assert.match( await refused(input, ALL_KEYS), - /Invalid input for web\.search/, + /Invalid input for websearch\.query/, JSON.stringify(input), ); assert.equal(sent.length, 0); @@ -874,7 +877,7 @@ 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", provider: "brave" }, ALL_KEYS); - assert.match(error, /web\.brave: request failed \(HTTP 401\)/); + assert.match(error, /websearch\.brave: request failed \(HTTP 401\)/); assert.ok(!error.includes("KEY-brave")); }); @@ -925,14 +928,14 @@ describe("a provider a host adds", () => { ({ name, href }) => ({ title: name, url: href, content: "" }), ), }; - const extended = pluginHarness(webSearch([acme, ...PROVIDERS]), "web"); + 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( - "search", + "query", { query: "q" }, { ...ALL_KEYS, acmeApiKey: "KEY-acme" }, ); @@ -951,9 +954,13 @@ describe("a host that keeps the keys", () => { const sent = provider({}); const requests: unknown[] = []; const codemode = Codemode.create({ - plugins: [web], + plugins: [plugin], connections: [ - { name: "web", plugin: "web", config: { provider: "exa" } }, + { + name: "websearch", + plugin: "websearch", + config: { provider: "exa" }, + }, ], credentialBroker: () => ({ request: async (request) => { @@ -967,7 +974,7 @@ describe("a host that keeps the keys", () => { }); try { const { result, error } = await codemode.execute( - 'return await web.search({ query: "q" })', + 'return await websearch.query({ query: "q" })', ); assert.equal(error, undefined); assert.deepEqual(result, { @@ -1029,7 +1036,7 @@ describe("the README", () => { describePackage(PACKAGE, { package: "@shiftlabs/codemode-websearch", - plugin: "web", + plugin: "websearch", actions: 1, write: 0, }); From 0a7bd7684edb8004b485dcdfc112de3c9230ea2b Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:48:14 +0200 Subject: [PATCH 10/14] feat: the bundled parallel plugin is deprecated in favor of websearch.query (SHFT-2967) --- docs/bundled-plugins.md | 2 +- packages/codemode-plugins/parallel/src/index.ts | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/bundled-plugins.md b/docs/bundled-plugins.md index e49c0305..c2cd0ab6 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. Web search across providers is the [`codemode-websearch`](../packages/codemode-websearch/README.md) package. +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, and the bundled `parallel` plugin is deprecated in its favor. 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: diff --git a/packages/codemode-plugins/parallel/src/index.ts b/packages/codemode-plugins/parallel/src/index.ts index 5e0a9ddc..d6af6760 100644 --- a/packages/codemode-plugins/parallel/src/index.ts +++ b/packages/codemode-plugins/parallel/src/index.ts @@ -1,6 +1,9 @@ /** * Parallel.ai web search/research plugin for codemode. * + * Deprecated: `websearch.query` from the codemode-websearch package searches + * through Parallel and eleven other providers with one input. + * * 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 @@ -16,6 +19,8 @@ import { credentialJson, type CodemodePluginAPI } from "@shiftlabs/codemode"; import { DEFAULT_BASE, parallelCredential } from "./credentials.js"; const NAME = "parallel"; +const DEPRECATED = + "Deprecated: where the codemode-websearch package is installed, search with websearch.query instead."; interface SearchResult { url?: string; @@ -32,6 +37,7 @@ interface SearchAnswer { export default function parallel(rl: CodemodePluginAPI): void { rl.setName(NAME); rl.setVersion("0.1.0"); + rl.setDescription(DEPRECATED); rl.setCredential(parallelCredential); rl.setConnectionSchema({ @@ -54,6 +60,7 @@ export default function parallel(rl: CodemodePluginAPI): void { rl.registerAction("search", { access: "read", description: + `${DEPRECATED} ` + "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: { From 602f49e6c6f4f5b0e685310fa5ab49f9f401a9fc Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 13:54:31 +0200 Subject: [PATCH 11/14] feat!: remove the bundled parallel plugin; websearch.query searches through Parallel (SHFT-2967) --- biome.json | 1 - docs/bundled-plugins.md | 3 +- docs/migrating-from-runline.md | 14 ++ packages/codemode-plugins/icons/parallel.svg | 1 - .../parallel/src/credentials.ts | 20 --- .../codemode-plugins/parallel/src/index.ts | 143 ------------------ .../src/tests/credential-fixtures/parallel.ts | 17 --- 7 files changed, 15 insertions(+), 184 deletions(-) delete mode 100644 packages/codemode-plugins/icons/parallel.svg delete mode 100644 packages/codemode-plugins/parallel/src/credentials.ts delete mode 100644 packages/codemode-plugins/parallel/src/index.ts delete mode 100644 packages/codemode/src/tests/credential-fixtures/parallel.ts 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/docs/bundled-plugins.md b/docs/bundled-plugins.md index c2cd0ab6..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. Web search across providers is the [`codemode-websearch`](../packages/codemode-websearch/README.md) package, and the bundled `parallel` plugin is deprecated in its favor. +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 d6af6760..00000000 --- a/packages/codemode-plugins/parallel/src/index.ts +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Parallel.ai web search/research plugin for codemode. - * - * Deprecated: `websearch.query` from the codemode-websearch package searches - * through Parallel and eleven other providers with one input. - * - * 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"; -const DEPRECATED = - "Deprecated: where the codemode-websearch package is installed, search with websearch.query instead."; - -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.setDescription(DEPRECATED); - 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: - `${DEPRECATED} ` + - "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/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; From 9a1c7e4655cb8f0adf887d71a30dbbaa077e1191 Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 14:00:39 +0200 Subject: [PATCH 12/14] feat: country, language and hostnames mean the same in either case (SHFT-2967) --- packages/codemode-websearch/README.md | 8 ++--- packages/codemode-websearch/src/index.ts | 32 +++++++++++-------- packages/codemode-websearch/src/providers.ts | 2 +- .../tests/websearch.test.ts | 24 ++++++++++++-- 4 files changed, 45 insertions(+), 21 deletions(-) diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index fdbb6f34..2e39e5ca 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -54,12 +54,12 @@ Each input has one form, and a value in another form is refused before any reque |---|---|---| | `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 in upper case | `"DE"` | -| `language` | An ISO 639-1 code in lower case | `"de"` | -| `includeDomains`, `excludeDomains` | 1 to 20 hostnames in lower case, without `https://` or a path | `["duckdb.org"]` | +| `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"` | -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. +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 | |---|---| diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts index 740be83c..0676652c 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -46,8 +46,8 @@ const FRESHNESS_DAYS: Record = { }; /** The inputs that narrow a search. A provider applies one or the search is refused. */ const FILTERS = ["includeDomains", "excludeDomains", "freshness"] as const; -/** A hostname in lower case, such as `duckdb.org`: no scheme, path or spaces. */ -const DOMAIN = "^[a-z0-9-]+(\\.[a-z0-9-]+)+$"; +/** 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 { @@ -168,6 +168,8 @@ function checkCode(kind: keyof typeof CODES, code: string | undefined): void { ); } +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); @@ -263,16 +265,16 @@ export function websearch( ), country: t.Optional( t.String({ - pattern: "^[A-Z]{2}$", + pattern: "^[A-Za-z]{2}$", description: - "Country to prefer results from: an ISO 3166-1 alpha-2 code in upper case, such as US, GB, DE", + "Country to prefer results from: an ISO 3166-1 alpha-2 code, such as US, GB, DE", }), ), language: t.Optional( t.String({ - pattern: "^[a-z]{2}$", + pattern: "^[A-Za-z]{2}$", description: - "Language to prefer results in: an ISO 639-1 code in lower case, such as en, es, fr", + "Language to prefer results in: an ISO 639-1 code, such as en, es, fr", }), ), provider: t.Optional( @@ -287,7 +289,7 @@ export function websearch( minItems: 1, maxItems: MAX_DOMAINS, description: - 'Return results from these sites only: hostnames in lower case, without https:// or a path, such as ["duckdb.org", "github.com"]. Not together with excludeDomains', + '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( @@ -341,17 +343,21 @@ export function websearch( throw new Error( `${NAME}: set includeDomains or excludeDomains, not both.`, ); - checkCode("country", input.country); - checkCode("language", input.language); + // 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: input.country, - language: input.language, - includeDomains: input.includeDomains, - excludeDomains: input.excludeDomains, + country, + language, + includeDomains: input.includeDomains?.map(lowerCase), + excludeDomains: input.excludeDomains?.map(lowerCase), freshness, publishedAfter: freshness && dayBefore(FRESHNESS_DAYS[freshness]), }; diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts index db983f60..c630d20d 100644 --- a/packages/codemode-websearch/src/providers.ts +++ b/packages/codemode-websearch/src/providers.ts @@ -32,7 +32,7 @@ export interface SearchRequest { country?: string; /** ISO 639-1 language code, lower case, such as `en`. A preference, like `country`. */ language?: string; - /** Hostnames to return results from, and no other. Never set with `excludeDomains`. */ + /** Hostnames in lower case to return results from, and no other. Never set with `excludeDomains`. */ includeDomains?: string[]; /** Hostnames to leave out of the results. Never set with `includeDomains`. */ excludeDomains?: string[]; diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index 2e71d036..040e9b46 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -829,6 +829,27 @@ describe("a country and a language", () => { }); }); + 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( @@ -851,11 +872,8 @@ describe("what a search accepts", () => { { query: "q", numResults: 21 }, { query: "q", numResults: 2.5 }, { query: "q", country: "germany" }, - { query: "q", country: "us" }, - { query: "q", language: "EN" }, { query: "q", language: "eng" }, { query: "x".repeat(401) }, - { query: "q", includeDomains: ["DuckDB.org"] }, { query: "" }, { query: "q", depth: "deep" }, { query: "q", options: { freshness: "pw" } }, From f614a18275fbdcf0bb2de0e2e50cdc940f9be6d3 Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 14:12:14 +0200 Subject: [PATCH 13/14] feat!: the connection chooses the provider; websearch.query has no provider input (SHFT-2967) --- packages/codemode-websearch/README.md | 27 ++-- packages/codemode-websearch/src/index.ts | 112 ++++++++--------- packages/codemode-websearch/src/providers.ts | 2 +- .../tests/websearch.test.ts | 119 ++++++++++-------- 4 files changed, 136 insertions(+), 124 deletions(-) diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index 2e39e5ca..6b7add4e 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -2,7 +2,7 @@ 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. Changing provider changes a key, not the code. +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 @@ -46,7 +46,6 @@ codemode exec 'return await websearch.query({ query: "duckdb 1.4 release notes", | `includeDomains` | Return results from these sites only | | `excludeDomains` | Leave results from these sites out | | `freshness` | Return only pages published this recently | -| `provider` | The provider to search with. The default is the connection's | Each input has one form, and a value in another form is refused before any request: @@ -69,7 +68,13 @@ A code or a hostname means the same in upper and lower case. Codemode turns each ## Choose a provider -A search uses the provider it names, else the connection's `provider`, else the first provider in this table that has a key: +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 | |---|---|---|---|---| @@ -86,15 +91,11 @@ A search uses the provider it names, else the connection's `provider`, else the | `serper` | `SERPER_API_KEY` | Yes | Yes | Yes | | `serpapi` | `SERPAPI_API_KEY` | Yes | Yes | Yes | -Name a provider to search with it for one call: - -```js -const { results } = await websearch.query({ query: "duckdb", provider: "exa" }); -``` +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: +`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({ @@ -120,7 +121,7 @@ codemode connection add websearch --plugin websearch --set exaApiKey=$EXA_API_KE | Field | Meaning | |---|---| -| `provider` | The provider a search uses when it names none | +| `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` | @@ -158,8 +159,8 @@ The list's order is the order a provider is chosen in. Parameters go in the quer | Outcome | Result | |---|---| | No provider has a key | The call rejects and names the environment variables | -| The provider named has no key | The call rejects and names its environment variable | -| The provider cannot apply a filter | The call rejects and names the providers that can | +| 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 says to search without it | | The provider refuses the request | The call rejects with `websearch.: request failed (HTTP )` | | The provider answers without results | Returns `results: []` | @@ -168,7 +169,7 @@ A provider's error text is not included in the message, because it can repeat th ## Understand the limits - Results are what the provider returns. Their length and freshness differ from provider to provider. -- Jina applies no filter, so a search through it with `includeDomains`, `excludeDomains`, or `freshness` is refused. +- 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. diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts index 0676652c..688e2d9b 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -1,7 +1,7 @@ /** - * Web search for codemode: one action that searches the web through - * whichever provider the connection has a key for, and answers results in - * one shape whichever provider that was. + * 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" }) * @@ -110,34 +110,66 @@ function credentialOf(providers: SearchProvider[]): CredentialDeclaration { } /** - * The provider a search goes to: the one the call names, else the - * connection's `provider`, else the first with a key in the connection. - * A host that signs requests keeps the keys, so only a connection that - * signs for itself (`signsItself`) is asked to hold the key of a provider - * that is named. + * 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>, - named: string | undefined, signsItself: boolean, + search: SearchRequest, ): SearchProvider { - const name = named ?? config.provider; + const name = config.provider; if (name === undefined) { - const first = providers.find((candidate) => hasKey(candidate, config)); - if (first) return first; + 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; 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.`, + `${NAME}: no provider with a key can filter by ${unapplied(keyed[0], search).join(" or ")}. Search without it.`, ); } const provider = providers.find((candidate) => candidate.name === name); if (!provider) throw new Error( - `${NAME}: no provider named ${JSON.stringify(name)}. The providers are ${providers.map((candidate) => candidate.name).join(", ")}.`, + `${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}. Set ${provider.env}, or search with a provider that has one.`, + `${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; } @@ -175,26 +207,6 @@ function dayBefore(days: number): string { return new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10); } -/** - * 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 } : {}), - }), - ), - ); -} - /** `params` without the entries that have no value. */ function defined(params: Record): Record { return Object.fromEntries( @@ -226,7 +238,7 @@ export function websearch( t.String({ enum: names, description: - "The provider a search uses when it names none. The default is the first provider with a key", + "The provider every search goes to. The default is the first provider with a key that can apply the search's filters", }), ), ...Object.fromEntries( @@ -277,13 +289,6 @@ export function websearch( "Language to prefer results in: an ISO 639-1 code, such as en, es, fr", }), ), - provider: t.Optional( - t.String({ - enum: names, - description: - "The provider to search with. The default is the connection's", - }), - ), includeDomains: t.Optional( t.Array(t.String({ pattern: DOMAIN }), { minItems: 1, @@ -333,12 +338,6 @@ export function websearch( required: ["provider", "results"], }, async execute(input, ctx) { - const provider = chosen( - providers, - ctx.connection.config, - input.provider, - !ctx.credentials, - ); if (input.includeDomains && input.excludeDomains) throw new Error( `${NAME}: set includeDomains or excludeDomains, not both.`, @@ -361,15 +360,12 @@ export function websearch( freshness, publishedAfter: freshness && dayBefore(FRESHNESS_DAYS[freshness]), }; - const refused = unapplied(provider, search); - if (refused.length) { - const able = providers - .filter((candidate) => !unapplied(candidate, search).length) - .map((candidate) => candidate.name); - throw new Error( - `${NAME}: ${provider.name} cannot filter by ${refused.join(" or ")}. Search without it, or with one of: ${able.join(", ")}.`, - ); - } + const provider = chosen( + providers, + ctx.connection.config, + !ctx.credentials, + search, + ); const params = defined(provider.params(search)); const answer = await credentialJson( ctx, diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts index c630d20d..c71ec9a6 100644 --- a/packages/codemode-websearch/src/providers.ts +++ b/packages/codemode-websearch/src/providers.ts @@ -55,7 +55,7 @@ export interface SearchResult { /** A search API: where it is, where its key goes, and how a search reads to and from it. */ export interface SearchProvider { - /** The name code passes as `provider`, and the stem of the key's connection field. */ + /** 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; diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index 040e9b46..57007810 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -75,6 +75,14 @@ async function refused( 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, @@ -435,11 +443,6 @@ const CASES: Record< }, }; -/** A connection with a key for every provider. */ -const ALL_KEYS = Object.fromEntries( - PROVIDERS.map(({ name }) => [`${name}ApiKey`, `KEY-${name}`]), -); - describe("websearch.query through each provider", () => { it("has a case for every provider", () => { assert.deepEqual( @@ -451,7 +454,7 @@ describe("websearch.query through each provider", () => { 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, provider: name }, ALL_KEYS); + const found = await search(SEARCH, through(name)); assert.deepEqual(found, { provider: name, results }); assert.equal(sent.length, 1); const [{ method, url, headers, body }] = sent; @@ -494,8 +497,8 @@ describe("websearch.query through each provider", () => { })), }); const found = await search( - { query: "q", numResults: 2, provider: "serpapi" }, - ALL_KEYS, + { query: "q", numResults: 2 }, + through("serpapi"), ); assert.deepEqual( found.results.map(({ title }) => title), @@ -520,18 +523,22 @@ describe("the provider a search uses", () => { assert.equal(found.provider, "exa"); }); - it("is the connection's, and then the call's", async () => { + it("is the connection's, when it names one", async () => { const sent = provider({ results: [] }); - const config = { ...ALL_KEYS, provider: "tavily" }; - assert.equal((await search({ query: "q" }, config)).provider, "tavily"); assert.equal( - (await search({ query: "q", provider: "exa" }, config)).provider, - "exa", + (await search({ query: "q" }, through("tavily"))).provider, + "tavily", ); - assert.deepEqual( - sent.map(({ url }) => new URL(url).host), - ["api.tavily.com", "api.exa.ai"], + 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 () => { @@ -545,28 +552,24 @@ describe("the provider a search uses", () => { assert.equal(sent.length, 0); }); - it("refuses a provider whose key the connection lacks, before any request", async () => { + 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", provider: "brave" }, - { exaApiKey: "e" }, + { query: "q" }, + { exaApiKey: "e", provider: "brave" }, ); assert.equal( error.split("\n")[0], - "Error: websearch: no key for brave. Set BRAVE_API_KEY, or search with a provider that has one.", + "Error: websearch: no key for brave, the connection's provider. Set BRAVE_API_KEY.", ); assert.equal(sent.length, 0); }); - it("refuses a provider it does not know", async () => { + it("is refused when the connection names one that does not exist", async () => { const sent = provider({}); assert.match( - await refused({ query: "q", provider: "altavista" }, ALL_KEYS), - /Invalid input for websearch\.query.*\/provider must be equal to one of the allowed values/, - ); - assert.match( - await refused({ query: "q" }, { ...ALL_KEYS, provider: "altavista" }), - /websearch: no provider named "altavista"\. The providers are parallel, brave, /, + await refused({ query: "q" }, through("altavista")), + /websearch: the connection names the provider "altavista"\. The providers are parallel, brave, /, ); assert.equal(sent.length, 0); }); @@ -671,19 +674,18 @@ describe("the filters of a search", () => { it(`${name}: sends sites and freshness as its API names them`, async () => { const sent = provider({}); const before = dayBefore(7); - await search({ query: "q", provider: name }, ALL_KEYS); + await search({ query: "q" }, through(name)); await search( { query: "q", - provider: name, includeDomains: ["a.example", "b.example"], freshness: "week", }, - ALL_KEYS, + through(name), ); await search( - { query: "q", provider: name, excludeDomains: ["c.example"] }, - ALL_KEYS, + { 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 @@ -703,8 +705,8 @@ describe("the filters of a search", () => { it("writes one site without brackets", async () => { const sent = provider({}); await search( - { query: "q", provider: "brave", includeDomains: ["a.example"] }, - ALL_KEYS, + { query: "q", includeDomains: ["a.example"] }, + through("brave"), ); assert.equal( new URL(sent[0].url).searchParams.get("q"), @@ -712,28 +714,41 @@ describe("the filters of a search", () => { ); }); - it("refuses a filter the provider cannot apply, and names those that can", async () => { + 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", provider: "jina", freshness: "day" }, - ALL_KEYS, + { query: "q", includeDomains: ["a.example"], freshness: "day" }, + { jinaApiKey: "j" }, ) ).split("\n")[0], - "Error: websearch: jina cannot filter by freshness. Search without it, or with one of: parallel, brave, exa, you, tavily, firecrawl, linkup, valyu, perplexity, serper, serpapi.", + "Error: websearch: no provider with a key can filter by includeDomains or freshness. Search without it.", ); - assert.match( - await refused( - { - query: "q", - provider: "jina", - includeDomains: ["a.example"], - freshness: "day", - }, - ALL_KEYS, - ), - /jina cannot filter by includeDomains or freshness\./, + 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); }); @@ -762,7 +777,7 @@ describe("a country and a language", () => { input: Record, ): Promise> => { const sent = provider({}); - await search({ query: "q", provider: name, ...input }, ALL_KEYS); + await search({ query: "q", ...input }, through(name)); return parameters(sent[0]); }; @@ -894,7 +909,7 @@ describe("what a search accepts", () => { 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", provider: "brave" }, ALL_KEYS); + const error = await refused({ query: "q" }, through("brave")); assert.match(error, /websearch\.brave: request failed \(HTTP 401\)/); assert.ok(!error.includes("KEY-brave")); }); @@ -902,7 +917,7 @@ describe("a provider that fails", () => { it("reads an answer without results as none", async () => { provider({ unexpected: true }); for (const { name } of PROVIDERS) - assert.deepEqual(await search({ query: "q", provider: name }, ALL_KEYS), { + assert.deepEqual(await search({ query: "q" }, through(name)), { provider: name, results: [], }); From 90de354e7128348252214638200de73014229952 Mon Sep 17 00:00:00 2001 From: Michael Livshits Date: Sun, 22 Nov 2026 14:19:47 +0200 Subject: [PATCH 14/14] refactor: wording follows the connection choosing the provider; the refusal names the filters set (SHFT-2967) --- packages/codemode-websearch/README.md | 4 ++-- packages/codemode-websearch/src/index.ts | 13 +++++++------ packages/codemode-websearch/src/providers.ts | 6 +++--- packages/codemode-websearch/tests/websearch.test.ts | 2 +- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/packages/codemode-websearch/README.md b/packages/codemode-websearch/README.md index 6b7add4e..40e6f11c 100644 --- a/packages/codemode-websearch/README.md +++ b/packages/codemode-websearch/README.md @@ -113,7 +113,7 @@ Set sites to search or sites to leave out, not both. ## Configure the connection -Add a connection to keep keys in codemode, or to set the default provider. Every field is optional: +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 @@ -160,7 +160,7 @@ The list's order is the order a provider is chosen in. Parameters go in the quer |---|---| | 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 says to search without it | +| 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: []` | diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts index 688e2d9b..b2fe1cc6 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -44,7 +44,7 @@ const FRESHNESS_DAYS: Record = { month: 31, year: 365, }; -/** The inputs that narrow a search. A provider applies one or the search is refused. */ +/** 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-]+)+$"; @@ -153,8 +153,9 @@ function chosen( (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 ${unapplied(keyed[0], search).join(" or ")}. Search without it.`, + `${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); @@ -215,9 +216,9 @@ function defined(params: Record): Record { } /** - * The `websearch` plugin over `providers`, in the order one is chosen when a - * search names none. A host adds a provider of its own by passing a list - * that includes it. + * 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, @@ -229,7 +230,7 @@ export function websearch( rl.setName(NAME); rl.setVersion(packageVersion(import.meta.url)); rl.setDescription( - "Search the web through the search provider the connection has a key for.", + "Search the web through the search provider the connection chooses.", ); rl.setCredential(credential); rl.setConnectionSchema( diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts index c71ec9a6..07c8c1bc 100644 --- a/packages/codemode-websearch/src/providers.ts +++ b/packages/codemode-websearch/src/providers.ts @@ -34,7 +34,7 @@ export interface SearchRequest { language?: string; /** Hostnames in lower case to return results from, and no other. Never set with `excludeDomains`. */ includeDomains?: string[]; - /** Hostnames to leave out of the results. Never set with `includeDomains`. */ + /** Hostnames in lower case to leave out of the results. Never set with `includeDomains`. */ excludeDomains?: string[]; /** Return only pages published this recently. */ freshness?: Freshness; @@ -77,7 +77,7 @@ export interface SearchProvider { /** * 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 refuses a search that sets it. + * provider cannot apply, and the plugin sends it no search that sets it. */ params(search: SearchRequest): Record; /** The results in the provider's answer. */ @@ -541,7 +541,7 @@ export const serpapi: SearchProvider = { }; /** - * Every provider, in the order one is chosen when a search names none: + * 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. */ diff --git a/packages/codemode-websearch/tests/websearch.test.ts b/packages/codemode-websearch/tests/websearch.test.ts index 57007810..82e51cf3 100644 --- a/packages/codemode-websearch/tests/websearch.test.ts +++ b/packages/codemode-websearch/tests/websearch.test.ts @@ -737,7 +737,7 @@ describe("the filters of a search", () => { { jinaApiKey: "j" }, ) ).split("\n")[0], - "Error: websearch: no provider with a key can filter by includeDomains or freshness. Search without it.", + "Error: websearch: no provider with a key can filter by includeDomains and freshness. Search without one of them.", ); assert.equal(sent.length, 0); });