plugin: magpie's web search is the Search plugin on the gateway's tool point (P3)

The third P3 point after observer/rotation, groups and middleware: the
tool point (internal/gwtool). A plugin serves a tool by name while it is
on; the process serving the gateway gates on it (Gate in ListenAndServe),
and a process not serving the gateway (CLI, TUI) has every tool, as
before.

plugins/search serves gwtool.WebSearch. Off, magpie offers and answers no
search of its own: the stand-in web_search isn't given to a model that
can't search, the search MCP server and Codex's search in ChatGPT's place
say "turn the Web search plugin on", and neither a search API nor a Kimi
Code plan's own search service is asked. A vendor that searches by itself
is still sent its own web_search. It is Essential and stays on while a
search API is set up or a searcher is picked (InUse); a providers.json or
settings.json that can't be read counts as unknown, so it stays on.

Settings → Models' Web search section stays visible with the plugin off:
the plugin can only be off when nothing is set up there, and adding a
search API there is what turns it back on (as Privacy does for redact).

Run at this head (rebased on origin/main 35aa50cfb):
- go test -count=1 ./... (full suite): 63 packages ok, none failed
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, chromium and webkit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw pass
- TestSearchOnAndOff, TestServingGatesTools, plugins/search tests

Broken by hand, each test went red: canSearch ungated, searchesOwn
ungated, webSearch ungated, no Gate in ListenAndServe, Apply serving
nothing, InUse ignoring the searcher, SearchAPIsSet swallowing the read
error, the gate never released.

Real use (built magpie, sandbox HOME/XDG_CONFIG_HOME, gateway on
127.0.0.1:3592, fake vendor and fake Tavily on 3591):
- on with a Tavily API set: a plain chat model was sent Read + web_search;
  MCP /mcp/magpie/web-search returned the fake's result
- `plugin builtin off search` with the API set: refused, "in use"
- API removed, turned off: the plain model got Read only; a native
  Anthropic provider still got its web_search; MCP answered isError with
  "turn the Web search plugin on"
- API added back: the plugin read "on, in use" and web_search was offered
  again
Not tried: a real search vendor or a real Kimi plan (fakes only).
This commit is contained in:
yetone
2026-10-15 16:45:51 +08:00
parent 35aa50cfb3
commit 9d97fd0733
15 changed files with 487 additions and 17 deletions
+19 -3
View File
@@ -12,7 +12,8 @@ P2 so far (a page moved out of the core whole: its code, styles and words:
Sessions, Library, Routing and Usage), and P3 so far (the gateway's
extension points: the observer, with OTel export as its first plugin; the
router strategy, with the routings besides Smart and the user's groups; and
the middleware point, with the JS gateway middleware and privacy masking). OpenCode plugins (npm packages in
the middleware point, with the JS gateway middleware and privacy masking;
and the tool point, with web search). OpenCode plugins (npm packages in
the plugin host) are a different thing; see
[provider and plugin ownership](provider-plugins.md) and
[gateway middleware](gateway-middleware.md).
@@ -27,7 +28,7 @@ the plugin host) are a different thing; see
| Ctx | What `Apply` gets: `OnDispose(f)`, `Contribute(slot, key)`, `Provide(name, v)` (withdrawn when it goes), `Service(name)`, and its composed `Config`. Disposers run in reverse, each one's panic logged and the rest still run. | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go) |
| plugins.yml | `appdir.Config()/plugins.yml`: `preset` (`essentials` or `all`) and `plugins`, rows of `{id, enabled, config}` holding only what the user set. | [`config.go`](../../internal/pluginrt/config.go) |
| Settings schema | `SchemaOf(Settings)` makes a JSON Schema object of the struct, in its fields' order (`x-order`): each exported field with a json name is a setting, of `bool`, an int, `float64` or `string`, with tags `title` (English; the window translates it), `description`, `enum` (comma separated) and `min`/`max`. Its values are the defaults. A field a form can't draw, or a tag that doesn't parse, panics at `Register`. `Schema.Validate` takes a value only as the schema allows it (a JSON float64 or a YAML int for an integer); `SetConfig(id, config)` writes the user's row through it, and `Compose` leaves out a value edited into plugins.yml by hand that it doesn't allow, so the default stands. | [`schema.go`](../../internal/pluginrt/schema.go), [`config.go`](../../internal/pluginrt/config.go) |
| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. `rotation` (P3), the routings besides Smart, is Essential and in use while a provider or group is routed by one of them. `middleware` (P3), the JS gateway middleware, is Essential and in use while plugins.json has a middleware on (`middleware.On`). `redact` (P3), privacy masking, is Essential and in use while Settings → Privacy asks for any masking (`masking.Wanted`). `usage` (P2), the Usage page, is Essential too, with no `InUse`: what it shows the gateway counts anyway, and the tray panel's Usage tab still shows the allowances with it off. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) |
| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. `rotation` (P3), the routings besides Smart, is Essential and in use while a provider or group is routed by one of them. `middleware` (P3), the JS gateway middleware, is Essential and in use while plugins.json has a middleware on (`middleware.On`). `redact` (P3), privacy masking, is Essential and in use while Settings → Privacy asks for any masking (`masking.Wanted`). `search` (P3), magpie's web search, is Essential and in use while a search API is set up or a searcher is picked. `usage` (P2), the Usage page, is Essential too, with no `InUse`: what it shows the gateway counts anyway, and the tray panel's Usage tab still shows the allowances with it off. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) |
The boundary is checked by `TestPluginsImportOnlyCore`: no package outside
`plugins/` imports one (but `main.go`, through `plugins/all`), a plugin never
@@ -215,7 +216,22 @@ failure policy, in [`internal/gwmw`](../../internal/gwmw/gwmw.go):
| `gwmw.Masker` | Masks what magpie sends a vendor and puts the values back in what comes back: `JSON`, `Text`, `Restore` and `Writer`. `Mask(m)` serves one until its remove (the last registered serves). It fails closed: `Masking(wanted)` is the masker for a request, or `ErrUnmasked` when the settings ask for masking and none serves, and `Safely` makes a masker that panics an error. The gateway's call sites (`serve`, count_tokens, embeddings and audio, transcriptions, images, video, the search stand-ins and their queries, the Codex backend) answer either with 503 "…nothing was sent", and the vendor gets nothing. `Served`, with none, asks the gate's refresh (the gateway's is `pluginrt.Refresh`, set by `gwmw.Refresh` in `ListenAndServe`) at most once a second and never from inside one, then looks again, so masking turned on a moment ago turns the plugin on for the request that needs it. | [`gwmw.go`](../../internal/gwmw/gwmw.go), [`redact.go`](../../internal/gateway/redact.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| `plugins/redact` | Requires `settings` and `gateway`, Essential. Apply serves `masking.Masker`, which reads settings.json on each call and masks with `internal/redact` as before (it lives in `internal/masking` because `settings` imports `redact`). `InUse` is `masking.Wanted`: *Mask secrets*, *Mask personal data* or a word of the user's own; settings.json that can't be read is an error, so it stays on. Since it is in use whenever masking is asked for, it can only be off while nothing is; the 503 is for a refresh not yet seen or a plugins.yml edited by hand. | [`redact.go`](../../plugins/redact/redact.go), [`masking.go`](../../internal/masking/masking.go) |
The other points follow in this order: tool (search), then budget.
## Gateway extension points (P3): tool
The tool point is the tools magpie answers itself for an agent, in place of
the vendor. Web search is the one now: the stand-in `web_search` a model
that can't search is given, the search MCP server, and Codex's search when
ChatGPT can't answer it ([Gateway routing](gateway-routing.md)). A vendor
that searches by itself is never the point's: its own `web_search` goes to
it, on or off.
| Part | What it does | Source |
| --- | --- | --- |
| `gwtool` | `Serve(name)` serves a tool until its remove; `Gate()` makes every tool wait on `Serve` until its stop; `Served(name)` is not gated, or served. The gateway holds `Gate` while it serves (`ListenAndServe`, `TestServingGatesTools`), so a process not serving it (the CLI, the TUI, an agent's config written there) has every tool, as before the point. `WebSearch` is the search's name. | [`gwtool.go`](../../internal/gwtool/gwtool.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| Off | `searchServed` gates the three places every search path goes through: `canSearch` (the stand-in tool, `/v1/models`' search note to another magpie, the subscriptions' search, `CanSearch` for the agents' rows), `searchesOwn` (a Kimi Code or WorkBuddy plan's own search service, a Google sign-in's Gemini) and `webSearch` itself, which answers `errSearchOff` without asking a searcher or a search API. So off, a request with `web_search` goes to the vendor as it does with no searcher set up, and the MCP server and Codex's search say the plugin is off (`TestSearchOnAndOff`). | [`search.go`](../../internal/gateway/search.go), [`search_api.go`](../../internal/gateway/search_api.go), [`search_kimi.go`](../../internal/gateway/search_kimi.go) |
| `plugins/search` | Requires `settings` and `gateway`, Essential. Apply serves `gwtool.WebSearch`. `InUse` counts the search APIs set up (`provider.SearchAPIsSet`, the file alone) and a searcher picked in Settings (neither magpie's pick nor off); an unreadable providers.json or settings.json is an error, so it stays on. The gateway's `KeepFresh` watches both files, so a search API added from the CLI or the window turns it on within 2s. | [`search.go`](../../plugins/search/search.go) |
The last point is budget.
## Source of truth and composing
+5 -1
View File
@@ -31,7 +31,7 @@ import (
"github.com/yetone/magpie/internal/awake"
"github.com/yetone/magpie/internal/gwmw"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/provider"
@@ -487,6 +487,10 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
}
})
defer stopGroups()
// and magpie's own tools (its web search) are offered and answered
// while the plugin serving each is on (gwtool)
stopTools := gwtool.Gate()
defer stopTools()
// and a request masking is wanted for, with no masker served, turns
// plugins/redact on as it is sent rather than being refused until
// KeepFresh's next look (gwmw.Served)
+18
View File
@@ -9,6 +9,7 @@ import (
"github.com/yetone/magpie/internal/agentenv"
"github.com/yetone/magpie/internal/gwmw"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/masking"
"github.com/yetone/magpie/internal/middleware"
"github.com/yetone/magpie/internal/provider"
@@ -24,6 +25,7 @@ func TestMain(m *testing.M) {
serveRotation()
groupsServed = provider.ServeGroups()
serveMiddleware()
searchOn = gwtool.Serve(gwtool.WebSearch)
code, err := isolatedTests(m)
if err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -178,3 +180,19 @@ func withoutGroups(t *testing.T) {
groupsServed = provider.ServeGroups()
})
}
// searchOn is plugins/search on: the gateway's tests offer and answer
// magpie's web search, as a user with it on has.
var searchOn func()
// withoutSearch is plugins/search off for t, in a process serving the
// gateway (gwtool.Gate): magpie's web search is neither offered nor
// answered.
func withoutSearch(t *testing.T) {
searchOn()
stop := gwtool.Gate()
t.Cleanup(func() {
stop()
searchOn = gwtool.Serve(gwtool.WebSearch)
})
}
+13
View File
@@ -15,6 +15,7 @@ import (
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
@@ -524,6 +525,9 @@ func (s *Server) webSearch(ctx context.Context, query string) (string, []Hit, er
// is set to (#1522: Codex asked while a "direct" provider served the
// turn dialed chatgpt.com directly)
ctx = netproxy.With(ctx, "")
if !searchServed() {
return "", nil, errSearchOff
}
if settings.Load().Searcher == "off" {
if len(provider.SearchAPIs()) == 0 {
return "", nil, errNoSearcher
@@ -567,6 +571,15 @@ func (s *Server) webSearch(ctx context.Context, query string) (string, []Hit, er
var errNoSearcher = errors.New("no provider that can search the web, nor a search API, is set up in magpie")
// errSearchOff is a search asked of magpie while plugins/search is off.
var errSearchOff = errors.New("magpie's web search is off: turn the Web search plugin on in magpie's Settings → Plugins")
// searchServed is whether plugins/search serves magpie's web search here
// (the gateway's tool point, gwtool): off, magpie neither offers its
// web_search nor answers one, and a vendor that searches by itself still
// does.
func searchServed() bool { return gwtool.Served(gwtool.WebSearch) }
// searchersInTurn is how many searchers a search is asked of, in turn,
// before it goes to the search APIs.
const searchersInTurn = 3
+6 -2
View File
@@ -35,9 +35,13 @@ type foundPage struct {
Age string // how old the search said it is, "" when it didn't
}
// canSearch is whether magpie can answer its web_search tool: a provider
// searches for it, or a search API does.
// canSearch is whether magpie can answer its web_search tool: plugins/search
// is on (searchServed), and a provider searches for it, or a search API
// does.
func canSearch() bool {
if !searchServed() {
return false
}
if _, _, ok := searcher(); ok {
return true
}
+2 -2
View File
@@ -52,9 +52,9 @@ func canSearchFor(p provider.Provider) bool {
// searchesOwn is whether p searches for its own models: by its Kimi Code
// plan's or WorkBuddy plan's search service (#1798), or a Google sign-in's
// own Gemini. Never with provider search Off in Settings (#1483), which
// leaves the search APIs alone.
// leaves the search APIs alone, nor with plugins/search off.
func searchesOwn(p provider.Provider) bool {
if settings.Load().Searcher == "off" {
if !searchServed() || settings.Load().Searcher == "off" {
return false
}
return provider.KimiCodeSearch(p) != "" || wbSearches(p) || googleAccount(p) && searcherModel(p) != ""
+160
View File
@@ -0,0 +1,160 @@
package gateway
import (
"context"
"errors"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/provider"
)
// The tool point's web search with plugins/search on and off, for a user
// with a search API and a Kimi Code plan that searches by itself. On,
// magpie offers its web_search to a model that can't search and answers
// it with the API or the plan's own search service. Off, it offers none,
// the request goes to the vendor without it, and a search asked of magpie
// anyway (the search MCP server, Codex's in ChatGPT's place) says the
// plugin is off without asking the API or the plan. A vendor that
// searches by itself is sent its own web_search either way.
func TestSearchOnAndOff(t *testing.T) {
fresh(t)
relay, seen := relayOfEvery(t)
kimi := newKimiPlan(t)
plan := provider.Provider{ID: "kimi", Name: "Kimi Code", Preset: "kimi-code-cn", Key: "sk-kimi",
Chat: kimi.URL + "/coding/v1", Models: []string{"kimi-for-coding"}}
if err := provider.Save(plan); err != nil {
t.Fatal(err)
}
f := newSearchAPIs(t)
if err := provider.SetSearchAPI(f.api("tavily", "tvly-k")); err != nil {
t.Fatal(err)
}
s := New()
ask := func(native bool) string {
t.Helper()
p := provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"custom-model"}, Searches: native}
if native {
p.Anthropic = relay.URL
} else {
p.Chat = relay.URL + "/v1"
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
_, before := seen()
body := `{"model":"relay/custom-model","max_tokens":100,"messages":[{"role":"user","content":"news?"}],"tools":[{"name":"Read","input_schema":{"type":"object"}},{"type":"web_search_20250305","name":"web_search"}]}`
if code, reply := post(t, "/v1/messages", body); code != 200 {
t.Fatalf("native %v: %d %s", native, code, reply)
}
paths, bodies := seen()
if len(bodies) != len(before)+1 {
t.Fatalf("native %v: upstream calls %v", native, paths[len(before):])
}
sent := bodies[len(bodies)-1]
if !strings.Contains(sent, "Read") {
t.Fatalf("native %v: the agent's own tool was dropped: %s", native, sent)
}
return sent
}
mcp := func() (string, error) {
return s.searchMCPRun(httptest.NewRequest("POST", "/mcp/search", nil), "latest go")
}
// on
if !CanSearch() || !canSearchFor(provider.Provider{}) || !searchesOwn(plan) {
t.Fatal("on: magpie's search not offered")
}
if !strings.Contains(ask(false), "web_search") {
t.Error("on: a model that can't search wasn't given magpie's web_search")
}
if !strings.Contains(ask(true), "web_search_20250305") {
t.Error("on: a vendor that searches by itself wasn't sent its own web_search")
}
if _, err := mcp(); err != nil {
t.Errorf("on: MCP search: %v", err)
}
if _, _, err := s.webSearch(searchingOn(context.Background(), plan), "latest go"); err != nil {
t.Errorf("on: the plan's own search: %v", err)
}
f.mu.Lock()
asked := len(f.asked)
f.mu.Unlock()
kimi.mu.Lock()
searched := len(kimi.searched)
kimi.mu.Unlock()
if asked == 0 || searched == 0 {
t.Fatalf("on: the API was asked %d times, the plan %d", asked, searched)
}
// off
withoutSearch(t)
if CanSearch() || canSearchFor(provider.Provider{}) || canSearchFor(plan) || searchesOwn(plan) {
t.Error("off: magpie's search still offered")
}
if sent := ask(false); strings.Contains(sent, "web_search") {
t.Errorf("off: magpie's web_search offered: %s", sent)
}
if !strings.Contains(ask(true), "web_search_20250305") {
t.Error("off: a vendor that searches by itself lost its own web_search")
}
if _, err := mcp(); err == nil || !strings.Contains(err.Error(), "Web search plugin") {
t.Errorf("off: MCP search said %v, not that the plugin is off", err)
}
for _, ctx := range []context.Context{context.Background(), searchingOn(context.Background(), plan)} {
if _, _, err := s.webSearch(ctx, "latest go"); !errors.Is(err, errSearchOff) {
t.Errorf("off: search said %v", err)
}
}
f.mu.Lock()
defer f.mu.Unlock()
kimi.mu.Lock()
defer kimi.mu.Unlock()
if len(f.asked) != asked || len(kimi.searched) != searched {
t.Errorf("off: the API was asked %v, the plan %v", f.asked[asked:], kimi.searched[searched:])
}
}
// The magpie serving the gateway, and only while it serves, offers
// magpie's tools only as their plugins serve them (gwtool.Gate): with
// plugins/search off, not its web search.
func TestServingGatesTools(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "127.0.0.1:0") // never where a magpie runs
searchOn()
defer func() { searchOn = gwtool.Serve(gwtool.WebSearch) }()
if !gwtool.Served(gwtool.WebSearch) {
t.Fatal("gated before serving")
}
s := New()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
done := make(chan error, 1)
go func() { done <- s.ListenAndServe(ctx) }()
deadline := time.Now().Add(3 * time.Second)
for {
s.lnMu.Lock()
ln := s.ln
s.lnMu.Unlock()
if ln != nil {
break
}
if time.Now().After(deadline) {
t.Fatal("gateway did not bind")
}
time.Sleep(10 * time.Millisecond)
}
if gwtool.Served(gwtool.WebSearch) {
t.Error("serving, with the plugin off: web search still served")
}
cancel()
if err := <-done; err != nil {
t.Fatal(err)
}
if !gwtool.Served(gwtool.WebSearch) {
t.Error("gate held after serving ended")
}
}
+12
View File
@@ -770,6 +770,9 @@ const I18N = {
"Privacy masking": "隐私遮盖",
"Secrets, personal data and your own words go to vendors as placeholders, and come back as they were": "密钥、个人信息和你自己的词以占位符发给服务商,回来时还原",
"Masking is on": "遮盖已开启",
"Models that can't search the web search with a provider that can, or a search API": "不能联网搜索的模型,借能搜索的提供商或搜索 API 来搜",
"1 search source set up": "已设置 1 个搜索来源",
"{n} search sources set up": "已设置 {n} 个搜索来源",
"In use, so it stays on": "正在使用,因此保持开启",
"Gateway page": "网关页面",
"The gateway's state and keys, how to connect a client, its models and recent calls": "网关的状态与密钥、客户端如何连接、它的模型和最近的调用",
@@ -4346,6 +4349,9 @@ const I18N = {
"Privacy masking": "隱私遮蓋",
"Secrets, personal data and your own words go to vendors as placeholders, and come back as they were": "金鑰、個人資料和你自己的詞以佔位符傳給服務商,回來時還原",
"Masking is on": "遮蓋已開啟",
"Models that can't search the web search with a provider that can, or a search API": "不能聯網搜尋的模型,借能搜尋的提供商或搜尋 API 來搜",
"1 search source set up": "已設定 1 個搜尋來源",
"{n} search sources set up": "已設定 {n} 個搜尋來源",
"In use, so it stays on": "正在使用,因此保持開啟",
"Gateway page": "閘道頁面",
"The gateway's state and keys, how to connect a client, its models and recent calls": "閘道的狀態與金鑰、用戶端如何連線、它的模型和最近的呼叫",
@@ -7894,6 +7900,9 @@ const I18N = {
"Privacy masking": "プライバシーマスキング",
"Secrets, personal data and your own words go to vendors as placeholders, and come back as they were": "シークレット、個人情報、自分で指定した語句はプレースホルダーとしてベンダーに送られ、戻るときに元に戻ります",
"Masking is on": "マスキングはオン",
"Models that can't search the web search with a provider that can, or a search API": "ウェブ検索できないモデルは、検索できるプロバイダーか検索 API で検索します",
"1 search source set up": "1 個の検索元を設定済み",
"{n} search sources set up": "{n} 個の検索元を設定済み",
"In use, so it stays on": "使用中のためオンのままです",
"Gateway page": "ゲートウェイページ",
"The gateway's state and keys, how to connect a client, its models and recent calls": "ゲートウェイの状態とキー、クライアントの接続方法、モデルと最近の呼び出し",
@@ -11456,6 +11465,9 @@ const I18N = {
"Privacy masking": "Datenschutz-Maskierung",
"Secrets, personal data and your own words go to vendors as placeholders, and come back as they were": "Geheimnisse, persönliche Daten und deine eigenen Wörter gehen als Platzhalter an Anbieter und kommen unverändert zurück",
"Masking is on": "Maskierung ist an",
"Models that can't search the web search with a provider that can, or a search API": "Modelle, die nicht im Web suchen können, suchen über einen Anbieter, der es kann, oder eine Such-API",
"1 search source set up": "1 Suchquelle eingerichtet",
"{n} search sources set up": "{n} Suchquellen eingerichtet",
"In use, so it stays on": "In Gebrauch, daher bleibt es an",
"Gateway page": "Gateway-Seite",
"The gateway's state and keys, how to connect a client, its models and recent calls": "Zustand und Schlüssel des Gateways, wie sich ein Client verbindet, seine Modelle und letzten Aufrufe",
+4 -4
View File
@@ -44,14 +44,14 @@ func TestBuiltinSwitch(t *testing.T) {
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if len(out) != 11 {
if len(out) != 12 {
t.Fatalf("the built-ins: %+v", out)
}
for _, b := range out {
// the Gateway, Routing and Usage pages, the routing strategies,
// the gateway middleware and privacy masking are essential: on in
// every preset
if b.On != (b.ID == "library" || b.ID == "gateway" || b.ID == "middleware" || b.ID == "redact" || b.ID == "rotation" || b.ID == "routing" || b.ID == "usage") || b.On != (b.State == pluginrt.Active) {
// the gateway middleware, privacy masking and web search are
// essential: on in every preset
if b.On != (b.ID == "library" || b.ID == "gateway" || b.ID == "middleware" || b.ID == "redact" || b.ID == "rotation" || b.ID == "routing" || b.ID == "search" || b.ID == "usage") || b.On != (b.State == pluginrt.Active) {
t.Fatalf("after library on: %+v", out)
}
}
+7 -5
View File
@@ -27,14 +27,16 @@ const PLUGINS = [
{ id: "redact", name: "Privacy masking", sub: "Secrets, personal data and your own words go to vendors as placeholders, and come back as they were", one: "Masking is on", many: "Masking is on" },
{ id: "rotation", name: "Routing strategies", sub: "The routings besides Smart: In order, In turn, Least used first, Weekly pace and By weight", one: "1 provider or group routed so", many: "{n} providers and groups routed so" },
{ id: "routing", name: "Routing", sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups", one: "1 group in use", many: "{n} groups in use" },
{ id: "search", name: "Web search", sub: "Models that can't search the web search with a provider that can, or a search API", one: "1 search source set up", many: "{n} search sources set up" },
{ id: "sessions", name: "Sessions", sub: "Your agents' past conversations: read, search, resume and export them", one: "Recording gateway conversations", many: "Recording gateway conversations" },
{ id: "usage", name: "Usage", sub: "Your allowances, what was spent and on what, each request, and what filled the context window" },
{ id: "warmups", name: "Warm-up and check-in", sub: "Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits", one: "1 warm-up or check-in on", many: "{n} warm-ups and check-ins on" },
];
// a new install's (the Essentials preset): all off but the Gateway, Routing
// and Usage pages, the routing strategies, the gateway middleware and privacy
// masking, which are essential, and two routing groups the user made
const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], middleware: [true, 0], otel: [false, 0], redact: [true, 0], rotation: [true, 0], routing: [true, 0], sessions: [false, 0], usage: [true, 0], warmups: [false, 0] };
// and Usage pages, the routing strategies, the gateway middleware, privacy
// masking and web search, which are essential, and two routing groups the
// user made
const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], middleware: [true, 0], otel: [false, 0], redact: [true, 0], rotation: [true, 0], routing: [true, 0], search: [true, 0], sessions: [false, 0], usage: [true, 0], warmups: [false, 0] };
// the Gateway page's settings, as pluginrt.SchemaOf makes them
const GATEWAY_SCHEMA = {
@@ -168,13 +170,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual([rt.on, rt.disabled], ["true", false], `${where}: the Routing page, on`);
const ro = rows.find((r) => r.id === "rotation");
assert.deepEqual([ro.on, ro.disabled], ["true", false], `${where}: the routing strategies, on`);
for (const id of ["middleware", "redact"]) {
for (const id of ["middleware", "redact", "search"]) {
const r = rows.find((r) => r.id === id);
assert.deepEqual([r.on, r.disabled], ["true", false], `${where}: ${id}, on`);
}
const us = rows.find((r) => r.id === "usage");
assert.deepEqual([us.on, us.disabled], ["true", false], `${where}: the Usage page, on`);
for (const r of rows.filter((r) => !["groups", "gateway", "middleware", "redact", "rotation", "routing", "usage"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
for (const r of rows.filter((r) => !["groups", "gateway", "middleware", "redact", "rotation", "routing", "search", "usage"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
await page.locator('#builtinList [data-id="groups"] [role="switch"]').click({ force: true });
await page.waitForTimeout(100);
assert.deepEqual(posts, [], `${where}: a locked switch posts nothing`);
+66
View File
@@ -0,0 +1,66 @@
// Package gwtool is the gateway's tool point (P3 of
// docs/subsystems/plugin-runtime.md): the tools magpie answers itself for
// an agent, in place of the vendor. A plugin serves a tool by its name
// while it is on (Serve). In the process serving the gateway (Gate), a
// tool no plugin serves is neither offered nor answered; a process not
// serving the gateway (the CLI, the TUI) has them all, as before the
// point was there.
//
// WebSearch is the one tool now, plugins/search's: magpie's web search for
// a model that can't search by itself. Off, a vendor that searches by
// itself still does; magpie offers no search of its own.
package gwtool
import "sync"
// WebSearch is magpie's web search: the stand-in web_search tool, the
// search MCP server and Codex's search when ChatGPT can't answer it.
const WebSearch = "web_search"
var gate struct {
sync.Mutex
gated int // Gate calls not yet stopped
served map[string]int // name → Serve calls not yet removed
}
// Gate makes every tool wait on Serve until stop: the gateway calls it as
// it starts serving.
func Gate() (stop func()) {
gate.Lock()
gate.gated++
gate.Unlock()
var once sync.Once
return func() {
once.Do(func() {
gate.Lock()
gate.gated--
gate.Unlock()
})
}
}
// Serve serves the tool name until remove: its plugin calls it while it
// is on.
func Serve(name string) (remove func()) {
gate.Lock()
if gate.served == nil {
gate.served = map[string]int{}
}
gate.served[name]++
gate.Unlock()
var once sync.Once
return func() {
once.Do(func() {
gate.Lock()
gate.served[name]--
gate.Unlock()
})
}
}
// Served says whether the tool name is offered and answered here now.
func Served(name string) bool {
gate.Lock()
defer gate.Unlock()
return gate.gated == 0 || gate.served[name] > 0
}
+16
View File
@@ -162,6 +162,22 @@ func SearchAPIs() []SearchAPI {
return slices.DeleteFunc(slices.Clone(load().Searches), func(a SearchAPI) bool { return !a.Ready() })
}
// SearchAPIsSet counts the search APIs that can be asked; a
// providers.json that can't be read is an error, not none.
func SearchAPIsSet() (int, error) {
f, err := read()
if err != nil {
return 0, err
}
n := 0
for _, a := range f.Searches {
if a.Ready() {
n++
}
}
return n, nil
}
// StoredSearchAPIs are the search APIs as saved, keys and all.
func StoredSearchAPIs() []SearchAPI { return load().Searches }
+1
View File
@@ -11,6 +11,7 @@ import (
_ "github.com/yetone/magpie/plugins/redact"
_ "github.com/yetone/magpie/plugins/rotation"
_ "github.com/yetone/magpie/plugins/routing"
_ "github.com/yetone/magpie/plugins/search"
_ "github.com/yetone/magpie/plugins/sessions"
_ "github.com/yetone/magpie/plugins/usage"
_ "github.com/yetone/magpie/plugins/warmups"
+49
View File
@@ -0,0 +1,49 @@
// Package search is magpie's web search for a model that can't search by
// itself: the agent's web_search tool, answered by a provider that can
// search or a search API set up in Settings. While a search API is set up
// or a searcher is picked, it stays on.
//
// It serves gwtool.WebSearch on the gateway's tool point (P3 of
// docs/subsystems/plugin-runtime.md). Off, magpie offers and answers no
// search of its own: the stand-in tool, the search MCP server and Codex's
// search in ChatGPT's place say there is no searcher, and a vendor that
// searches by itself still does.
package search
import (
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "search", API: "^1", Requires: []string{"settings", "gateway"}, Essential: true,
Name: "Web search", Sub: "Models that can't search the web search with a provider that can, or a search API",
One: "1 search source set up", Many: "{n} search sources set up",
InUse: InUse,
Apply: func(c *pluginrt.Ctx) error {
c.OnDispose(gwtool.Serve(gwtool.WebSearch))
return nil
},
})
}
// InUse counts the search APIs set up, and a searcher picked in Settings
// (neither magpie's pick nor off); a providers.json or settings that can't
// be read are not known, so it stays on.
func InUse() (int, error) {
n, err := provider.SearchAPIsSet()
if err != nil {
return 0, err
}
st, err := settings.LoadChecked()
if err != nil {
return 0, err
}
if st.Searcher != "" && st.Searcher != "off" {
n++
}
return n, nil
}
+109
View File
@@ -0,0 +1,109 @@
package search
import (
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/testenv"
)
func TestMain(m *testing.M) { testenv.Main(m) }
func manifest(t *testing.T) pluginrt.Manifest {
t.Helper()
for _, m := range pluginrt.Registered() {
if m.ID == "search" {
return m
}
}
t.Fatal("search not registered")
return pluginrt.Manifest{}
}
func sandbox(t *testing.T) {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, "cache"))
}
// In a process serving the gateway, on serves magpie's web search, off
// doesn't, on again does; a process not serving it has it either way.
func TestOnServesOffDoesNot(t *testing.T) {
sandbox(t)
if !gwtool.Served(gwtool.WebSearch) {
t.Fatal("not served outside the gateway")
}
stop := gwtool.Gate()
defer stop()
rt := pluginrt.New([]pluginrt.Manifest{manifest(t)})
defer rt.Stop()
served := func(want bool) {
t.Helper()
if ok := gwtool.Served(gwtool.WebSearch); ok != want {
t.Fatalf("search served: %v, want %v (%+v)", ok, want, rt.Statuses())
}
}
served(false)
rt.Reconcile(map[string]bool{"search": true}, nil)
served(true)
rt.Reconcile(map[string]bool{"search": false}, nil)
served(false)
rt.Reconcile(map[string]bool{"search": true}, nil)
served(true)
}
// In use while a search API is set up or a searcher is picked; magpie's
// pick or off: none; files that can't be read: not known.
func TestInUse(t *testing.T) {
sandbox(t)
count := func(want int) {
t.Helper()
if n, err := InUse(); err != nil || n != want {
t.Fatalf("in use %d %v, want %d", n, err, want)
}
}
count(0)
for _, s := range []string{"", "off"} {
if err := settings.Save(settings.Settings{Searcher: s}); err != nil {
t.Fatal(err)
}
count(0)
}
if err := settings.Save(settings.Settings{Searcher: "openai/gpt-5.4-mini"}); err != nil {
t.Fatal(err)
}
count(1)
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: "tvly-k"}); err != nil {
t.Fatal(err)
}
count(2)
if err := os.WriteFile(settings.Path(), []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
for _, bak := range []string{".bak", ".lastgood"} {
os.Remove(settings.Path() + bak)
}
if _, err := InUse(); err == nil {
t.Fatal("unreadable settings counted as known")
}
if err := os.Remove(settings.Path()); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(provider.Path(), []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
for _, bak := range []string{".bak", ".lastgood"} {
os.Remove(provider.Path() + bak)
}
if _, err := InUse(); err == nil {
t.Fatal("unreadable providers.json counted as known")
}
}