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>
74 lines
4.7 KiB
JavaScript
74 lines
4.7 KiB
JavaScript
// 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();
|
|
});
|
|
}
|
|
});
|
|
}
|