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>
236 lines
6.8 KiB
Go
236 lines
6.8 KiB
Go
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)
|
|
}
|