From 9b04c4e20ff8bf10c745a53f562f5007b82d007d Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 16 Oct 2026 20:17:43 +0800 Subject: [PATCH] plugin: async gateway request hooks, run in Bun before routing and after the reply (#2118) A package's magpie.hooks entry (or a *.hooks.{js,mjs,ts,mts} file) exports `async onRequest(body, ctx)` and an optional `onResponse(reply, ctx)`. They run in the Bun plugin host, so a hook can await I/O, for example a context service like PowerContext, which the sync moejs middleware can't. The gateway still makes one model request per client request. A hook adds context to the body; it doesn't register tools or run a loop, so magpie doesn't become an agent runtime. Ported from Tsukikage7/magpie#1. Changes from the fork: - The entry name is magpie.hooks / *.hooks.*. The fork's magpie.gateway / *.gateway.mjs is already the middleware's alias, so a hook importing node:fs was also loaded as moejs middleware and failed there. TestGatewayHookNamesApartFromMiddleware fails if the two sets overlap. - onRequest is rolled back, and counts as failed with no onResponse, when it throws, times out, returns non-JSON, or changes tools, tool_choice, function_call, functions, toolConfig, model or stream. - onResponse gets the client-facing reply, merged through the gateway's own stream decoder, collector and renderer (no second merger). - Codex's native passthrough (/backend-api/codex) runs the hooks too, without the sync middleware. - The run ends with the request handler, not the client connection. Codex hangs up on response.completed, and the reply it got is still captured as a success. TestGatewayHookSeesReplyAfterClientHangsUp is red on the old `r.Context().Err()` check and green with -count=3. - ctx.origin is host-derived (local / gateway-key / remote). Headers, keys and peer addresses never reach the hook. - Plugins page: a hook package shows a "Request hook" chip, a diagnostics line (outcome code, calls, avg ms, bytes, failures; no content), and Options. Strings are in en, zh, zh-TW, ja and de. Docs: docs/subsystems/gateway-request-hooks.md (new), provider-plugins.md, gateway-middleware.md, and site docs plugins.html in en, zh and ja. Real use, sandbox HOME on 127.0.0.1:3486 with the owner's real Codex Pro sign-in. The probe hook adds a codename note and logs both callbacks: - /v1/responses, /v1/messages, Gemini generateContent: stream and non-stream. onRequest's note reached the model (the answer had the codename), and onResponse got success=true and the whole reply. - /v1/chat/completions: with the probe also changing `model`, the change was rolled back (the reply came from the asked model) and no onResponse ran. Without that change, earlier: stream and non-stream success. - The real Codex CLI 0.162.1 `codex exec` through openai_base_url -> /backend-api/codex: the hook saw origin=local, agent=codex and the query; the answer had the codename; onResponse success=true (before the hang-up fix it never ran: the context was already cancelled). - `magpie plugin list` shows only "async gateway hook onRequest" for the hook package, no failed middleware. Tests (base origin/main 63be47717, macbook at load avg 220-340 from other sessions' suites): - gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean. go build and GOOS=linux -tags nogui build: ok. - go test ./... -timeout 45m: every package ok except: - agent, gateway and library timed out at 45m under the load; - gui's TestSetAnswersWhileDevinAndProvidersHang (#1375, also red on a clean 63be47717 run alone; commented there); - library's TestSkillRelinkKeepsUnreadableCopy, which passes -count=2 alone. Rerun at -timeout 150m: agent ok (4524s), library ok (2581s). gateway was ok except TestVisionWaitIsntTheDescribersTime's 300ms limit (#2444, commented), which passes -count=5 alone on this tree and on 63be47717. - internal/plugin and internal/gateway hook tests: ok. - GUI (chromium+webkit; en, zh, zh-TW, ja, de): plugin-gateway 12/12 twice. It failed earlier at load ~340, chromium only, on page.goto's 5s (#2542). All 43 plugin-*.test.cjs files and mobile-web are green except: - plugin-move: red on a clean 63be47717 too (#2399, commented); - plugin-moved-signin: one 5s waitFor under load, then 6/6 twice. Rebased onto ea3dee96a (21 commits; main touched host.go, host.js, i18n.js and the plugin docs; clean rebase), then rerun at the rebased head: - gofmt, vet (darwin, linux nogui, windows) and build: clean. - go test: plugin ok, cli ok, gateway -run 'Hook|Middleware|Codex|Plugin' ok. gui ok except TestMainWindowCorners, which was killed under load (#1936) and passes alone. - GUI: plugin-gateway 12/12, plugin-middleware 24/24, plugin-tools 22/22, plugin-agent 22/22. - Real account with the rebased binary: every protocol and the real Codex CLI gave the same results as above (codename answered, success=true, chat's model change rolled back). Co-authored-by: Tsukikage7 <65526564+Tsukikage7@users.noreply.github.com> --- docs/subsystems/README.md | 1 + docs/subsystems/gateway-middleware.md | 2 +- docs/subsystems/gateway-request-hooks.md | 113 +++++ docs/subsystems/provider-plugins.md | 2 + internal/cli/plugins_cli.go | 5 +- internal/gateway/codex_backend.go | 5 +- internal/gateway/gateway_hook_test.go | 436 ++++++++++++++++++ internal/gateway/gateway_hooks.go | 94 ++++ internal/gateway/middleware.go | 55 +++ internal/gui/assets/i18n.js | 60 +++ internal/gui/assets/plugins.js | 34 +- internal/gui/plugins.go | 19 +- internal/gui/plugins_gateway_test.go | 43 ++ internal/gui/tests/README.md | 7 + internal/gui/tests/plugin-gateway.test.cjs | 73 +++ internal/plugin/agent.go | 3 + internal/plugin/gateway.go | 235 ++++++++++ internal/plugin/gateway_test.go | 506 +++++++++++++++++++++ internal/plugin/host.go | 29 +- internal/plugin/host.js | 185 +++++++- internal/plugin/store.go | 3 + site/public/docs/ja/plugins.html | 8 + site/public/docs/plugins.html | 8 + site/public/docs/zh/plugins.html | 8 + 24 files changed, 1911 insertions(+), 23 deletions(-) create mode 100644 docs/subsystems/gateway-request-hooks.md create mode 100644 internal/gateway/gateway_hook_test.go create mode 100644 internal/gateway/gateway_hooks.go create mode 100644 internal/gui/plugins_gateway_test.go create mode 100644 internal/gui/tests/plugin-gateway.test.cjs create mode 100644 internal/plugin/gateway.go create mode 100644 internal/plugin/gateway_test.go diff --git a/docs/subsystems/README.md b/docs/subsystems/README.md index ce6b11b0e..b9cbfb23b 100644 --- a/docs/subsystems/README.md +++ b/docs/subsystems/README.md @@ -8,6 +8,7 @@ These pages describe current responsibilities, runtime paths, state, and contrac | Built-in plugins: registry, lifecycle, plugins.yml, presets, settings schemas, the window's kernel (slots, error boundary, kit) | [Plugin runtime](plugin-runtime.md) | | Plugins that run on the gateway's requests and replies | [Gateway middleware](gateway-middleware.md) | | Tools that plugins give, offered to every agent as an MCP server | [Plugin tools](plugin-tools.md) | +| Plugins that await context recall and observe completed replies | [Asynchronous gateway request hooks](gateway-request-hooks.md) | | Claude subscription turns across Claude Code runs | [Claude subscription bridge](claude-subscription-bridge.md) | | How the gateway picks a provider, key or account, and falls back | [Gateway routing and fallback](gateway-routing.md) | | Gateway Session Aggregation | [Gateway Session Aggregation](gateway-sessions.md) | diff --git a/docs/subsystems/gateway-middleware.md b/docs/subsystems/gateway-middleware.md index 04b3ff48a..78a627256 100644 --- a/docs/subsystems/gateway-middleware.md +++ b/docs/subsystems/gateway-middleware.md @@ -21,7 +21,7 @@ plugins.json is the source of truth for which middleware is installed and on, in ## Runtime path -1. `serveAgent` establishes the [gateway session identity and optional recording](gateway-sessions.md), then calls `Begin` on each registered `gwmw.Agent` (the JS chain's is `middleware.Begin`) with the request's protocol, model, stream flag, path and agent. With no middleware it calls `serve` directly. +1. `serveAgent` establishes the [gateway session identity and optional recording](gateway-sessions.md), runs any [asynchronous request hooks](gateway-request-hooks.md) through Bun, then calls `Begin` on each registered `gwmw.Agent` (the JS chain's is `middleware.Begin`) with the request's protocol, model, stream flag, path and agent. With no middleware it calls `serve` directly. 2. `Run.Request` passes the agent's body, in its own API, to each `onRequest` in turn. An object returned is the body the next middleware and the gateway get; `undefined` keeps the bytes as they were. `ctx.reject(status, message)` stops the chain, and the agent gets that error in its API's shape (`writeError`). 3. `Run.Wrap` wraps the response writer when some middleware has `onEvent` or `onResponse`. An SSE reply is split into events. Each event whose data is a JSON object goes to every `onEvent` that wants its name (`export const events`): an object replaces it, `null` drops it, and `undefined` writes the original bytes. `data: [DONE]` and other non-object data pass by. A whole JSON reply is buffered for `onResponse`, with `ctx.status` set. A reply with a `Content-Encoding` passes as-is. 4. `Run.End` returns the runtimes to their pools. diff --git a/docs/subsystems/gateway-request-hooks.md b/docs/subsystems/gateway-request-hooks.md new file mode 100644 index 000000000..8084b634f --- /dev/null +++ b/docs/subsystems/gateway-request-hooks.md @@ -0,0 +1,113 @@ +# Asynchronous gateway hooks + +Opt-in Bun hooks add external context before routing and observe completed replies. +The gateway makes one model request per client request. Tool declarations, tool +execution and subsequent inference rounds belong to the client. + +```mermaid +sequenceDiagram + participant Client + participant Magpie + participant Hook as Bun gateway hook + participant Model + Client->>Magpie: Request + Magpie->>Hook: await onRequest(body, ctx with host-derived origin) + Hook-->>Magpie: Context-enriched body, or original on failure + Magpie->>Model: One inference request + Model-->>Client: Live response through Magpie + Magpie--)Hook: onResponse(completedReply, ctx) + Note over Hook: Bounded best-effort notification +``` + +## Entry and request contract + +Declare `"magpie": {"hooks": "./context.hooks.ts"}` in package.json, +or install a `*.hooks.js`, `.mjs`, `.ts` or `.mts` file using `magpie plugin add`. +The names are apart from the JS gateway middleware's (`magpie.middleware`, +its alias `magpie.gateway`, `*.gateway.js`), so a hook that imports `node:fs` +is never also loaded as middleware. +Bun runs TypeScript directly. A gateway-only package does not need provider +main/exports, a client MCP installation, or a client skill. + +`export async function onRequest(body, ctx)` receives the client protocol JSON +before routing. Return a JSON object to add context; return `undefined` to keep +it. Mutations are rolled back when a hook throws, times out, returns invalid data, +or changes client tool declarations, tool choice, `model` or `stream` (the +gateway checked the caller's key against the model, and the client reads the +reply it asked for). A rolled-back hook counts as failed and gets no `onResponse` +for that request. It cannot reject requests or register tools. The synchronous middleware API remains available separately. + +Context fields: `protocol` (`chat`, `responses`, `anthropic`, `gemini`), `model`, +`stream`, `path`, `origin`, `agent`, `session`, `cwd`, `query`, package `options`, private +request `state`, an `AbortSignal` and `report(code, bytes)`. Headers and client +credentials are not forwarded to the hook. Query extraction keeps original model +input intact while excluding client environment/instruction notices from recall. +Empty identity fields must not be interpreted as authenticated user identity. + +`origin` is host-derived: `local` for a direct loopback request without +forwarding headers or a named gateway key, `gateway-key` for a named key +(including one used on loopback), otherwise `remote`. Forwarded traffic stays +remote even with `MAGPIE_TRUST_PROXY=1`. No key, key name, peer address or +client-supplied origin claim is exposed. Missing origin on an older host means +unknown. This classification is not a user identity; plugins that export +conversations must obtain their own explicit opt-in and default to skipping +non-local or unknown origins. It is available in both lifecycle callbacks. + +The `gatewayTimeoutMs` option accepts 100–10000 ms (default 1000 ms). The +entire request hook chain is bounded to ten seconds, with an eleven-second host +startup/RPC limit, including waiting for a host already starting during provider +discovery. The first request waits within that budget rather than skipping its +hook because startup holds the host lock. Client cancellation aborts the wait +and request-hook I/O. Hooks run in +plugin order. Failure keeps the last accepted request; diagnostics contain fixed +outcome codes and byte counts rather than private content. + +## Completion notification + +`export async function onResponse(reply, ctx)` is optional. It observes the +client-facing reply after response middleware finishes writing it. Streaming +bytes are forwarded immediately; a bounded copy is consolidated into that +protocol's response shape only for this callback, through the same decoder, +collector and renderer the gateway translates with (a Responses stream's +`response.completed` response is the reply as it is). The callback cannot rewrite +client output. `ctx.request` contains the accepted request, `ctx.success` reports +completion, and the same per-hook `ctx.state` links recall with capture. + +Notification is fire-and-forget, with a fresh timeout signal independent of the +finished HTTP request. It never waits for an observer's network operation before +returning client EOF. The run ends with the request handler, not with the client's +connection: a client that hangs up once the reply is whole (Codex closes on +`response.completed`) still gets a successful capture. Request failure, an +incomplete stream (a client gone mid-reply included) or a capture over 8 MiB +prevents successful capture (`success: false`, possibly a null +reply). This is best-effort delivery, not a durable queue: shutdown, host +retirement and capacity limits may discard notifications. Hooks must not blindly +retry non-idempotent external writes. + +Host request state is limited to 128 runs and expires after 15 minutes. The +response RPC has an eleven-second limit; each callback uses the configured +bounded hook timeout. Request-owned state is released after notification. + +## Sources and verification + +- `internal/plugin/gateway.go`: entry discovery, cancellation, completion dispatch. +- `internal/plugin/host.js`: async execution, rollback, state and deadlines. +- `internal/gateway/middleware.go`: `gatewayHooks`, before routing and around the + middleware, so `onResponse` sees what the agent got. `serveAgent` runs it for + every agent request; Codex's own ChatGPT sign-in passthrough + (`codex_backend.go`) runs it without the synchronous middleware. +- `internal/gateway/gateway_hooks.go`: bounded response observation and + `gatewayReply`, a stream made one reply. +- `internal/plugin/gateway_test.go` and `internal/gateway/gateway_hook_test.go`: + failures, cancellation, ownership and real HTTP streaming. + +Follow [provider plugin verification](provider-plugins.md#verification) to use +isolated HOME and resolved Go/Bun executables. Targeted race acceptance: + +```sh +go test -race -tags nogui ./internal/plugin ./internal/gateway -run '^TestGateway|^TestAsyncGateway' -count=1 +``` + +Service deployment, automatic installation and gateway-owned tool loops are +outside this contract. A concrete companion integration is PowerContext recall +via `/v1/context/prepare` and conversation capture via `/v1/sources/content`. diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 12a9a1122..39ece7e0f 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -179,6 +179,8 @@ The GUI's plugin integration includes `subOf`, `pluginSubs`, and `startPluginSig ## Verification +Plugins may also declare a provider-independent `magpie.hooks` entry, including pure gateway packages and mixed provider/Pi packages. Its asynchronous request contract and verification are documented in [Gateway request hooks](gateway-request-hooks.md). Existing provider hooks still use their normal entry path. + [`migrate_notice_test.go`](../../internal/provider/migrate_notice_test.go) includes `TestMovedBuiltinsSayTheirPlugin`, which checks that moved built-ins tell contributors which plugin serves them. Migration tests live beside [`migrate.go`](../../internal/provider/migrate.go). Gateway parity tests in [`plugin_parity_test.go`](../../internal/gateway/plugin_parity_test.go) and other `plugin_*_test.go` files compare or exercise plugin paths. A built-in test alone does not establish moved-user behavior. Inspect each test's fixture to confirm that it covers the provider and operation being changed. diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.go index f5cc93b0c..4afd3d8c5 100644 --- a/internal/cli/plugins_cli.go +++ b/internal/cli/plugins_cli.go @@ -20,7 +20,7 @@ import ( ) const pluginUsage = `usage: magpie plugin [list] [--json] - magpie plugin add install an OpenCode provider plugin, a pi package or a gateway middleware (opencode-gemini-auth, pi-antigravity, github:owner/repo, ./my-plugin.js, ./alias.middleware.js) + magpie plugin add install an OpenCode provider plugin, a pi package or a gateway hook/middleware (opencode-gemini-auth, pi-antigravity, github:owner/repo, ./my-plugin.js, ./alias.middleware.js, ./recall.hooks.ts) magpie plugin rm remove one magpie plugin update install the newest version of each magpie plugin on|off turn one on or off @@ -235,6 +235,9 @@ func listPlugins(ctx context.Context, asJSON bool) error { what += " " + muted.Render("("+strings.TrimSpace(n+" "+plugin.Installed(e.Spec))+")") } fmt.Printf("%s %s\n", what, state) + if plugin.Gateway(plugin.Target(e.Spec)) != "" { + fmt.Println(" " + muted.Render("async gateway hook") + " onRequest") + } // its calls are counted in the gateway's process, not this one if m, ok := mws[e.Spec]; ok && !e.Off { if m.Error != "" { diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 6e06c1e81..8616e03ac 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -190,9 +190,12 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) { } if r.Method == http.MethodPost && rest == "/responses" { withGatewaySession(w, r) - var recorded func() + var recorded, hooked func() w, recorded = recordConversation(w, r, provider.Responses, body) defer recorded() + // Codex's own sign-in: the request hooks, not the middleware + w, body, hooked = gatewayHooks(w, r, provider.Responses, body) + defer hooked() } s.codexUpstream(w, r, rest, body) } diff --git a/internal/gateway/gateway_hook_test.go b/internal/gateway/gateway_hook_test.go new file mode 100644 index 000000000..2b6183007 --- /dev/null +++ b/internal/gateway/gateway_hook_test.go @@ -0,0 +1,436 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +func TestAsyncGatewayResponseDoesNotHoldStream(t *testing.T) { + t.Setenv("MAGPIE_BUN", testenv.Bun(t)) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Cleanup(plugin.Settle) + generated := make(chan struct{}) + first := make(chan string, 1) + completed := make(chan map[string]any, 1) + release := make(chan struct{}) + notified := make(chan struct{}, 1) + observer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload map[string]any + json.NewDecoder(r.Body).Decode(&payload) + completed <- payload + select { + case <-release: + case <-r.Context().Done(): + } + w.WriteHeader(http.StatusNoContent) + })) + defer func() { close(release); observer.Close() }() + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{"content":"live answer"}}]}`)) + w.(http.Flusher).Flush() + select { + case <-generated: + case <-r.Context().Done(): + return + } + io.WriteString(w, sse(`data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, "data: [DONE]")) + })) + defer upstream.Close() + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "synthetic", Models: []string{"m1"}, Chat: upstream.URL + "/v1"}); err != nil { + t.Fatal(err) + } + abs := filepath.Join(t.TempDir(), "observer.hooks.js") + script := `export async function onRequest(body,ctx){ctx.state.question=ctx.query;return body} +export async function onResponse(body,ctx){await fetch(ctx.options.url,{method:"POST",body:JSON.stringify({body,success:ctx.success,question:ctx.state.question}),signal:ctx.signal})}` + if err := os.WriteFile(abs, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugin.Add(t.Context(), abs); err != nil { + t.Fatal(err) + } + if err := plugin.SetOptions(abs, map[string]any{"url": observer.URL, "gatewayTimeoutMs": 5000}); err != nil { + t.Fatal(err) + } + gw := httptest.NewServer(lanGuard(New().Handler())) + defer func() { + close(generated) + gw.CloseClientConnections() + gw.Close() + }() + // Client reads the first delta while upstream generation is still blocked. + go func() { + req, _ := http.NewRequestWithContext(t.Context(), "POST", gw.URL+"/v1/chat/completions", strings.NewReader(`{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"question"}]}`)) + req.Header.Set("Authorization", "Bearer magpie") + res, err := gw.Client().Do(req) + if err != nil { + first <- err.Error() + notified <- struct{}{} + return + } + defer res.Body.Close() + buf := make([]byte, 1024) + n, _ := res.Body.Read(buf) + first <- string(buf[:n]) + io.Copy(io.Discard, res.Body) + notified <- struct{}{} + }() + select { + case text := <-first: + if !strings.Contains(text, "live answer") { + t.Fatalf("first delta: %s", text) + } + case <-time.After(10 * time.Second): + t.Fatal("stream waited for completed generation") + } + generated <- struct{}{} + select { + case payload := <-completed: + if payload["success"] != true || payload["question"] != "question" || !strings.Contains(string(raw(payload["body"])), "live answer") { + t.Fatalf("completion: %+v", payload) + } + case <-time.After(10 * time.Second): + t.Fatal("missing completion notification") + } + select { + case <-notified: + case <-time.After(2 * time.Second): + t.Fatal("slow completion hook delayed client EOF") + } +} + +// Exercise the asynchronous host and server guard with all agent wire APIs. +// Service-specific contracts belong to companion plugin integration tests. +func TestAsyncGatewayThroughProtocols(t *testing.T) { + t.Setenv("MAGPIE_BUN", testenv.Bun(t)) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Cleanup(plugin.Settle) + upstream := make(chan []byte, 20) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + upstream <- b + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{"content":"recalled answer"}}]}`, `data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}`, "data: [DONE]")) + })) + defer up.Close() + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "upstream-secret", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + queries := make(chan map[string]any, 20) + contextService := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer context-test" { + t.Error("context service authorization missing") + } + var payload map[string]any + json.NewDecoder(r.Body).Decode(&payload) + queries <- payload + w.Header().Set("Content-Type", "application/json") + var content any = "Recalled Quartz codename: QUARTZ-8413 (" + payload["session"].(string) + ")" + switch payload["query"] { + case "empty": + content = "" + case "invalid": + content = 123 + case "denied": + w.WriteHeader(http.StatusForbidden) + return + } + json.NewEncoder(w).Encode(map[string]any{"context": content}) + })) + defer contextService.Close() + abs := filepath.Join(t.TempDir(), "recall.hooks.js") + if err := os.WriteFile(abs, []byte(` +export async function onRequest(body,ctx) { + const response=await fetch(ctx.options.serverUrl,{method:"POST",headers:{"Authorization":ctx.options.authorization},body:JSON.stringify({session:ctx.session,query:ctx.query,origin:ctx.origin}),signal:ctx.signal}) + if(!response.ok)throw new Error("unavailable") + const result=await response.json() + if(typeof result.context!=="string")throw new Error("invalid") + if(!result.context)return + const text="\n"+result.context+"" + const messages=ctx.protocol==="gemini"?body.contents:ctx.protocol==="responses"?body.input:body.messages + const m=messages.findLast(m=>m.role==="user") + if(typeof m.content==="string")m.content+=text + else if(ctx.protocol==="gemini")m.parts.push({text}) + else m.content.push({type:ctx.protocol==="responses"?"input_text":"text",text}) + return body +}`), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugin.Add(t.Context(), abs); err != nil { + t.Fatal(err) + } + if err := plugin.SetOptions(abs, map[string]any{"serverUrl": contextService.URL, "authorization": "Bearer context-test"}); err != nil { + t.Fatal(err) + } + gw := httptest.NewServer(lanGuard(New().Handler())) + defer gw.Close() + send := func(path, body, session string) []byte { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), "POST", gw.URL+path, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer magpie-codex") + req.Header.Set(SessionHeader, session) + res, err := gw.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + reply, _ := io.ReadAll(res.Body) + if res.StatusCode != 200 || !strings.Contains(string(reply), "recalled answer") { + t.Fatalf("agent reply: %d %s", res.StatusCode, reply) + } + return <-upstream + } + cases := []struct{ name, path, body string }{ + {"chat", "/v1/chat/completions", `{"model":"fake/m1","stream":true,"messages":[{"role":"system","content":"/tmp/quartz"},{"role":"user","content":"Quartz codename?"}]}`}, + {"responses", "/v1/responses", `{"model":"fake/m1","stream":true,"instructions":"/tmp/quartz","input":[{"role":"user","content":[{"type":"input_text","text":"Quartz codename?"}]}]}`}, + {"codex-context", "/v1/responses", `{"model":"fake/m1","stream":true,"input":[{"role":"user","content":[{"type":"input_text","text":"/tmp/quartz"},{"type":"input_text","text":"Quartz codename?"}]}]}`}, + {"anthropic", "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":40,"system":"/tmp/quartz","messages":[{"role":"user","content":[{"type":"text","text":"Quartz codename?"}]}]}`}, + {"gemini", "/v1beta/models/fake/m1:streamGenerateContent", `{"systemInstruction":{"parts":[{"text":"/tmp/quartz"}]},"contents":[{"role":"user","parts":[{"text":"Quartz codename?"}]}]}`}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := string(send(c.path, c.body, "session-a")) + if strings.Count(got, "QUARTZ-8413") != 1 || !strings.Contains(got, "session-a") || !strings.Contains(got, "Quartz codename?") { + t.Fatalf("recall did not reach provider exactly once: %s", got) + } + if strings.Contains(got, "context-test") || strings.Contains(got, "magpie-codex") { + t.Fatalf("plugin credentials leaked upstream: %s", got) + } + query := <-queries + if query["query"] != "Quartz codename?" || query["session"] != "session-a" || query["origin"] != "local" { + t.Fatalf("wrong preparation: %+v", query) + } + }) + } + if t.Failed() { + return + } + got := string(send(cases[0].path, cases[0].body, "session-b")) + <-queries + if !strings.Contains(got, "session-b") || strings.Contains(got, "session-a") { + t.Fatalf("session context leaked: %s", got) + } + for _, query := range []string{"empty", "invalid", "denied"} { + body := `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"` + query + `"}]}` + got := string(send(cases[0].path, body, "session-a")) + <-queries + if strings.Contains(got, "external-context") || !strings.Contains(got, query) { + t.Fatalf("failed/empty recall changed prompt: %s", got) + } + } + if err := plugin.SetOff(abs, true); err != nil { + t.Fatal(err) + } + got = string(send(cases[0].path, cases[0].body, "session-a")) + if strings.Contains(got, "external-context") { + t.Fatalf("disabled plugin injected context: %s", got) + } + select { + case q := <-queries: + t.Fatalf("disabled plugin queried context service: %+v", q) + default: + } +} + +func TestGatewayQueryUsesUserWords(t *testing.T) { + for _, tc := range []struct { + name string + messages []Message + want string + }{ + {"Codex environment", []Message{userMsg(envContext, "Quartz codename?")}, "Quartz codename?"}, + {"agent notices", []Message{userMsg("Quartz codename?"), userMsg(pluginRef, taskNotification)}, "Quartz codename?"}, + {"tool-only increment", []Message{{Role: "user", Parts: []Part{{Kind: ToolResult, Text: "QUARTZ-8413"}}}}, ""}, + {"context only", []Message{userMsg(envContext)}, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := gatewayQuery(&Request{Messages: tc.messages}); got != tc.want { + t.Fatalf("query %q, want %q", got, tc.want) + } + }) + } +} + +// Exercise provenance through authentication and the real Bun lifecycle; a +// client's body/header claims cannot replace the host's classification. +func TestAsyncGatewayOrigin(t *testing.T) { + t.Setenv("MAGPIE_BUN", testenv.Bun(t)) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Cleanup(plugin.Settle) + if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(catalog.CachePath(), []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + key, err := access.Update("add-key", access.Change{Name: "Shared"}) + if err != nil { + t.Fatal(err) + } + abs := filepath.Join(t.TempDir(), "origin.hooks.mjs") + script := `export function onRequest(body,ctx){ctx.state.origin=ctx.origin;body.origin=ctx.origin;return body} +export async function onResponse(reply,ctx){await fetch(ctx.options.url,{method:"POST",body:JSON.stringify({origin:ctx.origin,before:ctx.state.origin}),signal:ctx.signal})}` + observed := make(chan map[string]string, 20) + observer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var got map[string]string + json.NewDecoder(r.Body).Decode(&got) + observed <- got + w.WriteHeader(204) + })) + defer observer.Close() + if err := os.WriteFile(abs, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugin.Add(t.Context(), abs); err != nil { + t.Fatal(err) + } + if err := plugin.SetOptions(abs, map[string]any{"url": observer.URL}); err != nil { + t.Fatal(err) + } + for _, tc := range []struct{ name, peer, header, key, trust, want string }{ + {"local", "127.0.0.1:1234", "", "", "0", "local"}, + {"ipv6", "[::1]:1234", "", "", "0", "local"}, + {"named-loopback", "127.0.0.1:1234", "", key, "0", "gateway-key"}, + {"remote", "10.0.0.1:1234", "", key, "0", "gateway-key"}, + {"proxy", "127.0.0.1:1234", "X-Forwarded-For", key, "0", "gateway-key"}, + {"trusted-proxy", "127.0.0.1:1234", "Forwarded", "", "1", "remote"}, + {"trusted-tunnel", "127.0.0.1:1234", "Tailscale-User-Login", "", "1", "remote"}, + {"unknown-peer", "malformed", "", "", "0", "remote"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("MAGPIE_TRUST_PROXY", tc.trust) + // The guard requires sharing for nonlocal peers, without opening a listener. + t.Setenv("MAGPIE_ADDR", "0.0.0.0:3425") + req := httptest.NewRequest("POST", "http://127.0.0.1/v1/chat/completions", strings.NewReader(`{"model":"fake/m1","origin":"local","messages":[{"role":"user","content":"hello"}]}`)) + req.RemoteAddr = tc.peer + req.Header.Set("X-Magpie-Origin", "local") + if tc.header != "" { + req.Header.Set(tc.header, "remote-client") + } + if tc.key != "" { + req.Header.Set("Authorization", "Bearer "+tc.key) + } + // An invalid peer cannot pass the guard. Check it directly as a defensive + // classifier case; all accepted cases go through the complete lifecycle. + if tc.name == "unknown-peer" { + if got := gatewayOrigin(req); got != tc.want { + t.Fatalf("origin=%q, want %q", got, tc.want) + } + return + } + w := httptest.NewRecorder() + lanGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w, b, done := gatewayHooks(w, r, provider.Chat, []byte(`{"model":"fake/m1","origin":"local","messages":[{"role":"user","content":"hello"}]}`)) + defer done() + var got map[string]any + json.Unmarshal(b, &got) + if got["origin"] != tc.want { + t.Errorf("request origin=%v, want %s", got["origin"], tc.want) + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`) + })).ServeHTTP(w, req) + if w.Code != 200 { + t.Fatalf("guard status=%d: %s", w.Code, w.Body.String()) + } + select { + case got := <-observed: + if got["origin"] != tc.want || got["before"] != tc.want { + t.Fatalf("callback provenance=%v, want %s", got, tc.want) + } + case <-time.After(10 * time.Second): + t.Fatal("missing completion origin") + } + }) + } +} + +// Codex hangs up as soon as it reads response.completed, while ChatGPT may +// hold the connection a moment longer. The reply was delivered whole, so +// onResponse still sees it, as a success: the run ends with the handler, +// not with the client's connection. +func TestGatewayHookSeesReplyAfterClientHangsUp(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + held := make(chan struct{}) + chatgpt(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"type":"response.output_text.delta","delta":"pong"}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"pong"}]}]}}`)) + w.(http.Flusher).Flush() + select { + case <-held: + case <-r.Context().Done(): + } + }) + defer close(held) + t.Setenv("MAGPIE_BUN", testenv.Bun(t)) + t.Cleanup(plugin.Settle) + completed := make(chan map[string]any, 1) + observer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload map[string]any + json.NewDecoder(r.Body).Decode(&payload) + completed <- payload + })) + defer observer.Close() + abs := filepath.Join(t.TempDir(), "capture.hooks.js") + if err := os.WriteFile(abs, []byte(`export async function onRequest(body){return body} +export async function onResponse(reply,ctx){await fetch(ctx.options.url,{method:"POST",body:JSON.stringify({reply,success:ctx.success}),signal:ctx.signal})}`), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugin.Add(t.Context(), abs); err != nil { + t.Fatal(err) + } + if err := plugin.SetOptions(abs, map[string]any{"url": observer.URL, "gatewayTimeoutMs": 5000}); err != nil { + t.Fatal(err) + } + gw := httptest.NewServer(New().Handler()) + defer gw.Close() + ctx, hangUp := context.WithCancel(t.Context()) + defer hangUp() + req, _ := http.NewRequestWithContext(ctx, "POST", gw.URL+CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"ping"}`)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + res, err := gw.Client().Do(req) + if err != nil { + t.Fatal(err) + } + read := "" + buf := make([]byte, 4096) + for !strings.Contains(read, "response.completed") { + n, err := res.Body.Read(buf) + read += string(buf[:n]) + if err != nil { + t.Fatalf("stream ended before response.completed: %v %q", err, read) + } + } + hangUp() // as Codex does + res.Body.Close() + select { + case payload := <-completed: + if payload["success"] != true || !strings.Contains(string(raw(payload["reply"])), "pong") { + t.Fatalf("completion after hang-up: %+v", payload) + } + case <-time.After(10 * time.Second): + t.Fatal("onResponse never ran after the client hung up on a whole reply") + } +} diff --git a/internal/gateway/gateway_hooks.go b/internal/gateway/gateway_hooks.go new file mode 100644 index 000000000..80b95ade7 --- /dev/null +++ b/internal/gateway/gateway_hooks.go @@ -0,0 +1,94 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "errors" + "net/http" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" +) + +// gatewayResponse observes the bytes delivered to the client without changing +// them. The caller runs done after middleware has finished writing its reply. +func gatewayResponse(w http.ResponseWriter, r *http.Request, proto provider.Protocol, body []byte, run *plugin.GatewayRun) (http.ResponseWriter, func()) { + capture := &conversationWriter{captureResponseWriter: &captureResponseWriter{ + ResponseWriter: w, full: &spool{limit: conversationBodyMax, pattern: "magpie-hook-*"}, + }} + return capture, func() { + defer capture.full.discard() + if streamOf(body) { + _ = http.NewResponseController(w).Flush() + } + output, err := capture.full.read() + // a client that hangs up once it has the whole reply (Codex, on + // response.completed) still got it: gatewayReply judges the bytes + if err != nil || capture.full.cut() || capture.status >= 400 { + run.Finish(r.Context(), nil, false, body) + return + } + reply, err := gatewayReply(proto, output) + var response obj + json.Unmarshal(reply, &response) + success := err == nil && (len(response["error"]) == 0 || string(response["error"]) == "null") && str(response, "status") != "failed" && str(response, "status") != "incomplete" + run.Finish(r.Context(), reply, success, body) + } +} + +// gatewayReply is the reply the client got as one whole reply in its API: a +// whole body as it is, and a stream read through the protocol's decoder into +// the reply the gateway would have rendered. A Responses stream's completed +// response is the reply itself. A stream that never ended is an error. +func gatewayReply(proto provider.Protocol, body []byte) (json.RawMessage, error) { + body = bytes.TrimSpace(body) + if json.Valid(body) { + var object obj + if err := json.Unmarshal(body, &object); err != nil || object == nil { + return nil, errors.New("invalid model reply") + } + return bytes.Clone(body), nil + } + var c collector + var completed json.RawMessage + decode := decoder(proto) + ended := false + err := readSSE(bytes.NewReader(body), func(_ string, data string) error { + if data == "[DONE]" { + ended = true + return nil + } + if !json.Valid([]byte(data)) { + return errors.New("invalid model stream") + } + if proto == provider.Responses { + var e struct { + Type string `json:"type"` + Response json.RawMessage `json:"response"` + } + if json.Unmarshal([]byte(data), &e) == nil && e.Type == "response.completed" && len(e.Response) > 0 { + completed = e.Response + } + } + return decode(data, func(e Event) { + if e.Kind == KStop { + ended = true + } + c.add(e) + }) + }) + if err != nil { + return nil, err + } + if !ended { + return nil, errors.New("incomplete model stream") + } + if c.err != "" { + return nil, errors.New(c.err) + } + if completed != nil { + return completed, nil + } + res := c.finish() + return render(proto, res, &Request{Model: res.Model}), nil +} diff --git a/internal/gateway/middleware.go b/internal/gateway/middleware.go index 4865f6e7d..59006e9e3 100644 --- a/internal/gateway/middleware.go +++ b/internal/gateway/middleware.go @@ -2,9 +2,12 @@ package gateway import ( "net/http" + "slices" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/gwmw" "github.com/yetone/magpie/internal/middleware" + "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/provider" ) @@ -19,6 +22,8 @@ func (s *Server) serveAgent(w http.ResponseWriter, r *http.Request, from provide withGatewaySession(w, r) w, recorded := recordConversation(w, r, from, body) defer recorded() + w, body, hooked := gatewayHooks(w, r, from, body) + defer hooked() agents := gwmw.AgentsWanted(middlewareWanted) if len(agents) == 0 { s.serve(w, r, from, body) @@ -47,3 +52,53 @@ func (s *Server) serveAgent(w http.ResponseWriter, r *http.Request, from provide // middlewareWanted: plugins.json has a JS middleware on, so plugins/middleware // is in use. func middlewareWanted() bool { return middleware.On() > 0 } + +// gatewayHooks runs the asynchronous request hooks (OpenCode plugins' +// gateway entries, in the plugin host) on an agent's request: the body they +// leave is the one served, and they see the reply the agent got once it is +// whole. Its writer wraps the middleware's, so what they see is what the +// agent was given. With no hook it is the request as it came. +func gatewayHooks(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) (http.ResponseWriter, []byte, func()) { + if !plugin.HasGateway() { + return w, body, func() {} + } + info := plugin.GatewayContext{Origin: gatewayOrigin(r), Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r), Session: sessionOf(r.Header)} + if req, err := parse(from, body); err == nil { + info.Cwd = workDir(req) + info.Query = gatewayQuery(req) + } + run := plugin.GatewayBegin(r.Context(), body, info) + if run == nil { + return w, body, func() {} + } + w, done := gatewayResponse(w, r, from, run.Body, run) + return w, run.Body, func() { done(); run.Close() } +} + +// gatewayQuery uses the same user-authored words as routing, excluding +// agent context, tool results and images. Tool-only increments have none. +func gatewayQuery(req *Request) string { + for i := len(req.Messages) - 1; i >= 0; i-- { + m := req.Messages[i] + if m.Role != "user" { + continue + } + if query := userSaid(m); query != "" { + return query + } + } + return "" +} + +// gatewayOrigin exposes provenance, never credentials or peer addresses. +// Forwarded traffic remains remote even when the administrator trusts its +// proxy for authentication: that trust does not establish conversation ownership. +func gatewayOrigin(r *http.Request) string { + if access.Caller(r.Context()).KeyID != "" || managedKey(r) { + return "gateway-key" + } + if local(r) && !slices.ContainsFunc(forwardHeaders, func(h string) bool { return r.Header.Get(h) != "" }) { + return "local" + } + return "remote" +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 94659d185..63e588802 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -6,6 +6,21 @@ const I18N = { zh: { "None": "无", "Prompt": "提示词", + "Request hook": "请求 Hook", + "Gateway request hook": "网关请求 Hook", + "Context injected": "已注入上下文", + "No matching context": "没有匹配的上下文", + "Scope not bound": "Scope 未绑定", + "Authorization failed": "认证失败", + "Context service unavailable": "上下文服务不可用", + "Invalid context response": "上下文响应无效", + "Request skipped": "已跳过请求", + "Request cancelled": "请求已取消", + "Recall timed out": "召回超时", + "Request hook failed": "请求 Hook 失败", + "{n} calls, {ms} ms each": "调用 {n} 次,平均每次 {ms} ms", + "{n} bytes injected": "已注入 {n} 字节", + "Diagnostics reset when the plugin host restarts; prompts and recalled text are not stored": "插件宿主重启后诊断重置;不保存提示词和召回文本", "Check again": "重新检测", "Manage": "管理", "Manage agents": "批量管理", @@ -3679,6 +3694,21 @@ const I18N = { "zh-TW": { "None": "無", "Prompt": "提示詞", + "Request hook": "請求 Hook", + "Gateway request hook": "閘道請求 Hook", + "Context injected": "已注入上下文", + "No matching context": "沒有符合的上下文", + "Scope not bound": "Scope 未綁定", + "Authorization failed": "認證失敗", + "Context service unavailable": "上下文服務無法使用", + "Invalid context response": "上下文回應無效", + "Request skipped": "已跳過請求", + "Request cancelled": "請求已取消", + "Recall timed out": "召回逾時", + "Request hook failed": "請求 Hook 失敗", + "{n} calls, {ms} ms each": "呼叫 {n} 次,平均每次 {ms} ms", + "{n} bytes injected": "已注入 {n} 位元組", + "Diagnostics reset when the plugin host restarts; prompts and recalled text are not stored": "外掛宿主重新啟動後診斷重設;不儲存提示詞和召回文字", "Check again": "重新檢測", "Codex thread descriptions": "Codex 對話描述", "Codex composer predictions": "Codex 輸入框預測", @@ -7337,6 +7367,21 @@ const I18N = { ja: { "None": "なし", "Prompt": "プロンプト", + "Request hook": "リクエストフック", + "Gateway request hook": "ゲートウェイリクエストフック", + "Context injected": "コンテキストを追加済み", + "No matching context": "一致するコンテキストなし", + "Scope not bound": "Scope が未設定", + "Authorization failed": "認証に失敗", + "Context service unavailable": "コンテキストサービスに接続できません", + "Invalid context response": "コンテキストの応答が無効", + "Request skipped": "リクエストをスキップ", + "Request cancelled": "リクエストをキャンセル", + "Recall timed out": "コンテキスト取得がタイムアウト", + "Request hook failed": "リクエストフックに失敗", + "{n} calls, {ms} ms each": "{n} 回、平均 {ms} ms", + "{n} bytes injected": "{n} バイトを追加", + "Diagnostics reset when the plugin host restarts; prompts and recalled text are not stored": "プラグインホストの再起動で診断をリセットします。プロンプトと取得したテキストは保存しません", "Check again": "再確認", "Manage": "管理", "Manage agents": "エージェントを一括管理", @@ -10997,6 +11042,21 @@ const I18N = { de: { "None": "Keine", "Prompt": "Prompt", + "Request hook": "Anfrage-Hook", + "Gateway request hook": "Gateway-Anfrage-Hook", + "Context injected": "Kontext eingefügt", + "No matching context": "Kein passender Kontext", + "Scope not bound": "Scope nicht verknüpft", + "Authorization failed": "Authentifizierung fehlgeschlagen", + "Context service unavailable": "Kontextdienst nicht verfügbar", + "Invalid context response": "Ungültige Kontextantwort", + "Request skipped": "Anfrage übersprungen", + "Request cancelled": "Anfrage abgebrochen", + "Recall timed out": "Kontextabruf abgelaufen", + "Request hook failed": "Anfrage-Hook fehlgeschlagen", + "{n} calls, {ms} ms each": "{n} Aufrufe, je {ms} ms", + "{n} bytes injected": "{n} Bytes eingefügt", + "Diagnostics reset when the plugin host restarts; prompts and recalled text are not stored": "Diagnosen werden beim Neustart des Plugin-Hosts zurückgesetzt; Prompts und abgerufener Text werden nicht gespeichert", "Check again": "Erneut prüfen", "Manage": "Verwalten", "Manage agents": "Agents verwalten", diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 087dd5fa4..ed9cbcaa7 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -1052,14 +1052,20 @@ // gateway middleware runs in magpie's gateway, not as a subscription: // the row says so, and how it is doing, on a line of its own const mw = e.middleware; + const gw = e.gateway; const ag = e.agent; if (mw || e.isMiddleware) nm.append(kindChip("mw")); + if (gw || e.isGateway) { + const chip = kindChip("mw"); + chip.querySelector("span").textContent = t("Request hook"); + nm.append(chip); + } if (ag || e.isAgent) nm.append(kindChip("ag")); // a plugin of tools alone signs in to nothing: no Provider chip const toolsOnly = !!e.tools?.length && !e.providers?.length; if (e.tools?.length) nm.append(kindChip("tl")); if (e.page) nm.append(kindChip("pg")); - if (e.providers?.length || !(e.middlewareOnly || e.inMagpieOnly || toolsOnly || (mw && !e.isMiddleware) || (ag && !e.isAgent))) nm.append(kindChip("pv")); + if (e.providers?.length || !(e.gatewayOnly || e.middlewareOnly || e.inMagpieOnly || toolsOnly || (mw && !e.isMiddleware) || (ag && !e.isAgent))) nm.append(kindChip("pv")); who.append(nm); const subs = subsOf(pkg); const sub = el("div", "sub"); @@ -1090,8 +1096,8 @@ else if (!x.signedIn && subs.some((y) => y.signedIn)) s.title = t("{name} is a subscription of its own; {other} works without it", { name: x.name, other: subs.find((y) => y.signedIn).name }); sub.append(s); } - } else if ((mw || ag || toolsOnly || e.page && e.inMagpieOnly) && !e.providers.length) { - // only middleware, an agent, tools or a page: its own line says what it does + } else if ((mw || ag || gw || e.isGateway || toolsOnly || e.page && e.inMagpieOnly) && !e.providers.length) { + // only middleware, a request hook, an agent, tools or a page: its own line says what it does } else if (clashes.length && !e.providers.length) { // its own line below says whose it is } else if (e.providers.length) sub.textContent = t("Signs in to {names}", { names: e.providers.join(t(", ")) }); @@ -1103,11 +1109,12 @@ if (sub.textContent) who.append(sub); if (!ask) for (const c of clashes) who.append(clashLine(e, c, nameOfSpec)); if (mw && !e.off && !ask) who.append(mwLine(mw)); + if (gw && !e.off && !ask) who.append(gatewayLine(gw)); if (ag && !e.off && !ask) who.append(agentLine(ag)); if (e.tools?.length && !e.off && !ask) who.append(toolsLine(e.tools)); // off too: what its page may read is said before it is turned on if (e.page && !ask) who.append(pageLine(e.page)); - if (mw && !e.off && !ask && editing?.pkg === pkg) who.append(optionsEditor(e)); + if ((mw || e.isGateway) && !e.off && !ask && editing?.pkg === pkg) who.append(optionsEditor(e)); // the plugin's own picture (package.json's magpie.icon) before its // first provider's, which a plugin of several gives each its own (#1775) r.append(logo(l?.icon || l?.npm?.icon || e.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.inMagpieOnly && e.isAgent && !e.isMiddleware ? "ag" : e.inMagpieOnly && e.page && !e.isAgent && !e.isMiddleware ? "pg" : toolsOnly && !e.page && !mw && !ag ? "tl" : ""), who); @@ -1158,7 +1165,7 @@ r.append(val); return r; } - if (mw && !e.off && !mw.error && editing?.pkg !== pkg) { + if ((e.isGateway || (mw && !mw.error)) && !e.off && editing?.pkg !== pkg) { const o = el("button", "text", t("Options")); o.title = e.options ? t("The options it runs with") : t("It runs with no options; its package suggests some"); o.disabled = !!b; @@ -1331,6 +1338,23 @@ return d; } + function gatewayLine(g) { + const d = el("div", "sub pm-mw pm-gateway"); + const labels = { + idle: "Waiting for a request", ready: "Context injected", empty: "No matching context", + unbound: "Scope not bound", unauthorized: "Authorization failed", + unavailable: "Context service unavailable", invalid: "Invalid context response", + skipped: "Request skipped", cancelled: "Request cancelled", timeout: "Recall timed out", error: "Request hook failed", + }; + let text = t("Gateway request hook") + ": " + t(labels[g.lastOutcome] || labels.idle); + if (g.calls) text += " · " + t("{n} calls, {ms} ms each", { n: g.calls.toLocaleString(intlLang()), ms: g.avgMillis.toFixed(1) }); + if (g.lastBytes) text += " · " + t("{n} bytes injected", { n: g.lastBytes.toLocaleString(intlLang()) }); + d.append(el("span", "", text)); + if (g.failures) d.append(el("span", "sep", " · "), el("span", "pm-mw-fail", t("{n} failed", { n: g.failures.toLocaleString(intlLang()) }))); + d.title = t("Diagnostics reset when the plugin host restarts; prompts and recalled text are not stored"); + return d; + } + // the plugin's page: what it is, what npm says of it, and its README async function detail(l) { // a folder plugin: what it is comes from the folder, not from npm; a diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index 04a77bd30..22dddfe88 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -121,7 +121,10 @@ type pluginEntryJSON struct { Named bool `json:"named,omitempty"` // OptionsExample is what its package suggests for its options, which // the options editor starts from when none are set - OptionsExample map[string]any `json:"optionsExample,omitempty"` + OptionsExample map[string]any `json:"optionsExample,omitempty"` + Gateway *plugin.GatewayState `json:"gateway,omitempty"` + IsGateway bool `json:"isGateway,omitzero"` + GatewayOnly bool `json:"gatewayOnly,omitzero"` // IsMiddleware is whether its package has gateway middleware, said of // one switched off too, which Middleware leaves out; MiddlewareOnly is // whether that is all it has, no provider to sign in to @@ -240,6 +243,7 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON { // npm's newest, as it said last: asking it again is /api/plugins/npm's known := plugin.InfoCached(npmNames(l.Plugins)) mws := middleware.States() + gws := plugin.GatewayStates(ctx) var agentErrs map[string]string for _, e := range l.Plugins { if f, _ := plugin.Agent(plugin.Target(e.Spec)); f != "" && !e.Off { @@ -249,6 +253,17 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON { } for _, e := range l.Plugins { j := pluginEntryJSON{Entry: e, Error: errs[e.Spec], Providers: names[e.Spec], Version: plugin.Installed(e.Spec), Named: answered} + if plugin.Gateway(plugin.Target(e.Spec)) != "" { + j.IsGateway = true + j.GatewayOnly = plugin.GatewayOnly(plugin.Target(e.Spec)) + if !e.Off { + state := plugin.GatewayState{LastOutcome: "idle"} + if found, ok := gws[e.Spec]; ok { + state = found + } + j.Gateway = &state + } + } if npmPlugin(e.Spec) { j.Latest = known[plugin.Name(e.Spec)].Version } @@ -267,6 +282,8 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON { } if file, only := plugin.Middleware(plugin.Target(e.Spec)); file != "" { j.IsMiddleware, j.MiddlewareOnly = true, only + } + if j.IsMiddleware || j.IsGateway { j.OptionsExample = plugin.OptionsExample(plugin.Target(e.Spec)) } if file, _ := plugin.Agent(plugin.Target(e.Spec)); file != "" { diff --git a/internal/gui/plugins_gateway_test.go b/internal/gui/plugins_gateway_test.go new file mode 100644 index 000000000..e36668f63 --- /dev/null +++ b/internal/gui/plugins_gateway_test.go @@ -0,0 +1,43 @@ +package gui + +import ( + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/plugin" +) + +func TestGatewayPluginOptionsAndKind(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Setenv("MAGPIE_PLUGIN_MARKET", "off") + t.Cleanup(plugin.Settle) + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"name":"gateway-fixture","magpie":{"hooks":"./hooks.js","options":{"serverUrl":"http://127.0.0.1:8000"}}}`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "hooks.js"), []byte(`export function onRequest() {}`), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugin.Add(t.Context(), dir); err != nil { + t.Fatal(err) + } + state := pluginsState(t.Context(), nil) + if len(state.Plugins) != 1 { + t.Fatalf("plugins: %+v", state) + } + p := state.Plugins[0] + if !p.IsGateway || !p.GatewayOnly || p.OptionsExample["serverUrl"] != "http://127.0.0.1:8000" || p.Gateway == nil || p.Gateway.LastOutcome != "idle" { + t.Fatalf("gateway missing from Settings: %+v", p) + } + if err := plugin.SetOff(dir, true); err != nil { + t.Fatal(err) + } + p = pluginsState(t.Context(), nil).Plugins[0] + if !p.IsGateway || p.Gateway != nil { + t.Fatalf("disabled gateway: %+v", p) + } +} diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index e0f2fb7f9..c115d5b28 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -1,5 +1,12 @@ # Dropdown browser regression +`plugin-gateway.test.cjs` checks gateway-only plugin identification, the existing +JSON options editor and aggregate diagnostics in all five languages on Chromium +and WebKit. It uses local API fixtures, saves options through the real page, and +checks that request hooks have no provider badge. `MAGPIE_GATEWAY_ASSETS` selects +an older asset directory for a failing regression comparison; user settings and +live gateways are never accessed. + `settings-proxy-auth.test.cjs` checks optional SOCKS5/SOCKS5h usernames and passwords in Settings, using the real page with isolated API fixtures. It covers saving and reloading, escaped and non-UTF-8 credentials, masked diff --git a/internal/gui/tests/plugin-gateway.test.cjs b/internal/gui/tests/plugin-gateway.test.cjs new file mode 100644 index 000000000..b5c698889 --- /dev/null +++ b/internal/gui/tests/plugin-gateway.test.cjs @@ -0,0 +1,73 @@ +// Gateway-only plugins have options and private-data-free diagnostics. APIs are fixtures. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = process.env.MAGPIE_GATEWAY_ASSETS || path.resolve(__dirname, "../assets"); + +function server(lang, pluginState) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/gateway/trace") return json({ routes: [] }); + if (url.pathname === "/api/plugins/market" || url.pathname === "/api/plugins" || url.pathname === "/api/plugins/listings") return json(url.pathname === "/api/plugins" ? pluginState : url.pathname === "/api/plugins/listings" ? { listings: [] } : { listings: [], state: pluginState }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const SPEC = "/fixtures/context-plugin"; +for (const engine of ["chromium", "webkit"]) { + test(engine + ": gateway configuration and diagnostics", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({channel:"chromium"})); + t.after(() => browser.close()); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + await t.test(lang, async () => { + const page = await browser.newPage({viewport:{width:980,height:820}}); + page.setDefaultTimeout(5000); + const posted = [], errors = []; + const state = {bun:true, bunVersion:"1.4.3", plugins:[{ + spec:SPEC, providers:[], moved:[], isGateway:true, gatewayOnly:true, + optionsExample:{serverUrl:"http://127.0.0.1:8000",gatewayTimeoutMs:5000}, + gateway:{calls:3,failures:1,avgMillis:5.5,lastOutcome:"ready",lastBytes:120}, + }]}; + page.on("pageerror", e=>errors.push(e.message)); + await page.route("**/*",server(lang,state)); + await page.route("**/api/plugins/options", r=>{ + const data=r.request().postDataJSON(); posted.push(data); + state.plugins[0].options=data.options; + return r.fulfill({json:state}); + }); + await page.goto("http://magpie.test/?view=plugins"); + const installed = {en:"Installed",zh:"已安装","zh-TW":"已安裝",ja:"インストール済み",de:"Installiert"}[lang]; + await page.locator(":is(.lib-tabs .opt, .nav-s):visible",{hasText:installed}).click(); + const row=page.locator("#view-plugins .pm-row"); + assert.equal(await row.locator(".pm-chip.kind.pv").count(),0); + const line=row.locator(".pm-gateway"); + await line.waitFor(); + assert.match(await line.innerText(), /120/); + if(lang!=="en") assert.doesNotMatch(await line.innerText(),/Context injected|calls,|bytes injected/); + const options={en:"Options",zh:"选项","zh-TW":"選項",ja:"オプション",de:"Optionen"}[lang]; + await row.getByRole("button",{name:options,exact:true}).click(); + const textarea=row.locator(".pm-opts textarea"); + assert.deepEqual(JSON.parse(await textarea.inputValue()),state.plugins[0].optionsExample); + await textarea.fill('{"serverUrl":"http://127.0.0.1:9000","gatewayTimeoutMs":6000}'); + const save={en:"Save",zh:"保存","zh-TW":"儲存",ja:"保存",de:"Speichern"}[lang]; + await row.locator(".pm-opts").getByRole("button",{name:save,exact:true}).click(); + await textarea.waitFor({state:"detached"}); + assert.deepEqual(posted,[{spec:SPEC,options:{serverUrl:"http://127.0.0.1:9000",gatewayTimeoutMs:6000}}]); + assert.deepEqual(errors,[]); + await page.close(); + }); + } + }); +} diff --git a/internal/plugin/agent.go b/internal/plugin/agent.go index 8092cfae0..5899681e8 100644 --- a/internal/plugin/agent.go +++ b/internal/plugin/agent.go @@ -45,6 +45,9 @@ func Agent(target string) (file string, only bool) { // magpie's own process, its gateway middleware, its agent and its page, // so the host has nothing of it to load. func InMagpieOnly(target string) bool { + if Gateway(target) != "" { + return false + } mw, mwOnly := Middleware(target) ag, agOnly := Agent(target) pg, pgOnly := WindowPage(target) diff --git a/internal/plugin/gateway.go b/internal/plugin/gateway.go new file mode 100644 index 000000000..1a3b76732 --- /dev/null +++ b/internal/plugin/gateway.go @@ -0,0 +1,235 @@ +package plugin + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +// Gateway is the asynchronous request-hook entry a package runs in Bun: +// package.json magpie.hooks, or a *.hooks.{js,mjs,ts,mts} file. Unlike +// middleware (magpie.middleware/magpie.gateway, *.gateway.js), it can await +// I/O and observe the completed exchange; the names never overlap, so one +// file is never loaded as both. +func Gateway(target string) string { + st, err := os.Stat(target) + if err != nil { + return "" + } + if !st.IsDir() { + base := strings.ToLower(filepath.Base(target)) + // Bun runs TypeScript directly, so a hook may be a .ts file. + for _, ext := range []string{".hooks.js", ".hooks.mjs", ".hooks.ts", ".hooks.mts"} { + if strings.HasSuffix(base, ext) { + return target + } + } + return "" + } + var pkg struct { + Magpie struct { + Hooks string `json:"hooks"` + } `json:"magpie"` + } + b, err := os.ReadFile(filepath.Join(target, "package.json")) + if err != nil || json.Unmarshal(b, &pkg) != nil || strings.TrimSpace(pkg.Magpie.Hooks) == "" { + return "" + } + return filepath.Join(target, filepath.FromSlash(strings.TrimSpace(pkg.Magpie.Hooks))) +} + +// GatewayOnly distinguishes request hooks from packages that also serve a +// provider or add an agent. Keep the provider entry rules aligned with Bun. +func GatewayOnly(target string) bool { + if Gateway(target) == "" { + return false + } + st, err := os.Stat(target) + if err != nil { + return false + } + if !st.IsDir() { + return true + } + var pkg struct { + Main string + Exports json.RawMessage + } + b, err := os.ReadFile(filepath.Join(target, "package.json")) + if err != nil || json.Unmarshal(b, &pkg) != nil || pkg.Main != "" || len(pkg.Exports) != 0 { + return false + } + if file, _ := Agent(target); file != "" { + return false + } + for _, name := range []string{"index.ts", "index.tsx", "index.js", "index.mjs", "index.cjs"} { + if _, err := os.Stat(filepath.Join(target, name)); err == nil { + return false + } + } + return true +} + +// GatewayContext contains only the request identity and text, never its +// authorization headers. Empty fields mean the agent supplied no identity. +type GatewayContext struct { + Origin string `json:"origin"` // local, remote, or gateway-key; empty means unknown + Protocol string `json:"protocol"` + Model string `json:"model"` + Stream bool `json:"stream"` + Path string `json:"path"` + Agent string `json:"agent"` + Session string `json:"session"` + Cwd string `json:"cwd"` + Query string `json:"query"` +} + +// GatewayState is aggregate diagnostics for this host's lifetime. Outcomes +// are fixed codes; no request text, credentials or private context is kept. +type GatewayState struct { + Calls uint64 `json:"calls"` + Failures uint64 `json:"failures"` + AvgMillis float64 `json:"avgMillis"` + LastOutcome string `json:"lastOutcome"` + LastBytes uint64 `json:"lastBytes"` +} + +// GatewayStates asks only an existing host, so opening Settings does not +// start a gateway hook merely to display its diagnostics. +func GatewayStates(ctx context.Context) map[string]GatewayState { + if !HasGateway() { + return nil + } + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + if !hostMu.TryLock() { + return nil + } + h := current + hostMu.Unlock() + if h == nil { + return nil + } + var states map[string]GatewayState + if h.call(ctx, "gatewayStates", nil, &states) != nil { + return nil + } + return states +} + +// HasGateway avoids starting Bun for users who have no asynchronous hooks. +func HasGateway() bool { + for _, e := range Load().Plugins { + if !e.Off && Gateway(Target(e.Spec)) != "" { + return true + } + } + return false +} + +// GatewayRun belongs to the host that began it, even if the plugin list changes +// before the response. Close releases its private state and cancels active I/O. +type GatewayRun struct { + Body json.RawMessage + + h *host + id string + token string + mu sync.Mutex + closed bool + finished bool +} + +// GatewayBegin bounds startup and the entire request-hook chain. Failure or an +// absent hook returns nil so the gateway can keep the original request. +func GatewayBegin(ctx context.Context, body []byte, info GatewayContext) *GatewayRun { + if !HasGateway() { + return nil + } + start, cancel := context.WithTimeout(ctx, 11*time.Second) + defer cancel() + checkList() + // Provider discovery may already be starting the shared host. Wait within + // the same hook budget rather than skipping recall on the first request. + wait := time.NewTicker(10 * time.Millisecond) + defer wait.Stop() + for !hostMu.TryLock() { + select { + case <-start.Done(): + return nil + case <-wait.C: + } + } + if start.Err() != nil { + hostMu.Unlock() + return nil + } + h, err := getLocked(start) + hostMu.Unlock() + if err != nil || start.Err() != nil { + return nil + } + var out struct { + ID string `json:"id"` + Token string `json:"token"` + Body json.RawMessage `json:"body"` + } + err = h.call(start, "gatewayRequest", map[string]any{"operation": "begin", "body": json.RawMessage(body), "context": info}, &out) + if err != nil || out.ID == "" || out.Token == "" || len(out.Body) == 0 || out.Body[0] != '{' || !json.Valid(out.Body) { + return nil + } + // the run ends when its owner finishes or closes it, never when the + // client goes: Codex hangs up on response.completed, and the reply it + // got is still the exchange to observe + return &GatewayRun{Body: out.Body, h: h, id: out.ID, token: out.Token} +} + +// Finish schedules a bounded completion notification without waiting for it. +// Client cancellation after delivery does not cancel the notification. The +// host retains bounded request state; shutdown may discard pending callbacks. +func (r *GatewayRun) Finish(ctx context.Context, reply json.RawMessage, success bool, request ...json.RawMessage) { + if r == nil { + return + } + r.mu.Lock() + if r.closed || r.finished { + r.mu.Unlock() + return + } + r.finished, r.closed = true, true + r.mu.Unlock() + if !json.Valid(reply) { + reply = json.RawMessage("null") + success = false + } + params := map[string]any{"operation": "finish", "id": r.id, "token": r.token, "reply": append(json.RawMessage(nil), reply...), "success": success} + if len(request) != 0 && json.Valid(request[0]) { + params["request"] = append(json.RawMessage(nil), request[0]...) + } + go func() { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 11*time.Second) + defer cancel() + _ = r.h.call(ctx, "gatewayRequest", params, nil) + }() +} + +// Close releases an abandoned request and cancels active plugin I/O. +func (r *GatewayRun) Close() { + if r == nil { + return + } + r.mu.Lock() + if r.closed { + r.mu.Unlock() + return + } + r.closed = true + r.mu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _ = r.h.call(ctx, "gatewayRequest", map[string]any{"operation": "close", "id": r.id, "token": r.token}, nil) +} diff --git a/internal/plugin/gateway_test.go b/internal/plugin/gateway_test.go new file mode 100644 index 000000000..97b896194 --- /dev/null +++ b/internal/plugin/gateway_test.go @@ -0,0 +1,506 @@ +package plugin + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +func gatewayFixture(t *testing.T, source string) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"magpie":{"hooks":"./request.js"}}`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "request.js"), []byte(source), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Add(t.Context(), dir); err != nil { + t.Fatal(err) + } + return dir +} + +func TestGatewayHookWaitsForStartingHost(t *testing.T) { + sandbox(t) + gatewayFixture(t, `export function onRequest(body){return {...body,note:"recalled"}}`) + // Provider discovery holds this lock while starting the shared host. + hostMu.Lock() + locked := true + defer func() { + if locked { + hostMu.Unlock() + } + }() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + done := make(chan *GatewayRun, 1) + go func() { done <- GatewayBegin(ctx, []byte(`{"note":"original"}`), GatewayContext{}) }() + select { + case run := <-done: + if run != nil { + run.Close() + } + t.Fatal("first request skipped the starting host") + case <-time.After(50 * time.Millisecond): + } + hostMu.Unlock() + locked = false + select { + case run := <-done: + if run == nil { + t.Fatal("first request did not run its recall hook") + } + defer run.Close() + if !strings.Contains(string(run.Body), `"recalled"`) { + t.Fatalf("first request was not recalled: %s", run.Body) + } + case <-ctx.Done(): + t.Fatal("first request did not resume after host startup") + } +} + +func TestGatewayHookHostWaitCancellation(t *testing.T) { + sandbox(t) + gatewayFixture(t, `export function onRequest(body){return {...body,note:"recalled"}}`) + hostMu.Lock() + defer hostMu.Unlock() + ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) + defer cancel() + body := []byte(`{"note":"original"}`) + if got := gatewayRequest(ctx, body, GatewayContext{}); string(got) != string(body) { + t.Fatalf("cancelled startup changed the original request: %s", got) + } + if ctx.Err() == nil { + t.Fatal("request skipped host startup instead of waiting for its deadline") + } +} + +func TestGatewayRunStateOwnershipAndAsyncResponse(t *testing.T) { + sandbox(t) + started, release := make(chan struct{}, 2), make(chan struct{}, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + started <- struct{}{} + select { + case <-release: + case <-r.Context().Done(): + } + })) + defer func() { close(release); server.Close() }() + output := filepath.Join(t.TempDir(), "responses.jsonl") + fixture := gatewayFixture(t, `import fs from "node:fs"; +export function onRequest(body,ctx) { + ctx.state.original=body;ctx.state.value=()=>ctx.session; + return {...body,note:"recalled"}; +} +export async function onResponse(reply,ctx) { + await fetch(ctx.options.url,{signal:ctx.signal}); + fs.appendFileSync(ctx.options.output,JSON.stringify({reply,request:ctx.request,success:ctx.success,session:ctx.state.value(),original:ctx.state.original})+"\n"); +}`) + if err := SetOptions(fixture, map[string]any{"output": output, "url": server.URL, "gatewayTimeoutMs": 5000}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + first := GatewayBegin(ctx, []byte(`{"note":"original"}`), GatewayContext{Session: "first"}) + second := GatewayBegin(t.Context(), []byte(`{"note":"original"}`), GatewayContext{Session: "second"}) + if first == nil || second == nil || !strings.Contains(string(first.Body), `"recalled"`) { + t.Fatal("request lifecycle did not begin") + } + t.Cleanup(first.Close) + t.Cleanup(second.Close) + first.Finish(ctx, json.RawMessage(`{"answer":"first"}`), true, first.Body) + cancel() // Completed notifications outlive the HTTP request context. + first.Finish(t.Context(), json.RawMessage(`{"duplicate":true}`), true) + second.Finish(t.Context(), json.RawMessage(`{"answer":"second"}`), true, second.Body) + for range 2 { + select { + case <-started: + case <-time.After(10 * time.Second): + t.Fatal("Finish blocked or notification was cancelled with client request") + } + } + release <- struct{}{} + release <- struct{}{} + deadline := time.Now().Add(10 * time.Second) + for { + b, _ := os.ReadFile(output) + if strings.Count(string(b), "\n") == 2 { + if strings.Contains(string(b), "duplicate") || !strings.Contains(string(b), `"session":"first"`) || !strings.Contains(string(b), `"session":"second"`) || !strings.Contains(string(b), `"note":"original"`) || !strings.Contains(string(b), `"success":true`) { + t.Fatalf("completion state crossed requests: %s", b) + } + break + } + if time.Now().After(deadline) { + t.Fatalf("notifications did not finish: %s", b) + } + time.Sleep(10 * time.Millisecond) + } +} + +func TestGatewayHookCannotRegisterTools(t *testing.T) { + for _, source := range []string{ + `export function onRequest(body,ctx){ctx.addTools([]);return {...body,note:"corrupt"}}`, + `export function onRequest(body){return {...body,tools:[{type:"function",function:{name:"recall"}}]}}`, + } { + t.Run(source, func(t *testing.T) { + sandbox(t) + gatewayFixture(t, source) + body := []byte(`{"note":"original","tools":[]}`) + if out := gatewayRequest(t.Context(), body, GatewayContext{}); !strings.Contains(string(out), `"original"`) || strings.Contains(string(out), "recall") { + t.Fatalf("context hook changed client tools: %s", out) + } + }) + } +} + +// The gateway checked the caller's key against the model and answers in +// the streaming the client asked for: a hook that changes either is rolled +// back, while one that adds context alone is kept. +func TestGatewayHookCannotChangeModelOrStream(t *testing.T) { + body := []byte(`{"model":"original","stream":true,"messages":[]}`) + for _, tc := range []struct{ source, want string }{ + {`export function onRequest(body){return {...body,model:"other"}}`, `{"model":"original","stream":true,"messages":[]}`}, + {`export function onRequest(body){return {...body,stream:false}}`, `{"model":"original","stream":true,"messages":[]}`}, + {`export function onRequest(body){const {stream, ...rest} = body; return rest}`, `{"model":"original","stream":true,"messages":[]}`}, + {`export function onRequest(body){return {...body,messages:[{role:"system",content:"recalled"}]}}`, `{"model":"original","stream":true,"messages":[{"role":"system","content":"recalled"}]}`}, + } { + t.Run(tc.source, func(t *testing.T) { + sandbox(t) + gatewayFixture(t, tc.source) + var got, want any + json.Unmarshal(gatewayRequest(t.Context(), body, GatewayContext{}), &got) + json.Unmarshal([]byte(tc.want), &want) + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %v, want %s", got, tc.want) + } + }) + } +} + +func TestGatewayRunCapacityAndRelease(t *testing.T) { + sandbox(t) + gatewayFixture(t, `export function onRequest(body){return body}`) + runs := make([]*GatewayRun, 0, 128) + t.Cleanup(func() { + for _, run := range runs { + run.Close() + } + }) + for range 128 { + run := GatewayBegin(t.Context(), []byte(`{}`), GatewayContext{}) + if run == nil { + t.Fatalf("run capacity exhausted at %d", len(runs)) + } + runs = append(runs, run) + } + if run := GatewayBegin(t.Context(), []byte(`{}`), GatewayContext{}); run != nil { + run.Close() + t.Fatal("host retained more than its bounded request capacity") + } + runs[0].Close() + run := GatewayBegin(t.Context(), []byte(`{}`), GatewayContext{}) + if run == nil { + t.Fatal("closed run did not release capacity") + } + defer run.Close() +} + +func TestGatewayHookChainRollbackAndOptions(t *testing.T) { + sandbox(t) + first := gatewayFixture(t, `export async function onRequest(body, ctx) { await Promise.resolve(); body.note = ctx.options.note; return body }`) + if err := SetOptions(first, map[string]any{"note": "first"}); err != nil { + t.Fatal(err) + } + gatewayFixture(t, `export async function onRequest(body) { body.note = "corrupt"; throw new Error("private token must not be logged") }`) + gatewayFixture(t, `export async function onRequest(body) { body.note += "-last"; return body }`) + loaded, err := Plugins(t.Context()) + if err != nil || len(loaded) != 3 { + t.Fatalf("loaded: %+v %v", loaded, err) + } + for _, p := range loaded { + if p.Error != "" { + t.Fatalf("load: %+v", p) + } + } + out := gatewayRequest(t.Context(), []byte(`{"note":"original","messages":[]}`), GatewayContext{Protocol: "chat"}) + var got struct{ Note string } + if err := json.Unmarshal(out, &got); err != nil || got.Note != "first-last" { + t.Fatalf("chain did not preserve successful hooks and undo failed mutation: %s (%v)", out, err) + } + if err := SetOff(first, true); err != nil { + t.Fatal(err) + } + out = gatewayRequest(t.Context(), []byte(`{"note":"original"}`), GatewayContext{}) + if !strings.Contains(string(out), "original-last") { + t.Fatalf("disabled hook ran: %s", out) + } +} + +func TestGatewayHookMixedProviderPackage(t *testing.T) { + sandbox(t) + dir := gatewayFixture(t, `export function onRequest(body) { body.note="recalled";return body }`) + if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"type":"module","main":"./provider.js","magpie":{"hooks":"./request.js"}}`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "provider.js"), []byte(`export default async function(){return {auth:{provider:"fixture",methods:[]},config(config){config.provider.fixture={name:"Gateway fixture",models:{m1:{name:"m1"}}}}}}`), 0o644); err != nil { + t.Fatal(err) + } + providers, err := Providers(t.Context()) + if err != nil || len(providers) != 1 || providers[0].ID != "fixture" { + t.Fatalf("mixed package lost its provider: %+v %v", providers, err) + } + out := gatewayRequest(t.Context(), []byte(`{"note":"original"}`), GatewayContext{}) + if !strings.Contains(string(out), "recalled") { + t.Fatalf("mixed package lost its gateway hook: %s", out) + } +} + +func TestGatewayHookMixedPiPackage(t *testing.T) { + sandbox(t) + ctx, cancel := context.WithTimeout(t.Context(), 4*time.Minute) + defer cancel() + installPinnedPi(t, ctx) + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "extensions"), 0o755); err != nil { + t.Fatal(err) + } + for _, file := range []string{"package.json", "extensions/fakepi.ts"} { + b, err := os.ReadFile(filepath.Join("testdata", "pi", file)) + if err != nil { + t.Fatal(err) + } + if file == "package.json" { + var pkg map[string]any + if err := json.Unmarshal(b, &pkg); err != nil { + t.Fatal(err) + } + pkg["magpie"] = map[string]string{"hooks": "./request.js"} + b = mustJSON(t, pkg) + } + if err := os.WriteFile(filepath.Join(dir, filepath.FromSlash(file)), b, 0o644); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(dir, "request.js"), []byte(`export function onRequest(body){body.note="recalled";return body}`), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Add(ctx, dir); err != nil { + t.Fatal(err) + } + providers, err := Providers(ctx) + if err != nil || len(providers) != 2 { + t.Fatalf("mixed package lost Pi providers: %+v %v", providers, err) + } + out := gatewayRequest(t.Context(), []byte(`{"note":"original"}`), GatewayContext{}) + if !strings.Contains(string(out), "recalled") { + t.Fatalf("mixed Pi package lost gateway hook: %s", out) + } +} + +func TestGatewayHookTimeoutCancelsHTTPAndKeepsBody(t *testing.T) { + sandbox(t) + started, stopped := make(chan struct{}), make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(started) + <-r.Context().Done() + close(stopped) + })) + defer srv.Close() + source := `export async function onRequest(body, ctx) { body.note="corrupt"; await fetch(` + string(mustJSON(t, srv.URL)) + `,{signal:ctx.signal}); return body }` + gatewayFixture(t, source) + if _, err := Plugins(t.Context()); err != nil { + t.Fatal(err) + } + original := []byte(`{"note":"original"}`) + out := gatewayRequest(t.Context(), original, GatewayContext{}) + if string(out) != string(original) { + t.Fatalf("timeout changed request: %s", out) + } + select { + case <-started: + default: + t.Fatal("hook never reached HTTP") + } + select { + case <-stopped: + case <-time.After(10 * time.Second): + t.Fatal("timed-out hook did not cancel HTTP") + } +} + +func TestGatewayHookCallerCancellation(t *testing.T) { + sandbox(t) + started, stopped := make(chan struct{}), make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(started) + <-r.Context().Done() + close(stopped) + })) + defer srv.Close() + gatewayFixture(t, `export async function onRequest(body,ctx) { await fetch(`+string(mustJSON(t, srv.URL))+`,{signal:ctx.signal}); return body }`) + if _, err := Plugins(t.Context()); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan []byte, 1) + go func() { done <- gatewayRequest(ctx, []byte(`{"note":"original"}`), GatewayContext{}) }() + select { + case <-started: + case <-time.After(10 * time.Second): + t.Fatal("hook never started") + } + cancel() + select { + case out := <-done: + if string(out) != `{"note":"original"}` { + t.Fatalf("cancel changed body: %s", out) + } + case <-time.After(10 * time.Second): + t.Fatal("caller cancellation did not return") + } + select { + case <-stopped: + case <-time.After(10 * time.Second): + t.Fatal("caller cancellation did not stop host HTTP") + } + // The canceled RPC releases its capacity; another RPC can still finish. + var out any + if err := Call(t.Context(), "providers", map[string]any{}, &out); err != nil { + t.Fatal(err) + } +} + +func mustJSON(t *testing.T, v any) []byte { + t.Helper() + b, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + return b +} + +func TestGatewayDiagnosticsAndExtendedBudget(t *testing.T) { + sandbox(t) + spec := gatewayFixture(t, `export async function onRequest(body,ctx) { + await new Promise(resolve=>setTimeout(resolve,1100)); + ctx.report("private secret query", 99); + ctx.report("ready", 12); + body.note="recalled"; return body + }`) + if err := SetOptions(spec, map[string]any{"gatewayTimeoutMs": 2000}); err != nil { + t.Fatal(err) + } + out := gatewayRequest(t.Context(), []byte(`{"note":"original"}`), GatewayContext{Query: "private secret query"}) + if !strings.Contains(string(out), "recalled") { + t.Fatalf("configured recall budget ignored: %s", out) + } + state := GatewayStates(t.Context())[spec] + if state.Calls != 1 || state.Failures != 0 || state.LastOutcome != "ready" || state.LastBytes != 12 || state.AvgMillis < 1000 { + t.Fatalf("diagnostics: %+v", state) + } + if strings.Contains(string(mustJSON(t, state)), "private") { + t.Fatal("diagnostics retained private data") + } +} + +// A malformed result and an undefined result both keep original bytes. +func TestGatewayHookInvalidOrUndefinedResult(t *testing.T) { + for _, result := range []string{"null", "[]", "undefined", "{toJSON(){return null}}"} { + t.Run(result, func(t *testing.T) { + sandbox(t) + gatewayFixture(t, `export function onRequest(body){body.note="corrupt";return `+result+`}`) + out := gatewayRequest(t.Context(), []byte(`{"note":"original"}`), GatewayContext{}) + if !strings.Contains(string(out), `"original"`) { + t.Fatalf("invalid return changed request: %s", out) + } + }) + } +} + +// Bun loads TypeScript itself: a direct *.hooks.ts file and a package +// whose magpie.hooks names a .ts entry both run without a build step. +func TestGatewayHookTypeScript(t *testing.T) { + sandbox(t) + direct := filepath.Join(t.TempDir(), "recall.hooks.ts") + if err := os.WriteFile(direct, []byte(`type Body = { note: string } +export async function onRequest(body: Body): Promise { body.note += "-direct"; return body }`), 0o644); err != nil { + t.Fatal(err) + } + if Gateway(direct) == "" { + t.Fatal("direct .hooks.ts file not recognised") + } + if _, err := Add(t.Context(), direct); err != nil { + t.Fatal(err) + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"magpie":{"hooks":"./src/request.ts"}}`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(dir, "src"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "src", "request.ts"), []byte(`interface Body { note: string } +export function onRequest(body: Body): Body { body.note += "-package"; return body }`), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Add(t.Context(), dir); err != nil { + t.Fatal(err) + } + out := gatewayRequest(t.Context(), []byte(`{"note":"m"}`), GatewayContext{Protocol: "chat"}) + if !strings.Contains(string(out), `"m-direct-package"`) { + t.Fatalf("TypeScript hooks did not run in order: %s", out) + } +} + +// gatewayRequest is a hook run on body alone: the body it leaves. +func gatewayRequest(ctx context.Context, body []byte, info GatewayContext) []byte { + run := GatewayBegin(ctx, body, info) + if run == nil { + return body + } + defer run.Close() + return run.Body +} + +// A JS gateway middleware (*.gateway.js, magpie.gateway) and a request hook +// (*.hooks.js, magpie.hooks) never claim the same entry: a hook importing +// node:fs loaded as middleware too would show "didn't load" for a plugin +// that works. +func TestGatewayHookNamesApartFromMiddleware(t *testing.T) { + files := map[string]bool{"a.hooks.js": true, "a.hooks.mjs": true, "a.hooks.ts": true, "a.hooks.mts": true, "a.gateway.js": false, "a.gateway.mjs": false, "a.middleware.js": false} + for name, hook := range files { + p := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(p, []byte(`export async function onRequest(b) { return b }`), 0o644); err != nil { + t.Fatal(err) + } + if got := Gateway(p) != ""; got != hook { + t.Errorf("%s: hook %v, want %v", name, got, hook) + } + if f, _ := Middleware(p); hook && f != "" { + t.Errorf("%s is loaded as middleware too", name) + } + } + for key, hook := range map[string]bool{"hooks": true, "gateway": false, "middleware": false} { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"magpie":{"`+key+`":"./entry.js"}}`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "entry.js"), []byte(`export async function onRequest(b) { return b }`), 0o644); err != nil { + t.Fatal(err) + } + if got := Gateway(dir) != ""; got != hook { + t.Errorf("magpie.%s: hook %v, want %v", key, got, hook) + } + if f, _ := Middleware(dir); hook && f != "" { + t.Errorf("magpie.%s is loaded as middleware too", key) + } + } +} diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 09ccda7c1..b1843548f 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -90,13 +90,14 @@ type call struct { // A fetch's head and chunks wait here, in the order they came, until // the body's reader takes them: the host's reader queues them without // ever waiting on one request's consumer (see push). - stream bool - mu sync.Mutex - queue []message - queued int // the queued chunks' decoded bytes - over error // why the call was given up on - stopped bool // the call is over for good: nothing more is queued - wake chan struct{} // buffered 1: something was queued, or the call is over + stream bool + cancellable bool // a gateway request owns asynchronous I/O, without a stream slot + mu sync.Mutex + queue []message + queued int // the queued chunks' decoded bytes + over error // why the call was given up on + stopped bool // the call is over for good: nothing more is queued + wake chan struct{} // buffered 1: something was queued, or the call is over // window is this call's credit in charged bytes (a frame's payload plus // frameOverhead) and owed is how much of it the child has spent and the @@ -343,7 +344,7 @@ func (c *call) transitionLocked(event callEvent, why error, answer *message) fun }{c.over.Error()}} c.terminal = &m } - if event == callCancelled && c.state == callActive && c.stream { + if event == callCancelled && c.state == callActive && (c.stream || c.cancellable) { c.state = callAborting } else { c.state = callReleased @@ -807,6 +808,12 @@ func get(ctx context.Context) (*host, error) { checkList() hostMu.Lock() defer hostMu.Unlock() + return getLocked(ctx) +} + +// getLocked requires hostMu. Gateway hooks bound both the lock wait and +// startup with their request-hook budget. +func getLocked(ctx context.Context) (*host, error) { if hostStale.Swap(false) && current != nil { go current.retire() current = nil @@ -962,13 +969,14 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { Spec string `json:"spec"` Target string `json:"target"` Options map[string]any `json:"options,omitempty"` + Gateway string `json:"gateway,omitempty"` } var items []item for _, e := range l.Plugins { // a plugin that is only gateway middleware or an agent runs in // magpie (internal/middleware, internal/agentplug), not here if !e.Off && !InMagpieOnly(Target(e.Spec)) { - items = append(items, item{e.Spec, Target(e.Spec), e.Options}) + items = append(items, item{e.Spec, Target(e.Spec), e.Options, Gateway(Target(e.Spec))}) } } var res struct { @@ -1396,6 +1404,9 @@ func (h *host) call(ctx context.Context, method string, params, out any) error { if err != nil { return err } + c.mu.Lock() + c.cancellable = method == "gatewayRequest" + c.mu.Unlock() if err := h.enqueueCall(ctx, map[string]any{"id": id, "method": method, "params": params}, nil, c); err != nil { c.settle(err) return err diff --git a/internal/plugin/host.js b/internal/plugin/host.js index c6324892e..353fc2e39 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -26,6 +26,7 @@ // plugin's getAuth, client.auth.set and loader see that account alone. import { AsyncLocalStorage } from "node:async_hooks" +import { randomUUID } from "node:crypto" import dns from "node:dns" import fs from "node:fs" import http2 from "node:http2" @@ -281,6 +282,7 @@ let prefer = {} // provider id → key → true/false (settings.json's pluginOptions, #2038) let chosen = {} const hooks = [] // {spec, hooks} +const gatewayHooks = [] // {spec, options, onRequest} const loaded = [] // {spec, id, error} const loaders = new Map() // account → options the auth loader returned const sessions = new Map() // oauth sign-in in progress → its authorize result @@ -1162,18 +1164,33 @@ async function loadPlugins(list) { } } for (const p of list) { - if (pis.includes(p)) continue + const isPi = pis.includes(p) + if (isPi && !p.gateway) continue try { + let gateway + if (p.gateway) { + gateway = await import(pathToFileURL(p.gateway).href) + if (typeof gateway.onRequest !== "function") throw new Error("magpie.hooks exports no onRequest") + } let fns = [] - for (const file of entries(p.target)) { + // A gateway-only package needs no OpenCode entry. Mixed packages + // still load their provider hooks through the usual entry rules. + const pkg = readJSON(path.join(p.target, "package.json")) + const onlyGateway = isPi || (p.gateway && (p.gateway === p.target || (!pkg?.main && !pkg?.exports && !INDEX_FILES.some((f) => fs.existsSync(path.join(p.target, f)))))) + for (const file of onlyGateway ? [] : entries(p.target)) { fns = servers(await import(pathToFileURL(file).href)) if (fns.length) break } - if (fns.length === 0) throw new Error("exports no OpenCode plugin function") + if (fns.length === 0 && !gateway) throw new Error("exports no OpenCode plugin function") for (const fn of fns) hooks.push({ spec: p.spec, target: p.target, hooks: (await fn(input, p.options)) ?? {} }) - loaded.push({ spec: p.spec }) + if (gateway) gatewayHooks.push({ spec: p.spec, options: p.options ?? {}, onRequest: gateway.onRequest, + onResponse: gateway.onResponse, + state: { calls: 0, failures: 0, totalMillis: 0, lastOutcome: "idle", lastBytes: 0 } }) + if (!isPi) loaded.push({ spec: p.spec }) } catch (e) { - loaded.push({ spec: p.spec, error: e?.plain ? e.message : String(e?.stack ?? e) }) + const error = e?.plain ? e.message : String(e?.stack ?? e) + if (isPi) loaded.find((r) => r.spec === p.spec).error = error + else loaded.push({ spec: p.spec, error }) } } config = { provider: {}, ...structuredClone(userConfig) } @@ -1187,6 +1204,139 @@ async function loadPlugins(list) { } } +// A bounded await detaches its listener even when the plugin ignores the +// signal. The rejected promise is observed, so late failures cannot escape. +function bounded(promise, signal) { + return new Promise((resolve, reject) => { + const finish = (fn, value) => { signal.removeEventListener("abort", abort); fn(value) } + const abort = () => finish(reject, new DOMException("Aborted", "AbortError")) + // Observe the task even if cancellation won before the await began. + Promise.resolve(promise).then((value) => finish(resolve, value), (error) => finish(reject, error)) + if (signal.aborted) abort() + else signal.addEventListener("abort", abort, { once: true }) + }) +} + +// A run owns the private state of its participating plugins. Its token prevents +// a stale or malformed RPC from selecting another request's tool handlers. +const gatewayRuns = new Map() +const GATEWAY_RUN_LIMIT = 128 +const GATEWAY_RUN_TTL = 15 * 60 * 1000 +const gatewayTimeout = (h) => Number.isInteger(h.options.gatewayTimeoutMs) && h.options.gatewayTimeoutMs >= 100 && h.options.gatewayTimeoutMs <= 10000 ? h.options.gatewayTimeoutMs : 1000 +const gatewayBudget = () => Math.min(10000, Math.max(2000, gatewayHooks.reduce((n, h) => n + gatewayTimeout(h), 0))) + +function closeGateway(run) { + if (!run || run.closed) return + run.closed = true + gatewayRuns.delete(run.id) + clearTimeout(run.timer) + run.controller.abort() + run.plugins.length = 0 +} + +async function gatewayBegin(p, signal) { + if (gatewayRuns.size >= GATEWAY_RUN_LIMIT) return null + const run = { id: randomUUID(), token: randomUUID(), plugins: [], controller: new AbortController(), closed: false, finished: false } + gatewayRuns.set(run.id, run) + run.timer = setTimeout(() => closeGateway(run), GATEWAY_RUN_TTL) + run.timer.unref() + let body = p.body + // The total budget bounds many installed hooks as well as one slow hook. + const total = AbortSignal.any([signal, run.controller.signal, AbortSignal.timeout(gatewayBudget())]) + for (const h of gatewayHooks) { + if (total.aborted) break + const ctl = new AbortController() + const timer = setTimeout(() => ctl.abort(), gatewayTimeout(h)) + const ownSignal = AbortSignal.any([total, ctl.signal]) + const started = performance.now() + let outcome = "skipped", bytes = 0 + try { + // Diagnostics accept fixed codes and byte counts only. Never retain + // exception messages, queries, scope IDs, credentials or recalled text. + const report = (code, count = 0) => { + if (ownSignal.aborted || !["ready", "empty", "unbound", "unauthorized", "unavailable", "invalid", "skipped"].includes(code)) return + outcome = code + bytes = Number.isSafeInteger(count) && count >= 0 && count <= 32768 ? count : 0 + } + const ctx = { ...p.context, options: structuredClone(h.options), state: {}, signal: ownSignal, report } + const result = await bounded(Promise.resolve().then(() => h.onRequest(structuredClone(body), ctx)), ownSignal) + let next = body + if (result !== undefined) { + if (!result || typeof result !== "object" || Array.isArray(result)) throw new Error("invalid body") + // Validate serialization before accepting a plugin's result. + next = JSON.parse(JSON.stringify(result)) + if (!next || typeof next !== "object" || Array.isArray(next)) throw new Error("invalid serialized body") + if (outcome === "skipped") outcome = "ready" + } + // Context hooks cannot register or change client tools or tool choice, + // nor the model or streaming: the gateway checked the caller's key + // against the model, and the client reads the reply it asked for. + for (const key of ["tools", "tool_choice", "function_call", "functions", "toolConfig", "model", "stream"]) { + if (JSON.stringify(next[key]) !== JSON.stringify(body[key])) throw new Error("context hook changed client tools, model or streaming") + } + if (JSON.stringify(next.config?.tools) !== JSON.stringify(body.config?.tools) || JSON.stringify(next.config?.toolConfig) !== JSON.stringify(body.config?.toolConfig)) throw new Error("context hook changed client tools") + body = next + run.plugins.push({ h, ctx }) + } catch { + if (ownSignal.aborted) outcome = signal.aborted ? "cancelled" : "timeout" + else if (!["unbound", "unauthorized", "unavailable", "invalid"].includes(outcome)) outcome = "error" + // Exception text may contain tokens or recalled private material. + if (!signal.aborted) send({ event: "log", level: "warn", message: `${h.spec}: gateway request hook failed or timed out; keeping request` }) + } finally { + h.state.calls++ + if (["timeout", "error", "unauthorized", "unavailable", "invalid"].includes(outcome)) h.state.failures++ + h.state.totalMillis += performance.now() - started + h.state.lastOutcome = outcome + h.state.lastBytes = outcome === "ready" ? bytes : 0 + clearTimeout(timer) + ctl.abort() + } + } + if (signal.aborted || run.closed) { + closeGateway(run) + signal.throwIfAborted() + return null + } + return { id: run.id, token: run.token, body } +} + +async function gatewayFinish(run, p, signal) { + if (run.finished) return null + run.finished = true + const total = AbortSignal.any([signal, run.controller.signal, AbortSignal.timeout(gatewayBudget())]) + try { + for (const { h, ctx } of run.plugins) { + if (total.aborted) break + if (typeof h.onResponse !== "function") continue + const ctl = new AbortController() + const timer = setTimeout(() => ctl.abort(), gatewayTimeout(h)) + ctx.signal = AbortSignal.any([total, ctl.signal]) + ctx.success = p.success === true + if (p.request !== undefined) ctx.request = structuredClone(p.request) + try { + await bounded(Promise.resolve().then(() => h.onResponse(structuredClone(p.reply), ctx)), ctx.signal) + } catch { + if (!signal.aborted) send({ event: "log", level: "warn", message: `${h.spec}: gateway response hook failed or timed out` }) + } finally { + clearTimeout(timer) + ctl.abort() + } + } + } finally { + closeGateway(run) + } + return null +} + +async function gatewayRequest(p, signal) { + if (p.operation === "begin") return gatewayBegin(p, signal) + const run = gatewayRuns.get(p.id) + if (!run || run.closed || run.token !== p.token) return null + if (p.operation === "close") { closeGateway(run); return null } + if (p.operation === "finish") return gatewayFinish(run, p, signal) + return null +} + // auths are the auth hooks by provider, the last plugin to name one // winning, as in OpenCode, unless the user picked one of them for it // (prefer): a plugin of their own beside a third party's that signs in to @@ -2237,6 +2387,13 @@ async function fetchAs(id, record, key, params) { // ---- the loop ---------------------------------------------------------------- const handlers = { + gatewayStates() { + return Object.fromEntries(gatewayHooks.map(({ spec, state }) => [spec, { + calls: state.calls, failures: state.failures, + avgMillis: state.calls ? state.totalMillis / state.calls : 0, + lastOutcome: state.lastOutcome, lastBytes: state.lastBytes, + }])) + }, async init(p) { authPath = p.authPath modelsDevPath = p.modelsDevPath ?? "" @@ -2369,6 +2526,7 @@ const done = () => { if (--pending === 0 && closed) process.exit(0) } +const gatewayInflight = new Map() // RPC id -> AbortController const rl = readline.createInterface({ input: process.stdin, terminal: false }) rl.on("line", (line) => { if (!line.trim()) return @@ -2382,6 +2540,7 @@ rl.on("line", (line) => { const id = msg.params?.id const record = inflight.get(id) if (record) transitionFetch(record, "cancelled") + gatewayInflight.get(id)?.abort() return } if (msg.method === "credit") { @@ -2398,6 +2557,22 @@ rl.on("line", (line) => { ).finally(done) return } + if (msg.method === "gatewayRequest") { + const ctl = new AbortController() + gatewayInflight.set(msg.id, ctl) + // Own cancellation before waiting for init, just as provider fetches do. + bounded(ready ?? Promise.reject(new Error("the host has not been initialised")), ctl.signal) + .then(() => gatewayRequest(msg.params ?? {}, ctl.signal)) + .then( + (result) => { + if (!ctl.signal.aborted) return send({ id: msg.id, result }) + if (msg.params?.operation === "begin" && result?.id) closeGateway(gatewayRuns.get(result.id)) + }, + () => { if (!ctl.signal.aborted) return send({ id: msg.id, result: null }) }, + ) + .finally(() => { gatewayInflight.delete(msg.id); done() }) + return + } if (msg.method === "fetch") { const id = msg.id // the fetch is owned the moment its message is read, before the async diff --git a/internal/plugin/store.go b/internal/plugin/store.go index 66c32b208..6f551be2c 100644 --- a/internal/plugin/store.go +++ b/internal/plugin/store.go @@ -463,6 +463,9 @@ func notPlugin(target string) error { if err != nil || !st.IsDir() || IsPi(target) { return nil } + if Gateway(target) != "" { + return nil + } if f, _ := Middleware(target); f != "" { return nil } diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.html index 6d07e2cd6..8a2db737a 100644 --- a/site/public/docs/ja/plugins.html +++ b/site/public/docs/ja/plugins.html @@ -83,6 +83,7 @@ プロバイダ id テスト 公開と掲載 + 非同期ゲートウェイリクエストフック ゲートウェイミドルウェア すべてのエージェントのツール エージェントプラグイン @@ -609,6 +610,13 @@ m plugin logout acme +

非同期ゲートウェイリクエストフック

+

プラグインはエージェントのリクエストをルーティングする前に I/O を待てます。package.json に "magpie": { "hooks": "./hooks.js" } を宣言するか、*.hooks.js / .mjs / .ts / .mts を追加し(Bun は TypeScript をビルドなしで実行します)、名前付きの非同期 onRequest(body, ctx) をエクスポートします。専用パッケージに OpenCode main/exports は不要です。

+

任意の非同期 onResponse(reply, ctx) は出力完了後にベストエフォートの通知を受け取ります。応答やライブストリームは変更せず、ツール宣言と実行ループはクライアントが担当します。

+

Bun でリクエストごとに一度、JS ゲートウェイミドルウェアの前に実行し、Codex 自身の ChatGPT サインインを含むすべてのプロバイダーに適用します。body はエージェント API のオブジェクトです。ctx は protocol、model、stream、path、agent、session、cwd、query、options、signal を持ちます。query は最後のユーザーテキストで、ツール結果と画像を除きます。ない識別情報は空で、Authorization は渡しません。

+

オブジェクトを返すと置き換え、undefined は元を保ちます。モデル、ストリーミング、クライアントのツールやツール選択を変えたフックは取り消され、失敗として扱われ、そのリクエストでは onResponse が呼ばれません。コピーを渡すので失敗や undefined の直接変更は破棄します。成功した変更は有効な順に渡ります。各フックは既定で 1 秒です。gatewayTimeoutMs は 100〜10000 ミリ秒の整数です。全体は合計予算を 2〜10 秒に制限し、起動と RPC を含めて 11 秒です。設定 → プラグインでオプションと呼び出し回数、時間、失敗、最新の結果を確認できます。ctx.report(code, bytes) は ready/empty/unbound/unauthorized/unavailable/invalid/skipped とバイト数のみを受け付けます。私的なテキストは保存せず、再読み込みで統計をリセットします。fetch に ctx.signal を使ってください。例外、不正な戻り値、タイムアウト、起動中のホストは元を保ちます。Bun はホスト権限で動くので信頼できるコードを使ってください。

+

magpie plugin add ./my-plugin で追加し、magpie plugin options my-plugin '{"serverUrl":"http://127.0.0.1:8000"}' で設定します。on/off と設定変更は再読み込みします。ソースだけの変更は設定の再読み込みが必要です。内部のタイトルや分類リクエストは対象外です。

+

ゲートウェイミドルウェア

プラグインはゲートウェイミドルウェアにもなれます。エージェントが magpie のゲートウェイに送るすべてのリクエストに対して、ルーティングの前に実行され、戻ってくる応答に対しても実行されるコードです。モデルに別名を付ける、システムプロンプトに追記する、リクエストを断る、モデルの出力を書き換えたり隠したりする、通ったものを独自に数える、といったことができます。プラグインのものかどうかに関係なく、すべてのプロバイダで動きます。

diff --git a/site/public/docs/plugins.html b/site/public/docs/plugins.html index c2d5a2d2b..79ca75c93 100644 --- a/site/public/docs/plugins.html +++ b/site/public/docs/plugins.html @@ -83,6 +83,7 @@ Provider ids Testing Publishing and listing + Async gateway request hooks Gateway middleware Tools for every agent Agent plugins @@ -609,6 +610,13 @@ m plugin logout acme +

Async gateway request hooks

+

A plugin can await I/O before an agent request is routed, for example to recall project context. Declare "magpie": { "hooks": "./hooks.js" } in package.json, or add a *.hooks.js / .mjs / .ts / .mts file (Bun runs TypeScript without a build step). Export a named async onRequest(body, ctx). A gateway-only package needs no OpenCode main/exports.

+

Optional async onResponse(reply, ctx) receives a best-effort completion notification after output finishes. It cannot change the reply and never holds the live stream. Client tool declarations and tool loops stay with the client.

+

It runs in Bun once per agent request, before the JS gateway middleware, for every provider, Codex's own ChatGPT sign-in included. body is the agent API object. ctx contains protocol, model, stream, path, agent, session, cwd, query, options and signal. The query is the latest user text, excluding tool results and images. Missing identity fields are empty; authorization headers are never included.

+

Return an object to replace the request, or undefined to keep it. A hook that changes the model, streaming, the client's tools or its tool choice is rolled back, as a failure, and gets no onResponse for that request. Each hook receives a clone; mutations from failed or undefined hooks are discarded. Successful changes follow enabled plugin order. Each hook defaults to one second; gatewayTimeoutMs accepts integers from 100 to 10000 milliseconds. The chain sums budgets, clamped to 2–10 seconds; startup plus RPC is bounded to 11 seconds. Settings → Plugins offers JSON options and call, latency, failure and outcome diagnostics. ctx.report(code, bytes) accepts ready/empty/unbound/unauthorized/unavailable/invalid/skipped and byte counts only. Statistics reset on reload and retain no private text. Use ctx.signal with fetch. Errors, invalid returns, timeouts and a host busy starting keep the request. Bun plugins have host privileges; install trusted code.

+

Install with magpie plugin add ./my-plugin; save options with magpie plugin options my-plugin '{"serverUrl":"http://127.0.0.1:8000"}'. On/off and options changes reload the host; source-only edits need a configuration reload. Internal title/classifier requests skip the hook.

+

Gateway middleware

A plugin can also be gateway middleware: code that magpie’s gateway runs on every request an agent sends it, before the request is routed, and on the reply on its way back. It can give a model another name, add to the system prompt, turn a request away, change or hide what the model says, or keep its own count of what goes through. It works with every provider, a plugin’s or not.

diff --git a/site/public/docs/zh/plugins.html b/site/public/docs/zh/plugins.html index 88ea9ecf1..2ae407bbb 100644 --- a/site/public/docs/zh/plugins.html +++ b/site/public/docs/zh/plugins.html @@ -83,6 +83,7 @@ 供应商 id 测试 发布与上架 + 异步网关请求钩子 网关中间件 给每个智能体的工具 Agent 插件 @@ -609,6 +610,13 @@ m plugin logout acme +

异步网关请求钩子

+

插件可以在 Agent 请求路由前等待外部 I/O,例如召回项目上下文。在 package.json 声明 "magpie": { "hooks": "./hooks.js" },或者添加 *.hooks.js / .mjs / .ts / .mts 文件(Bun 直接运行 TypeScript,无需构建)。导出具名异步 onRequest(body, ctx)。纯网关插件不需要 OpenCode 的 main/exports。

+

可选的异步 onResponse(reply, ctx) 在输出完成后接收尽力投递的通知,不修改回复,也不阻塞实时流。工具声明和工具循环由客户端负责。

+

它在 Bun 中运行,每个 Agent 请求调用一次,位于 JS 网关中间件之前,对所有供应商生效,包括 Codex 自己的 ChatGPT 登录。body 是 Agent API 请求对象;ctx 包含 protocol、model、stream、path、agent、session、cwd、query、options、signal。query 是最后一条用户文本,不含工具结果和图片;缺失身份信息为空,HTTP Authorization 不传入。

+

返回对象替换请求,undefined 保留此前请求。改动模型、流式、客户端工具或工具选择的钩子会被回滚,算作失败,这次请求不会调用它的 onResponse。每个钩子收到独立副本,失败或返回 undefined 时丢弃其原地修改。成功修改按启用顺序传给后续插件。每个钩子默认 1 秒;选项 gatewayTimeoutMs 可设为 100 到 10000 毫秒的整数。整条链按预算求和,限制为 2 到 10 秒,包含宿主启动及 RPC 共 11 秒。设置 → 插件提供选项编辑及调用次数、耗时、失败与最近结果。ctx.report(code, bytes) 只接受 ready/empty/unbound/unauthorized/unavailable/invalid/skipped 和字节数;不保存私有文本,重载后统计清零。fetch 应使用 ctx.signal。异常、畸形返回、超时、宿主正忙于启动时保留原请求。Bun 插件具有宿主权限,只安装可信代码。

+

用 magpie plugin add ./my-plugin 安装,magpie plugin options my-plugin '{"serverUrl":"http://127.0.0.1:8000"}' 设置选项。on/off 和选项变更触发宿主重载;仅修改源码需主动触发配置重载。内部标题和分类请求跳过此钩子。

+

网关中间件

插件还可以是网关中间件:agent 发给 magpie 网关的每个请求,在路由之前先经过它;回复在返回的路上也经过它。它可以给模型起别名、往系统提示词里加内容、拒绝请求、改写或隐藏模型说的话,或者自己统计经过的流量。它对所有供应商都起作用,不管是不是插件提供的。