Files
magpie/docs/subsystems/gateway-request-hooks.md
T
yetoneandID-VerNe 3f6a101fe1 providers: Images per request in the editor's Advanced, per model, learned from 100milionseek's and Coarena's words (#6849)
Yuu_jiang_ on X (#6849): 100milionseek and Coarena take at most 8 images
a request, counted over the whole conversation, tool results included,
and every turn after the ninth screenshot failed with no way on but
/clear. ID-VerNe's max-images (the commit before) set one number from
the CLI. This builds on it:

- The cap is per provider, and optionally per model: max-images=8, or
  max-images=8,gemini-3-flash=10. The exact model is looked up first,
  then its upstream name, then "*" for all. The provider's cap moves
  with a model's local id like the other per-model limits.
- 100milionseek's "At most 8 images per request (MAX_IMAGES)." and
  Coarena's "A request may carry at most 8 images." are learned as
  Copilot's words are, by provider and model, so the first refusal is
  the last. A user's own number is fitted before any refusal; a learned
  one that is smaller still lowers it.
- Images are counted everywhere, a tool_result's too; the oldest are
  left out first and the latest user turn keeps its own. Only the
  request sent changes; session files are not touched. A request with
  no cap, or within it, goes out byte for byte as it came.
- The provider editor's Advanced (folded unless set) has Images per
  request under Max output, in maximages.js, imported as that field is
  drawn, in every language. A GUI save keeps the value when the field
  isn't drawn. An editor opened and closed is not dirty (the draft
  takes the value only when typed), and the import, like keyrates.js's,
  draws nothing once the editor has closed: before that, a quick close
  threw "Cannot read properties of null (reading 'maxImages')" and
  ('keyPriceRates'), which add-sheet and key-box-once caught.
- Budgets: app.js and the core +354, said in core_budget_test.go.

What was run:
- go test -count=1 -timeout 45m ./... on mote at 618bfc1a9 + these two
  commits: 102 packages ok; internal/tui red on TestEveryWordHasZh
  ("subagent pool", red on main, fixed by 6fbc24a05). After rebasing on
  origin/main c9e8422fa: internal/gui (budgets), tui, agent, testenv,
  gateway and provider: all ok. gofmt clean; GOOS=linux go vet -tags
  nogui ./... and GOOS=windows go vet ./... ok on mica.
- At 618bfc1a9 + these commits, on mote: provider-max-images 60/0,
  add-sheet 6/0, add-button 6/0, key-box-once 20/0, nokey-editor 4/0,
  provider-base-api 4/0, add-sheet-custom 32/0, kimi-subagent-pool
  20/0, sync-signins-except 20/0; old-webkit 4/2 (#6030 headerpresets,
  #5919), i18n-keys 3/1 (#6877), provider-max-output 4/20 (#6209),
  editor-hints 30/10 (the same at origin/main, in #6934).
- The whole GUI suite (1569 files, chromium + webkit, every language)
  on mote at the pre-fix head under another session's suite: 153 files
  red. Each red file rerun at the fixed head and at origin/main
  ad585ccd6 on mica (and mote for the close ones). Red at head only:
  add-button (Escape showed the discard confirm: the dirty draft, fixed),
  add-sheet and key-box-once (the null draft above, fixed); now 3/0,
  6/0, 20/0, provider-max-images 60/0. Every other red file is red the
  same at origin/main, the same subtests: filed with its numbers as
  #6934 (the #6782 class). i18n-keys' ", with an image" is #6877,
  old-webkit #6030/#5919, provider-max-output #6209.

Broken by hand (each red, then put back): the relay words left out
(TestImageCapLearnedFromRelayWords), per-model lookup by upstream name
gone (TestMaxImagesOnAModelListedByItsOwnID), a copy made when nothing
applies (TestImageCapNoneIsTheSameBytes), the learned cap over the
user's (TestMaxImagesStandsOverTheLearnedCap), the GUI save dropping it
(TestProviderSaveKeepsMaxImages), the CLI's empty value
(TestProviderSetMaxImages), the cap not moving with a local id, the JS
parse without its 1000 limit and the field not unfolding Advanced
(provider-max-images), and the draft written on open (provider-max-
images' Escape check, 20 red).

Not tried: no real 100milionseek or Coarena account (the words are the
reporter's literal ones); no GUI run on Windows or Linux; the suite's
GUI half ran under load, so many reds are shared timeouts.

Co-authored-by: ID-VerNe <yuu_seeing@foxmail.com>
2026-11-17 15:39:12 +08:00

206 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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.
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`, `kind`, 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.
`kind` is `"subagent"` when the client says the request is a subagent's
(Claude Code's `x-claude-code-agent-id`, Codex's `x-openai-subagent:
collab_spawn`; `hookKind` in `internal/gateway/middleware.go`) and `""`
otherwise. It is read from each request's own headers and is the same in
`onRequest` and that request's `onResponse`; a main-conversation request
after a subagent in the same session is `""`. The prompt and tool history
are never used to guess it.
`origin` is host-derived: `local` for a direct loopback request without
forwarding headers or a named gateway key; `magpie-key` for the sharing key
magpie made itself (`access.Identity.Default`: the key marked `lan`, the one
`LANKeyID` names, or an older magpie's settings-only key) when it comes from
this computer (`ownComputer`: loopback, one of this computer's own
addresses, or a WSL distro's network; never with forwarding headers, a
trusted proxy's included, nor through magpie web's page port), which is
where magpie writes it into the owner's own agents; `gateway-key` for any
other named key, on loopback too (one the owner made for someone else, a
value a user brought, a `sk-magpie-` key that didn't authenticate), and for
the sharing key from anywhere else: Gateway keys lists it with a Copy
button and offers it to connect other computers, so a friend may hold it;
otherwise `remote`. magpie has no "this named key is mine" mark, so every
key the owner made reads `gateway-key`. A plugin that serves the owner's own
agents beyond `local` checks `magpie-key`, never `gateway-key`
(plugins#526). Hosts before `magpie-key` (v0.1.2208) sent `gateway-key` for
the sharing key too, so a plugin that trusts only `local` sees both as
not local, as before. 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 is an integer from 100 to 30000 ms (default
1000 ms); a value outside the range is clamped to the nearer bound, and one that
isn't an integer gets the default. The request hook chain's budget is the hooks'
timeouts summed within two to ten seconds, or the longest hook's own timeout when
that is longer, so a slow deep recall configured for 15 seconds gets them (#5890,
plugins#926). Starting the host, including waiting for one already starting
during provider discovery, is bounded to eleven seconds; the whole run (startup
and the request RPC) to the budget plus one second, never under eleven seconds
(`gatewayWait` in `gateway.go`, which mirrors host.js's `gatewayTimeout` and
`gatewayBudget`). With every hook at 10000 ms or less both are the one
eleven-second limit they always were. 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.
## Sign-in notification
`export async function onSignIn(event, ctx)` is optional, and a hooks file may
export it alone, with no `onRequest` (a hook without `onRequest` is passed by
for requests). It hears of a subscription account that has to be signed in
again, or whose sign-in ends soon (shannnnnks on X: of several Codex accounts
behind the gateway, one is signed out now and then). `event` is
`{provider, providerName, account, state, endsAt?}`: the provider's id and
name, the account's label as the Providers page shows it (its email for most
sign-ins), and `state` `signed-out`, or `ending` with `endsAt` (an ISO time)
for a Claude sign-in within three days of its end. No token, credential mark
or vendor text is sent. `ctx` has the package `options` and an `AbortSignal`;
each hook gets its own timeout (`gatewayTimeoutMs`) within the chain's budget,
and one that throws or times out is logged and holds up none after it.
The accounts and the test are the app's sign-in alert's
([providers-accounts](providers-accounts.md), `provider.WatchSignIns`): an
account in use of a subscription switched on whose row says Sign in again
(any mark on a Claude, Copilot or plugin account; a built-in's revoked or
refused sign-in, ChatGPT's `token_revoked` and refused refresh among them),
told once until it is usable again. The magpie serving the gateway looks a
minute after it starts and every two minutes after
(`keepHooksToldOfSignIns`, `tellHooksOfSignIns` in
`internal/gateway/signin_hooks.go`), reading magpie's own files only. What
the hooks were told is kept in `signin-hooks.json` beside `providers.json`,
apart from the app's `signin-alerts.json`, so the desktop notification and
the hooks are each told, and a restart tells neither again. With no hook
installed (`plugin.HasGateway`) nothing is looked at or marked, so a hook
installed later hears of an account already signed out. Delivery
(`plugin.GatewaySignIn`) is fire-and-forget and best-effort like
`onResponse`: the mark is set as it is handed over, and a host that fails
to start loses it. An older host never calls `onSignIn`, and fails
to load a hooks file without `onRequest`.
Host request state is limited to 128 runs and expires after 15 minutes. The
response RPC has the request RPC's limit (the budget plus one second, at least
eleven seconds); 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. The
requests magpie makes on its own call `serve` directly and run no hooks:
Codex's compaction and its fallback turn, titles, System One's
classifier, search and vision (#4847). A request over a provider's byte
cap is fitted in the gateway itself, not by a hook (`body_cap.go`), as is
one over a model's image cap (`image_cap.go`, #6849). The cap is the
smaller of the user's `MaxImages` (by model id, `"*"` for all; the
editor's Advanced › Images per request, `magpie provider set <id>
max-images=8 max-images.<model>=10`) and the one a 400 taught that
provider's model: Copilot's words on a Copilot account, and
100milionseek's and Coarena's own words, which name their vendor, on any
provider. Every image counts, those in a tool_result too; the oldest go
first, the latest user message's are kept, and a request with no cap or
within it goes as the same bytes. Session files are never touched.
- `internal/gateway/gateway_hooks.go`: bounded response observation and
`gatewayReply`, a stream made one reply.
- `internal/gateway/signin_hooks.go`: sign-in events, and
`internal/plugin/gateway.go`'s `GatewaySignIn` and host.js's
`gatewaySignIn` that deliver them.
- `internal/plugin/gateway_test.go` and `internal/gateway/gateway_hook_test.go`:
failures, cancellation, ownership and real HTTP streaming.
`internal/plugin/gateway_budget_test.go`: a 12-second recall and response
given 15 seconds, the default and 10000 ms still cut by the host, two
8000 ms hooks still sharing ten seconds, an over-long timeout
clamped, caller cancellation under a long budget, and the Go mirror of the
budget.
`TestGatewaySignInHook` (a sign-in-only hook, options, a throwing hook)
and `TestRevokedAccountToldToHooksOnce` (a revoked ChatGPT account told
once, not before a hook is installed, with no token) guard sign-ins.
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`.