MengXiangxi (#3821): a GitHub repository tagged magpie-plugin whose package.json has magpie.hooks and no main, exports or index.js, a gateway request hook alone that installs and runs, never showed in the Plugins page's "Unofficial, on GitHub". readTagged read the magpie block's middleware, agent and page but not hooks, so such a package was taken for a provider: the file #1327's check looks for in the repository was its entry as Bun resolves it, index.js, which it hasn't, and the 404 left it out without a word. An inert index.js, as the reporter tried, lists it, as a provider. readTagged reads magpie.hooks. A package with hooks, no main or exports, and none of middleware, agent or page is of kind "hooks", and the file #1327's check looks for is its hooks file, so one whose hooks file isn't committed (a dist built only to publish) is still left out, as a middleware's is. The Plugins page picks "hooks" out with middleware, as both run in the gateway (kindOf), and its chip says Request hook, as an installed one's row does, through the word kindChip takes since the previous commit. docs/subsystems/gateway-request-hooks.md says so. Not changed: a raw 404 that GitHub's cache answers just after a push is still kept for that push in this process (the reporter's second point, #4067). plugins.js grows 51 bytes for it. With the previous commit the core's scripts are 24 bytes under main's, 1,527,948 of 1,528,076. What was run (tree 79884772, on origin/main56602426, go1.26.8, linux/amd64, Linux 5.15), outside graftcp, the Go tests at umask 077: - TestTaggedHooksAlone, new. IvanXxxxyyuffff/magpie-system-prompt-file's package.json as it is (a repository the report names) is kept, of kind hooks, with its spec, package and version 0.3.0, and its hooks file is the file asked for, never an index.js. someone/hooks-gone, whose hooks file is only in a dist it doesn't commit, is left out. With TestTaggedRepos*, -count=50: 350 of 350 pass; -race -count=20: 140 of 140, no race. - plugin-github-hooks.test.cjs, new. Seven repositories of /api/plugins/github's real answer of 2026-10-27 (two providers, three middleware, two of hooks alone): each of hooks alone has the gateway's chip saying Request hook and is picked out under Middleware, in English, Chinese, Traditional Chinese, Japanese and German at 980px and 420px. Chromium and WebKit, 3 runs: 22 of 22 each run. - Broken by hand, each red: - no kind made of magpie.hooks, as on main: TestTaggedHooksAlone, hooks alone not kept. - the kind made but the file looked for still the entry, index.js: the same. - the hooks file not looked for: TestTaggedHooksAlone, the hooks file not among the files asked for. - kindOf without hooks, so a Provider: plugin-github-hooks 0 of 22. - the card's chip not given its word: 0 of 22. - TestCoreScriptBudget: ok. - gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go vet for windows, go build -tags nogui for linux and darwin and go build for windows: exit 0 each. go vet and go build without the tag on linux: exit 1 (no libsoup-3.0 or gio-unix-2.0 here). - The Plugins page's GUI files near the change, 24 with the new one and i18n-keys, each run by itself in Chromium and in WebKit: 42 of 48 runs green. The other 6 are red the same at56602426, each file run the same way, and none is in what this changes: - i18n-keys, both engines: "a plugin's words are its own", for plugins/routing/i18n.js "masking…", which internal/masking/masking.go says too (#4053). - builtins, WebKit: Plugins › Built-in, the Observability switch's click times out, the stuck Plugins header (.lib-head.pm-head.stuck) over it taking the pointer. - plugin-github, WebKit: de 440, a click scrolls #view-plugins, 74 to 139 (65 to 119 at 56602426; #3218 has the same check red in Chromium). - plugin-github-wait, Chromium: de 440, Try again moves #view-plugins by 2. - plugin-release, WebKit: en and zh read "Serves Zed\n" for "Serves Zed". - go test -tags nogui -count=1 -timeout 45m ./... (Bun 1.4.2, log kept; 8m48s, load 32 at its start): 71 packages ok, internal/plugin among them, and 16 tests red in 6 packages, none of them this commit's tests or what they cover (internal/gui's are its gateway tests): agent TestCodexDriftReached (#3398); TestInstalledVersion, TestHowInstalled, TestCursorFolderFromTheEditorIsNotTheCLI, TestCopilotFolderFromAnIDEPluginIsNotTheCLI, TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir and TestZedAppPath (#3141); TestReasonixCLIRequiresSupportedNativeVersion and TestReasonixCLIRecoversAfterProbeTimeout (#3641); davsync TestSyncTeraCloudStillSeesOtherWrites (#3420); edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask 077, #3640); gateway TestPluginToldWhereTheAgentWorks (the /tmp/.git of #3675); gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie (#3649). The rest is what was run for 31a99237, at tree 2dd21699 on origin/main508911e4, the same Go change (github.go has since taken e4ccf67b's search timeout, in askTagged, not readTagged; 31a99237's plugins.js named the card's chip by hand, not through kindChip, and had three lines of comment this leaves out; not this tree): - Real use: magpie web built at508911e4and at that change's code (529f07e5, the same but for the new GUI file), each in a sandbox HOME, asked real GitHub for /api/plugins/github.508911e4listed 163 and left IvanXxxxyyuffff/magpie-system-prompt-file out. That change listed 164, it and MengXiangxi/magpie-openviking (which now has the inert index.js) of kind hooks. cyberElar/magpie-x-search (#1327's, a command only) was left out by both. Not tried: macOS and Windows; the real app's window (no display here, the page in Playwright's browsers only). Landed by yetone in a batch of Coffemon's patches from the issues. What was run, go1.26.8, on origin/maincc81ad4ea, then again at70a0c387c(gofmt, the three vets, the changed tests, umask 077): - mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask 077; agent, provider, library and gateway with an empty .git above TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the changed tests in agent, provider, gateway and gui; the timing tests -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok. TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js 1,312,975 of 1,315,316, no budget raised. - Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink at umask 077 and two Reasonix tests under an empty .git; on Linux (wsl-run) TestProgram at umask 077 with the old program.go. With each fix's code taken back to main's, the Gemini imageConfig tests, TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced, TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto, plugin-github-hooks, plugins-more-discover, plugin-namesake were red. Broken by hand: claudeKeyed always true (both OwnEndpointNeverAsked tests red), claudeAsk a no-op (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder (the three TestGitOnDisk tests red). - GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n, gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on Linux (wsl-run). 11 files had reds (click-scroll, panel-fold, plugin-card-update, plugin-github, plugin-move*, segs-glide, tray-totals, update-*), and run again side by side they fail the same on origin/maind80d75f30(79 pass, 26 fail here; 78 and 27 there). They are click-scroll guards ("the click must not scroll the page"), varying by language from run to run (#4385). copilot-ghe's route-after-close red is #1949, seen on main244d80e23too. In Chromium on mote, Chromium segfaulted partway through files (#4125): context-map, context-scroll-end and context-tune fail the same on origin/main0911a65e7, so the batch's own files (plugin-namesake, update-auto, plugins-more-discover, plugin-github-hooks) ran in Chromium on Linux: 62 of 62. - Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote) at 472a0608f (on70a0c387c): every package ok but internal/gateway, whose five reds were #4362's (Antigravity turned-away and TestCodexSpentGrokFailingIsTold), fixed on main ind80d75f30. After the rebase on244d80e23the five pass, and gofmt, the three vets and the targeted runs above were run again: ok. In Linux the sign-in, copilot, plugin-github*, plugins-more-discover, plugin-namesake, plugin-gateway, update-auto, quota-refresh-order and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe #1949, plugin-github's click scroll, both red on main too). - Rebased again onc7171a256, over its budget fixe94bf7a08: gofmt, vet of gui, gateway, provider and plugin, TestCoreScriptBudget (core 1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini, GitOnDisk and plugin tests, and in Linux both engines i18n-keys, update-mirror, plugin-namesake, plugins-more-discover, plugin-github-hooks and update-auto (138 of 138): ok. Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its Chromium segfaulted, #4125); macOS WebKit; the real app's window.
6.5 KiB
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.
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.
Discover lists a GitHub repository tagged magpie-plugin whose package.json has
magpie.hooks and no main or exports as a Request hook, picked out with
middleware (TaggedRepos checks that the hooks file is committed, as it does
middleware's; TestTaggedHooksAlone, plugin-github-hooks.test.cjs).
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, soonResponsesees what the agent got.serveAgentruns 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 andgatewayReply, a stream made one reply.internal/plugin/gateway_test.goandinternal/gateway/gateway_hook_test.go: failures, cancellation, ownership and real HTTP streaming.
Follow provider plugin verification to use isolated HOME and resolved Go/Bun executables. Targeted race acceptance:
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.