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>
114 lines
6.2 KiB
Markdown
114 lines
6.2 KiB
Markdown
# 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`.
|