search: a plugin can give a web search API (its search hook)
treeman on Discord #help asked for web search to be pluggable so users can
add search vendors. A plugin's `search` hook, {search: {<id>: {name, keysURL?,
keyOptional?, url?, execute({query, count, key, url}, ctx)}}}, adds an API to
Settings > Models > Web search as `<plugin>:<id>`. It is added, keyed, ordered,
switched off and removed like Tavily or Brave. The built-in APIs stay built in.
How: host.js collects the hook's entries (id [a-z0-9-], an execute) into
Loaded.Searches and runs one with the `search` op (timeout from ctx, an error
with a numeric status comes back as a refusal). The host notes them in
plugin-searches.json (internal/plugin/search.go); provider.AllSearchVendors
adds the noted ones of plugins that are on to SearchVendors, so Ready, check,
the CLI and the GUI list see them. askSearchAPI hands a plugin vendor to
askPluginSearch below askSearchAPIKeys, so keys, rest on 401/402/403/429,
order, the masked query and the request-log row are the built-ins' own.
Run (mote, on this tree, whose base df7c94bdf was just fetched):
- go test -timeout 45m ./internal/plugin ./internal/provider ./internal/gateway
./internal/cli: ok.
- go vet native; GOOS=windows go vet plugin, provider, gateway, cli: ok;
GOOS=linux go vet plugin, provider, gateway: ok. gofmt -l: empty.
- internal/gui: TestCoreScriptBudget and TestMainWindowCorners fail in a
full run. This change touches no script (only api.go's loop), so the
budget red is the base's (re-checked after the rebase, below);
TestMainWindowCorners is AppKit on mote (macOS 27).
Broken by hand: skipping off plugins in NotedSearches turns TestPluginSearch
red; the refusal mapping removed turns TestPluginSearchAPI red.
Not tried: a real plugin against a real vendor's API; the GUI JS suite (no
GUI script changed); a Linux or Windows window; site/public/docs (en, zh, ja)
do not describe the hook yet. A plugin just added is listed once the host has
loaded it; RestoreSearchAPIs drops a plugin's entry on a machine without it.
The community README has the template (magpie-community/plugins 3ec42d4).
Reported by treeman.
This commit is contained in:
@@ -1157,6 +1157,43 @@ export const LemonPlugin = async () => ({
|
||||
In TypeScript, `icon` and `placeholder` aren't in OpenCode's types: build
|
||||
the hook as a variable (or cast it), or put the icon in `package.json`.
|
||||
|
||||
#### Web search APIs from a plugin
|
||||
|
||||
A plugin can add a web search API to Settings › Models › Web search with a
|
||||
`search` hook (magpie's own; OpenCode ignores it). It is listed after
|
||||
Tavily, Brave and the rest under its own name, and added, keyed, switched
|
||||
off, reordered and removed like them (`magpie search add <plugin>:<id> <key>`
|
||||
on the command line). magpie keeps its keys (several, tried in turn, a refused
|
||||
one resting), its order and its place in the request log, masks the query
|
||||
as it does for every search API, and asks the plugin only while the
|
||||
plugin is on and the Web search plugin is.
|
||||
|
||||
```js
|
||||
export const MojeekSearch = async () => ({
|
||||
search: {
|
||||
mojeek: { // [a-z0-9-], at most 32; the API is `<plugin>:mojeek`
|
||||
name: "Mojeek", // its name in the list
|
||||
keysURL: "https://www.mojeek.com/services/api/", // "Get a key" link, optional
|
||||
keyOptional: false, // true: it answers with no key
|
||||
url: false, // true: the user gives its address (a SearXNG's)
|
||||
async execute({ query, count, key, url }, ctx) {
|
||||
const r = await fetch(`https://api.mojeek.com/search?fmt=json&q=${encodeURIComponent(query)}&t=${count}&api_key=${key}`, { signal: ctx.abort })
|
||||
if (!r.ok) throw Object.assign(new Error(await r.text()), { status: r.status }) // 401, 402, 403, 429 rest the key
|
||||
const j = await r.json()
|
||||
return j.response.results.map((x) => ({ title: x.title, url: x.url, text: x.desc }))
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
`execute` returns `[{ title, url, text?, age? }]` (or `{ results: [...] }`);
|
||||
magpie strips tags and cuts each page's text. A throw with a numeric
|
||||
`status` (and `retryAfter`, its Retry-After) is the API refusing the key,
|
||||
treated as a built-in's 401/402/403/429 is; any other throw is a failure
|
||||
and the next search API is asked. It has the time a search API has
|
||||
(a quarter of a search's limit); `ctx.abort` fires then.
|
||||
|
||||
#### Gateway middleware
|
||||
|
||||
A plugin can also be gateway middleware: `onRequest(body, ctx)` sees each
|
||||
|
||||
@@ -1404,6 +1404,20 @@ Covered by `TestSearchAPIAtItsOwnBaseURL`, `TestSearchKeyStaysAtItsBaseURL`,
|
||||
`TestSearchAPIBaseURLFromSettings`, `TestSearchCLI` and
|
||||
`search-api.test.cjs`.
|
||||
|
||||
### A search API a plugin gives
|
||||
|
||||
A plugin's `search` hook adds search APIs under the id `<plugin>:<id>`
|
||||
(`provider.AllSearchVendors`; [plugin-tools](plugin-tools.md#search-apis-from-a-plugin)).
|
||||
`askSearchAPI` hands one to `askPluginSearch`, so the keys, their rest after a
|
||||
401/402/403/429 (`SearchRefused`), the listed order, the switch, the masked
|
||||
query and the request-log row are the built-ins' own, and the plugin is
|
||||
asked only while it is on. A plugin API has no `Base` of its own: its URL
|
||||
field shows only when the plugin declares `url: true`, and then is required.
|
||||
Its pages are cleaned like a built-in's (`searchPlain`, `clipText`, six at
|
||||
most). It is asked with the time left of a quarter of the search's limit, and
|
||||
`plugin.RunSearch` returns when that is out, though the plugin's own fetch may
|
||||
run on until the host's abort reaches it. `TestPluginSearchAPI`.
|
||||
|
||||
## The search APIs' order, and one switched off
|
||||
|
||||
`provider.SearchAPIs` gives the search APIs in their saved order, the
|
||||
|
||||
@@ -51,3 +51,16 @@ node --test internal/gui/tests/plugin-tools.test.cjs internal/gui/tests/builtins
|
||||
```
|
||||
|
||||
The example plugin the tests load is [`internal/plugin/testdata/tools`](../../internal/plugin/testdata/tools/index.js): tools with a zod shape, a raw JSON Schema, one that sleeps past the timeout, one that throws, and two that are left out.
|
||||
|
||||
## Search APIs from a plugin
|
||||
|
||||
The same host and `Loaded` list carry a second hook, `search`: `{search: {<id>: {name, keysURL?, keyOptional?, url?, execute({query, count, key, url}, ctx)}}}`, which adds a web search API to magpie's own ([`provider.SearchVendors`](../../internal/provider/search_api.go)). It is not part of the tools MCP server; it belongs to the search path ([Gateway routing](gateway-routing.md), "A search API's base URL").
|
||||
|
||||
| Part | Responsibility | Source |
|
||||
| --- | --- | --- |
|
||||
| Collect | `searchesOf` keeps the ids that match `^[a-z0-9][a-z0-9-]{0,31}$` and have an `execute`; `searchList` returns `{id, name, keysURL, keyOptional, needURL}` with the plugin (`Loaded.Searches`). | `searchesOf`, `searchList` in [`host.js`](../../internal/plugin/host.js); [`search.go`](../../internal/plugin/search.go) |
|
||||
| Note | After every load the host notes them in `plugin-searches.json` (whole, only when changed). `NotedSearches` reads it without starting the host (`filememo`), for plugins that are on in plugins.json; a note that can't be parsed is an error, and `AllSearchVendors` then adds none. The API's vendor id is `<plugin short name>:<id>` (`PluginSearch.VendorID`), so it can't take a built-in's id. | `noteSearches`, `NotedSearches` in `search.go` |
|
||||
| List | `provider.AllSearchVendors` is `SearchVendors` plus the noted ones; `SearchVendorOf`, `Ready`, `check` and the GUI's `searchVendors` use it. A user's saved key and order stay in providers.json under that id; with the plugin off or removed the API is not ready, so never asked, and comes back with the plugin. | `search_api.go` in `internal/provider`, `searchVendorJSON` in [`api.go`](../../internal/gui/api.go) |
|
||||
| Ask | `askSearchAPI` hands a plugin's vendor to `askPluginSearch`, below `askSearchAPIKeys`: the same keys, rest, timeout (a quarter of `searchTimeout`) and request-log row as a built-in, with the query `apiSearch` already masked. `plugin.RunSearch` runs the host's `search` call; a throw with a numeric `status` comes back as `SearchRefused`, which becomes `searchRefused`. Pages are cleaned with `searchPlain` and `clipText`, six at most. | `askPluginSearch` in [`search_api.go`](../../internal/gateway/search_api.go) |
|
||||
|
||||
Constraints: the plugin runs with the user's rights and sees the key and the (masked) query, as a built-in's vendor does. A backup or sync that restores search APIs on a computer without the plugin drops the plugin's entry there (`RestoreSearchAPIs` keeps only vendors it knows). The vendor list is read from the last load's note, so a plugin just added is listed after the host has loaded it. Tests: `TestPluginSearch` (host, `testdata/search`), `TestPluginSearchAPI` and `TestPluginSearchAPISeesMaskedQuery` (gateway).
|
||||
|
||||
Reference in New Issue
Block a user