From 90bf96a23d74a8d9804fba8eb3ee28fa7ee374b0 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 4 Nov 2026 08:36:33 +0800 Subject: [PATCH] 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: {: {name, keysURL?, keyOptional?, url?, execute({query, count, key, url}, ctx)}}}, adds an API to Settings > Models > Web search as `:`. 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. --- docs/reference.md | 37 ++++ docs/subsystems/gateway-routing.md | 14 ++ docs/subsystems/plugin-tools.md | 13 ++ internal/cli/search_cli.go | 2 + internal/gateway/search_api.go | 52 ++++++ internal/gateway/search_plugin_api_test.go | 157 +++++++++++++++++ internal/gui/api.go | 4 +- internal/plugin/host.go | 3 + internal/plugin/host.js | 70 ++++++++ internal/plugin/search.go | 168 +++++++++++++++++++ internal/plugin/search_test.go | 95 +++++++++++ internal/plugin/testdata/search/index.js | 25 +++ internal/plugin/testdata/search/package.json | 6 + internal/provider/search_api.go | 45 ++++- 14 files changed, 684 insertions(+), 7 deletions(-) create mode 100644 internal/gateway/search_plugin_api_test.go create mode 100644 internal/plugin/search.go create mode 100644 internal/plugin/search_test.go create mode 100644 internal/plugin/testdata/search/index.js create mode 100644 internal/plugin/testdata/search/package.json diff --git a/docs/reference.md b/docs/reference.md index 34d01ed0c..d024b8f05 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -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 : ` +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 `: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 diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 42574e14f..1dcda1a44 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -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 `:` +(`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 diff --git a/docs/subsystems/plugin-tools.md b/docs/subsystems/plugin-tools.md index 9ce5fe4f5..512bc62ed 100644 --- a/docs/subsystems/plugin-tools.md +++ b/docs/subsystems/plugin-tools.md @@ -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: {: {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 `:` (`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). diff --git a/internal/cli/search_cli.go b/internal/cli/search_cli.go index 3121a372a..c384a8b27 100644 --- a/internal/cli/search_cli.go +++ b/internal/cli/search_cli.go @@ -27,6 +27,8 @@ const searchUsage = `usage: magpie search rm take one away apis: tavily, brave, exa, firecrawl, you, deepseek, volcengine, wsa, searxng + and the ones a plugin gives (its search hook), as : in magpie's Settings + › Models › Web search; a plugin that is off gives none url= is the API's base URL, for an endpoint of your own that answers as that API does (e.g. url=https://search.example.com/tavily). Without it the vendor's own is diff --git a/internal/gateway/search_api.go b/internal/gateway/search_api.go index aee09523e..599c6c829 100644 --- a/internal/gateway/search_api.go +++ b/internal/gateway/search_api.go @@ -18,6 +18,7 @@ import ( "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/usage" ) @@ -261,6 +262,9 @@ func pagesSaid(pages []foundPage) (string, []Hit) { // askSearchAPI asks one search API for the query. func (s *Server) askSearchAPI(ctx context.Context, a provider.SearchAPI, query string) ([]foundPage, error) { + if v, ok := provider.SearchVendorOf(a.Vendor); ok && v.Plugin != "" { + return s.askPluginSearch(ctx, a, v, query) + } var r *http.Request var err error post := func(path string, body any) { @@ -406,6 +410,54 @@ func (s *Server) askSearchAPI(ctx context.Context, a provider.SearchAPI, query s return pages, nil } +// runPluginSearch asks a plugin's search API in the host (a test's has no host). +var runPluginSearch = plugin.RunSearch + +// askPluginSearch asks a search API a plugin gives (its search hook) in the +// plugin host. It is asked as a built-in is: from askSearchAPIKeys, so with +// the user's keys in their order, the same time to answer, the same rest of +// a key it refused (the plugin throws an error with a status) and the same +// row in the request log; and with the query apiSearch masked. What it +// found is cut and cleaned as a built-in's pages are. +func (s *Server) askPluginSearch(ctx context.Context, a provider.SearchAPI, v provider.SearchVendor, query string) ([]foundPage, error) { + got, err := runPluginSearch(ctx, v.Plugin, v.PluginID, query, searchHits, a.Key, a.Base()) + if err != nil { + var r plugin.SearchRefused + if errors.As(err, &r) { + msg := r.Msg + if a.Key != "" { + msg = strings.ReplaceAll(msg, a.Key, provider.MaskSearchKey(a.Key)) + } + if keyRefusal(r.Status) { + return nil, searchRefused{r.Status, msg, r.RetryAfter} + } + return nil, errors.New(msg) + } + if ctx.Err() != nil { + return nil, errors.New("no answer in time") + } + if a.Key != "" { + err = errors.New(strings.ReplaceAll(err.Error(), a.Key, provider.MaskSearchKey(a.Key))) + } + return nil, err + } + var pages []foundPage + for _, r := range got { + if r.URL == "" { + continue + } + title := searchPlain(r.Title) + if title == "" { + title = r.URL + } + pages = append(pages, foundPage{Title: title, URL: r.URL, Text: clipText(searchPlain(r.Text), pageText), Age: r.Age}) + if len(pages) == searchHits { + break + } + } + return pages, nil +} + // readSearchAPI reads the pages out of a search API's reply. func readSearchAPI(vendor string, b []byte) ([]foundPage, error) { switch vendor { diff --git a/internal/gateway/search_plugin_api_test.go b/internal/gateway/search_plugin_api_test.go new file mode 100644 index 000000000..8bb2a892e --- /dev/null +++ b/internal/gateway/search_plugin_api_test.go @@ -0,0 +1,157 @@ +package gateway + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" +) + +// plugged has plugins.json list a plugin that gives one search API, as the +// host notes it after a load, with no host. +func plugged(t *testing.T, spec string, off bool) { + t.Helper() + offs := "" + if off { + offs = `,"off":true` + } + write := func(name, body string) { + if err := os.WriteFile(filepath.Join(settings.Dir(), name), []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + if err := os.MkdirAll(settings.Dir(), 0o700); err != nil { + t.Fatal(err) + } + write("plugins.json", `{"plugins":[{"spec":"`+spec+`"`+offs+`}]}`) + write("plugin-searches.json", `{"`+spec+`":[{"id":"mojeek","name":"Mojeek","keysURL":"https://www.mojeek.com/services/api/"}]}`) +} + +// A search API a plugin gives is asked on the same path as Tavily and the +// rest (#treeman on Discord): it is added and keyed like them under its +// own name (:), asked with the masked query, its keys tried in +// turn with a refused one resting, its pages cut and cleaned, and every ask +// a row of the request log. Turned off, the plugin's API is not asked, and +// not listed. +func TestPluginSearchAPI(t *testing.T) { + fresh(t) + const spec = "@acme/opencode-mojeek-search@1.0.0" + const id = "mojeek-search:mojeek" + plugged(t, spec, false) + var asked []string + old := runPluginSearch + t.Cleanup(func() { runPluginSearch = old }) + runPluginSearch = func(_ context.Context, sp, pid, query string, count int, key, url string) ([]plugin.SearchPage, error) { + asked = append(asked, sp+" "+pid+" "+key+" "+query) + switch key { + case "spent-key-0001": + return nil, plugin.SearchRefused{Status: 429, Msg: "slow down, " + key, RetryAfter: "30"} + case "broken-key-0002": + return nil, errors.New("boom with " + key) + } + return []plugin.SearchPage{ + {Title: "Go downloads", URL: "https://go.dev/dl/", Text: "Go 1.27.1\n is out", Age: "2026-10-01"}, + {Title: "no address"}, + }, nil + } + + v, ok := provider.SearchVendorOf(id) + if !ok || v.Name != "Mojeek" || v.Plugin != spec || v.PluginID != "mojeek" || v.KeysURL == "" { + t.Fatalf("vendor %+v %v", v, ok) + } + if got := provider.AllSearchVendors(); got[len(got)-1].ID != id || len(got) != len(provider.SearchVendors)+1 { + t.Fatalf("not listed after the built-ins: %v", got) + } + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: id}); err == nil || !strings.Contains(err.Error(), "needs its API key") { + t.Errorf("no key: %v", err) + } + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "nobody:none", Key: "k"}); err == nil || !strings.Contains(err.Error(), id) { + t.Errorf("an unknown plugin's API: %v", err) + } + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: id, Key: "spent-key-0001,good-key-0003"}); err != nil { + t.Fatal(err) + } + if !canSearch() { + t.Fatal("a plugin's search API alone doesn't let magpie search") + } + + s := New() + ctx := context.WithValue(context.Background(), searchForKey{}, &CallFor{Agent: "claude"}) + said, hits, err := s.apiSearch(ctx, "latest go") + if err != nil { + t.Fatal(err) + } + if len(hits) != 1 || hits[0].URL != "https://go.dev/dl/" || hits[0].Title != "Go downloads" || hits[0].PageAge != "2026-10-01" || + !strings.Contains(said, "Go downloads — https://go.dev/dl/\nGo 1.27.1 is out") { + t.Fatalf("said %q hits %+v", said, hits) + } + if len(asked) != 2 || asked[0] != spec+" mojeek spent-key-0001 latest go" || asked[1] != spec+" mojeek good-key-0003 latest go" { + t.Fatalf("asked %q", asked) + } + // the refused key rests: the next search starts from the other + asked = nil + if _, _, err := s.apiSearch(ctx, "again"); err != nil || len(asked) != 1 || !strings.Contains(asked[0], "good-key-0003") { + t.Fatalf("after the refusal: %v %q", err, asked) + } + rows, _ := searchRows(t) + if len(rows) != 3 || rows[0].Requested != "Mojeek" || rows[0].Status != 429 || rows[0].ProviderKeyName == "spent-key-0001" || + rows[1].Status != 200 || rows[1].Source != usage.SourceSearch { + t.Fatalf("log %+v", rows) + } + for _, r := range rows { + if strings.Contains(r.Error, "spent-key-0001") || strings.Contains(r.Error, "latest go") { + t.Errorf("row says the key or the query: %+v", r) + } + } + + // a failure that isn't about the key says so, without the key + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: id, Key: "broken-key-0002"}); err != nil { + t.Fatal(err) + } + if _, _, err := s.apiSearch(ctx, "q"); err == nil || !strings.Contains(err.Error(), "boom") || strings.Contains(err.Error(), "broken-key-0002") { + t.Errorf("a failure: %v", err) + } + + // the plugin off: its API isn't asked, nor listed + plugged(t, spec, true) + asked = nil + if _, ok := provider.SearchVendorOf(id); ok || len(provider.SearchAPIs()) != 0 || canSearch() { + t.Error("the plugin is off, and its search API is still there") + } + if s.apiSearch(ctx, "q"); len(asked) != 0 { + t.Errorf("asked with the plugin off: %q", asked) + } +} + +// The query is masked before a plugin's search API sees it, as before +// Tavily's. +func TestPluginSearchAPISeesMaskedQuery(t *testing.T) { + fresh(t) + plugged(t, "mojeek-search", false) + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "mojeek-search:mojeek", Key: "k"}); err != nil { + t.Fatal(err) + } + old := runPluginSearch + t.Cleanup(func() { runPluginSearch = old }) + var got string + runPluginSearch = func(_ context.Context, _, _, q string, _ int, _, _ string) ([]plugin.SearchPage, error) { + got = q + return []plugin.SearchPage{{Title: "t", URL: "https://x.dev"}}, nil + } + if err := settings.Save(settings.Settings{RedactPersonal: true}); err != nil { + t.Fatal(err) + } + if _, _, err := New().apiSearch(context.Background(), "who called from 13812345678"); err != nil { + t.Fatal(err) + } + if !strings.Contains(got, "{{PHONE_") || strings.Contains(got, "13812345678") { + t.Errorf("the plugin saw %q", got) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index d943100e8..c7e73b153 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -626,8 +626,8 @@ func searchState(s *settingsJSON) { } s.SearchAPIs = append(s.SearchAPIs, j) } - for _, v := range provider.SearchVendors { - s.SearchVendors = append(s.SearchVendors, searchVendorJSON{ID: v.ID, Name: v.Name, KeysURL: v.KeysURL, NeedURL: v.Base == "", KeyOptional: v.KeyOptional, Base: v.Base}) + for _, v := range provider.AllSearchVendors() { + s.SearchVendors = append(s.SearchVendors, searchVendorJSON{ID: v.ID, Name: v.Name, KeysURL: v.KeysURL, NeedURL: v.WantsURL(), KeyOptional: v.KeyOptional, Base: v.Base}) } s.SearchProvider = gateway.Searcher() s.SearchAuto, s.SearchUnused = gateway.AutoSearcher(), gateway.SearcherUnused() diff --git a/internal/plugin/host.go b/internal/plugin/host.go index e13d0ad15..f8a9ff0a4 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -617,6 +617,8 @@ type Loaded struct { ServedBy map[string]string `json:"servedBy,omitempty"` // Tools are the tools its tool hook gives (tools.go) Tools []Tool `json:"tools,omitempty"` + // Searches are the web search APIs its search hook gives (search.go) + Searches []SearchDef `json:"searches,omitempty"` } // Clash is a provider id more than one plugin signs in to. The host runs @@ -1169,6 +1171,7 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { } h.loaded = res.Plugins noteTools(res.Plugins) + noteSearches(res.Plugins) for _, p := range res.Plugins { if p.Error != "" { log.Printf("plugin %s didn't load: %s", p.Spec, p.Error) diff --git a/internal/plugin/host.js b/internal/plugin/host.js index e45cb0b2a..12c39cb15 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -1556,6 +1556,8 @@ const signsIn = (spec) => [...new Set(hooks.filter((h) => h.spec === spec && h.h function withProviders(l) { const tools = l.error ? [] : toolList(l.spec) if (tools.length) l = { ...l, tools } + const searches = l.error ? [] : searchList(l.spec) + if (searches.length) l = { ...l, searches } const ids = l.error ? [] : signsIn(l.spec) if (!ids.length) return l const a = auths() @@ -1719,6 +1721,73 @@ async function runTool({ spec, name, args, ms, agent }) { return { text: out === undefined ? "" : JSON.stringify(out) } } +// ---- web search APIs -------------------------------------------------------- +// +// A plugin's search hook adds web search APIs to magpie's own list (Tavily, +// Brave, …): {search: {: {name, keysURL?, keyOptional?, url?, execute}}}. +// execute({query, count, key, url}, ctx) returns the pages found: +// [{title, url, text?, age?}] (or {results: [...]}). A throw with a numeric +// status (401, 402, 403, 429…) is the API refusing the key, which magpie +// rests as it does a built-in's; retryAfter is its Retry-After. +// magpie keeps the keys, order and limits, and masks the query before it. + +const SEARCH_ID = /^[a-z0-9][a-z0-9-]{0,31}$/ + +function searchesOf(spec) { + const m = new Map() + for (const h of hooks) { + if (h.spec !== spec) continue + const t = h.hooks.search + if (!t || typeof t !== "object") continue + for (const [id, def] of Object.entries(t)) { + if (SEARCH_ID.test(id) && def && typeof def.execute === "function") m.set(id, def) + } + } + return m +} + +function searchList(spec) { + const out = [] + for (const [id, def] of searchesOf(spec)) { + out.push({ + id, + name: typeof def.name === "string" && def.name ? def.name : id, + ...(typeof def.keysURL === "string" && /^https?:\/\//.test(def.keysURL) ? { keysURL: def.keysURL } : {}), + ...(def.keyOptional === true ? { keyOptional: true } : {}), + ...(def.url === true ? { needURL: true } : {}), + }) + } + return out +} + +async function runSearch({ spec, id, query, count, key, url, ms }) { + const def = searchesOf(spec).get(id) + if (!def) throw new Error(`${spec} has no search API ${id}`) + const abort = AbortSignal.timeout(ms > 0 ? ms : 60_000) + const ctx = { directory, worktree: directory, abort } + let out + try { + out = await Promise.race([ + Promise.resolve().then(() => def.execute({ query, count, key: key ?? "", url: url ?? "" }, ctx)), + new Promise((_, reject) => abort.addEventListener("abort", () => reject(new Error("no answer in time")), { once: true })), + ]) + } catch (e) { + const status = Number(e?.status) + if (Number.isInteger(status) && status >= 300 && status < 600) { + return { status, error: String(e?.message ?? e), retryAfter: e?.retryAfter == null ? "" : String(e.retryAfter) } + } + throw e + } + const rs = Array.isArray(out) ? out : Array.isArray(out?.results) ? out.results : null + if (!rs) throw new Error("the search returned neither a list nor {results}") + const str = (v) => (typeof v === "string" ? v : v == null ? "" : String(v)) + return { + pages: rs.filter((r) => r && typeof r === "object").map((r) => ({ + title: str(r.title), url: str(r.url), text: str(r.text ?? r.content ?? r.snippet), age: str(r.age ?? r.date), + })), + } +} + function authOf(provider) { const a = auths().get(provider) if (!a) throw new Error(`no plugin signs in to ${provider}`) @@ -3029,6 +3098,7 @@ const handlers = { authorize, callback, tool: runTool, + search: runSearch, apiKey, load, usage, diff --git a/internal/plugin/search.go b/internal/plugin/search.go new file mode 100644 index 000000000..857ecb84a --- /dev/null +++ b/internal/plugin/search.go @@ -0,0 +1,168 @@ +package plugin + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io/fs" + "log" + "path/filepath" + "regexp" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/filememo" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/steady" +) + +// SearchDef is a web search API a plugin gives: its search hook +// ({search: {: {name, keysURL, keyOptional, url, execute}}}). magpie +// lists it beside Tavily, Brave and the rest, keeps its keys and order, and +// asks it through the gateway's search path (internal/gateway/search_api.go). +type SearchDef struct { + ID string `json:"id"` // [a-z0-9-], at most 32 + Name string `json:"name"` + KeysURL string `json:"keysURL,omitempty"` + KeyOptional bool `json:"keyOptional,omitempty"` + // NeedURL: the user gives an address (a SearXNG's), passed to the + // plugin as url + NeedURL bool `json:"needURL,omitempty"` +} + +// PluginSearch is a search API with the plugin that gives it. +type PluginSearch struct { + Spec string `json:"spec"` + SearchDef +} + +// VendorID is how the search API is known in magpie's list and in +// providers.json: the plugin's short name and its own id, so no plugin's +// id can take a built-in's place or another plugin's. +func (p PluginSearch) VendorID() string { + short := strings.Trim(unsafeVendorChars.ReplaceAllString(strings.ToLower(ShortName(Name(p.Spec))), "-"), "-") + return short + ":" + p.ID +} + +// unsafeVendorChars are what a vendor id leaves out: the CLI lowercases it +// and it is a word in a space-separated key id. +var unsafeVendorChars = regexp.MustCompile(`[^a-z0-9-]+`) + +// SearchPage is one page a plugin's search found. +type SearchPage struct { + Title string `json:"title"` + URL string `json:"url"` + Text string `json:"text"` + Age string `json:"age"` +} + +// SearchRefused is a plugin's search API turning the key away: the status +// it threw (401, 402, 403, 429…), which magpie treats as it does a built-in +// API's. +type SearchRefused struct { + Status int + Msg string + RetryAfter string +} + +func (e SearchRefused) Error() string { return e.Msg } + +// searchSlack is how long Go waits past the time the host is given. +const searchSlack = 5 * time.Second + +// RunSearch asks the plugin spec's search API id for the query, within the +// time ctx has (60s with none), starting the host if need be. A refusal of +// the key is a SearchRefused. +func RunSearch(ctx context.Context, spec, id, query string, count int, key, url string) ([]SearchPage, error) { + ms := int64(60_000) + if d, ok := ctx.Deadline(); ok { + ms = max(time.Until(d).Milliseconds(), 1) + } + var out struct { + Pages []SearchPage `json:"pages"` + Status int `json:"status"` + Error string `json:"error"` + RetryAfter string `json:"retryAfter"` + } + err := callWithTimeout(ctx, "search", map[string]any{ + "spec": spec, "id": id, "query": query, "count": count, "key": key, "url": url, "ms": ms, + }, &out, time.Duration(ms)*time.Millisecond+searchSlack) + if err != nil { + return nil, err + } + if out.Status != 0 { + return nil, SearchRefused{out.Status, out.Error, out.RetryAfter} + } + return out.Pages, nil +} + +// searchesPath is where the search APIs the host last loaded are noted, by +// plugin: provider.SearchVendorOf reads it, which mustn't start the host. +func searchesPath() string { return filepath.Join(settings.Dir(), "plugin-searches.json") } + +// SearchesPath is the note NotedSearches reads. +func SearchesPath() string { return searchesPath() } + +var searchesMu sync.Mutex + +// noteSearches notes which plugins the host loaded give search APIs, +// written whole and only when it changed. +func noteSearches(loaded []Loaded) { + m := map[string][]SearchDef{} + for _, l := range loaded { + if l.Error == "" && len(l.Searches) > 0 { + m[l.Spec] = l.Searches + } + } + b, _ := json.MarshalIndent(m, "", " ") + searchesMu.Lock() + defer searchesMu.Unlock() + old, err := steady.ReadFile(searchesPath()) + if err == nil && strings.TrimSpace(string(old)) == strings.TrimSpace(string(b)) { + return + } + if len(m) == 0 && errors.Is(err, fs.ErrNotExist) { + return + } + defer filememo.Forget() + if err := writeWhole(searchesPath(), append(b, '\n')); err != nil { + log.Printf("plugin searches: noting them: %v", err) + } +} + +// NotedSearches are the search APIs the plugins that are on in plugins.json +// gave when the host last loaded them, in plugins.json's order. It does not +// start the host. A note that can't be read or parsed gives none (and an +// error): the plugin's APIs are then unknown, not removed. +func NotedSearches() ([]PluginSearch, error) { + m, err := filememo.Read("plugin-searches", searchesPath(), func(b []byte) (map[string][]SearchDef, error) { + var m map[string][]SearchDef + if err := json.Unmarshal(b, &m); err != nil { + return nil, fmt.Errorf("%s: %w", searchesPath(), err) + } + return m, nil + }) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []PluginSearch + seen := map[string]bool{} + for _, e := range Load().Plugins { + if e.Off { + continue + } + for _, d := range m[e.Spec] { + p := PluginSearch{Spec: e.Spec, SearchDef: d} + if !seen[p.VendorID()] { + seen[p.VendorID()] = true + out = append(out, p) + } + } + } + return out, nil +} diff --git a/internal/plugin/search_test.go b/internal/plugin/search_test.go new file mode 100644 index 000000000..abc4d2b2c --- /dev/null +++ b/internal/plugin/search_test.go @@ -0,0 +1,95 @@ +package plugin + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// A plugin's search hook (testdata/search): the host lists the APIs with an +// id magpie can use and an execute, leaves out the rest, and notes them for +// the provider package, which reads the note without starting the host and +// only for plugins that are on. A search is run with the user's key and +// address, its results read from a list or {results}, a throw with a +// status is a refused key, and one that never answers is ended. +func TestPluginSearch(t *testing.T) { + sandbox(t) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/search") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + loaded, err := Plugins(ctx) + if err != nil || len(loaded) != 1 { + t.Fatalf("%v %v", loaded, err) + } + var ids []string + for _, d := range loaded[0].Searches { + ids = append(ids, d.ID) + } + if strings.Join(ids, " ") != "fake own" { + t.Fatalf("searches = %+v", loaded[0].Searches) + } + if d := loaded[0].Searches[0]; d.Name != "Fake Search" || d.KeysURL != "https://example.com/keys" || d.KeyOptional || d.NeedURL { + t.Errorf("fake = %+v", d) + } + if d := loaded[0].Searches[1]; !d.NeedURL { + t.Errorf("own = %+v", d) + } + + ns, err := NotedSearches() + if err != nil || len(ns) != 2 || ns[0].VendorID() != ShortName(Name(abs))+":fake" || ns[0].Spec != abs { + t.Fatalf("noted = %+v, %v", ns, err) + } + + pages, err := RunSearch(ctx, abs, "fake", "go", 6, "k1", "http://x") + if err != nil || len(pages) != 2 || pages[0].Title != "T go" || pages[0].URL != "https://example.com/6" || + pages[0].Text != "key k1 url http://x" || pages[0].Age != "2026" { + t.Errorf("pages = %+v, %v", pages, err) + } + _, err = RunSearch(ctx, abs, "fake", "go", 6, "spent", "") + var r SearchRefused + if !errors.As(err, &r) || r.Status != 429 || r.RetryAfter != "30" || !strings.Contains(r.Msg, "quota spent") { + t.Errorf("a refused key: %#v", err) + } + if _, err := RunSearch(ctx, abs, "fake", "go", 6, "boom", ""); err == nil || !strings.Contains(err.Error(), "it broke") || errors.As(err, &r) { + t.Errorf("a failure: %v", err) + } + if _, err := RunSearch(ctx, abs, "fake", "go", 6, "shape", ""); err == nil || !strings.Contains(err.Error(), "neither a list") { + t.Errorf("a wrong shape: %v", err) + } + if _, err := RunSearch(ctx, abs, "nothing", "go", 6, "", ""); err == nil || !strings.Contains(err.Error(), "no search API nothing") { + t.Errorf("an unknown API: %v", err) + } + short, stop := context.WithTimeout(ctx, 400*time.Millisecond) + t0 := time.Now() + _, err = RunSearch(short, abs, "fake", "go", 6, "hang", "") + stop() + // the host ends it at 400ms; Go's own backstop 5s later + if err == nil || time.Since(t0) > 4*time.Second { + t.Errorf("a search that never answers: %v after %s", err, time.Since(t0)) + } + if _, err := RunSearch(ctx, abs, "fake", "go", 6, "k1", ""); err != nil { + t.Errorf("the host after a search ran out of time: %v", err) + } + + // off: not listed + if err := SetOff(abs, true); err != nil { + t.Fatal(err) + } + if ns, err := NotedSearches(); err != nil || len(ns) != 0 { + t.Errorf("with the plugin off: %+v, %v", ns, err) + } + // a note that can't be read is an error, never "none, so remove" + if err := os.WriteFile(searchesPath(), []byte("{half"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := NotedSearches(); err == nil { + t.Error("a corrupt note counted as no searches") + } +} diff --git a/internal/plugin/testdata/search/index.js b/internal/plugin/testdata/search/index.js new file mode 100644 index 000000000..cd1dcf81c --- /dev/null +++ b/internal/plugin/testdata/search/index.js @@ -0,0 +1,25 @@ +// A plugin giving web search APIs (the search hook), which magpie lists +// beside Tavily and the rest. No network: each answers from its arguments. +export default async () => ({ + search: { + fake: { + name: "Fake Search", + keysURL: "https://example.com/keys", + async execute({ query, count, key, url }) { + if (key === "spent") { + const e = new Error("quota spent for " + key) + e.status = 429 + e.retryAfter = 30 + throw e + } + if (key === "boom") throw new Error("it broke") + if (key === "hang") await new Promise(() => {}) + if (key === "shape") return "not a list" + return { results: [{ title: "T " + query, url: "https://example.com/" + count, content: "key " + key + " url " + url, date: "2026" }, null, { title: 5 }] } + }, + }, + own: { name: "Own", keyOptional: true, url: true, execute: async () => [] }, + "Bad Id": { name: "x", execute: async () => [] }, + noexec: { name: "x" }, + }, +}) diff --git a/internal/plugin/testdata/search/package.json b/internal/plugin/testdata/search/package.json new file mode 100644 index 000000000..7b8616c5b --- /dev/null +++ b/internal/plugin/testdata/search/package.json @@ -0,0 +1,6 @@ +{ + "name": "opencode-search-example", + "version": "1.0.0", + "type": "module", + "main": "index.js" +} diff --git a/internal/provider/search_api.go b/internal/provider/search_api.go index 60cc11e3c..e151609d2 100644 --- a/internal/provider/search_api.go +++ b/internal/provider/search_api.go @@ -10,6 +10,8 @@ import ( "net/url" "slices" "strings" + + "github.com/yetone/magpie/internal/plugin" ) // SearchAPI is a web search API the user gave magpie a key to. @@ -50,8 +52,18 @@ type SearchVendor struct { // gateway's askSearchAPI): a base URL given ending in one of them is // that base, so the path isn't asked twice (/search/search, #509) Paths []string + // Plugin is the spec of the plugin that gives this API (its search + // hook), "" for one of magpie's own; PluginID is its id there. The + // plugin asks it (plugin.RunSearch); ID is plugin.PluginSearch.VendorID. + Plugin, PluginID string + // NeedURL: a plugin's API the user gives an address for, as a SearXNG + NeedURL bool } +// WantsURL is whether the user must give its address (a SearXNG's, or a +// plugin's that asked for one). +func (v SearchVendor) WantsURL() bool { return v.Base == "" && (v.Plugin == "" || v.NeedURL) } + // YouFreeSearch is You.com's search that takes no key (#1626): 100 // searches a day for each address, then 429. With a key, You.com is // asked at its Base, ydc-index.io, instead. @@ -75,13 +87,33 @@ var SearchVendors = []SearchVendor{ {ID: "searxng", Name: "SearXNG", KeyOptional: true, Paths: []string{"/search"}}, } -// SearchVendorOf is the vendor by its id. +// AllSearchVendors are SearchVendors and the search APIs the plugins that +// are on give (their search hook), after them. A plugin note that can't be +// read adds none. +func AllSearchVendors() []SearchVendor { + out := slices.Clone(SearchVendors) + ps, _ := plugin.NotedSearches() + for _, p := range ps { + out = append(out, SearchVendor{ID: p.VendorID(), Name: p.Name, KeysURL: p.KeysURL, KeyOptional: p.KeyOptional, + Plugin: p.Spec, PluginID: p.ID, NeedURL: p.NeedURL}) + } + return out +} + +// SearchVendorOf is the vendor by its id: one of magpie's, or a plugin's. func SearchVendorOf(id string) (SearchVendor, bool) { i := slices.IndexFunc(SearchVendors, func(v SearchVendor) bool { return v.ID == id }) - if i < 0 { + if i >= 0 { + return SearchVendors[i], true + } + if !strings.Contains(id, ":") { return SearchVendor{}, false } - return SearchVendors[i], true + all := AllSearchVendors() + if i := slices.IndexFunc(all[len(SearchVendors):], func(v SearchVendor) bool { return v.ID == id }); i >= 0 { + return all[len(SearchVendors)+i], true + } + return SearchVendor{}, false } // Keys are the keys in Key: one, or several the user gave separated by @@ -152,7 +184,7 @@ func (a SearchAPI) ownBase() string { // with a key where it needs one (a SearXNG, You.com, may not). func (a SearchAPI) Ready() bool { v, known := SearchVendorOf(a.Vendor) - return known && a.Base() != "" && (a.Key != "" || v.KeyOptional) + return known && (a.Base() != "" || (v.Plugin != "" && !v.NeedURL)) && (a.Key != "" || v.KeyOptional) } // check says what is wrong with a search API the user gives. @@ -160,7 +192,7 @@ func (a SearchAPI) check() error { v, ok := SearchVendorOf(a.Vendor) if !ok { var ids []string - for _, v := range SearchVendors { + for _, v := range AllSearchVendors() { ids = append(ids, v.ID) } return fmt.Errorf("no search API %q: one of %s", a.Vendor, strings.Join(ids, ", ")) @@ -182,6 +214,9 @@ func (a SearchAPI) check() error { if a.Vendor == "searxng" && a.URL == "" { return fmt.Errorf("SearXNG needs its address, as url=https://…") } + if v.Plugin != "" && v.NeedURL && a.URL == "" { + return fmt.Errorf("%s needs its address, as url=https://…", a.Name()) + } if a.Key == "" && !v.KeyOptional { return fmt.Errorf("%s needs its API key", a.Name()) }