diff --git a/docs/subsystems/gateway-request-hooks.md b/docs/subsystems/gateway-request-hooks.md index 7662dbf7c..3537b717e 100644 --- a/docs/subsystems/gateway-request-hooks.md +++ b/docs/subsystems/gateway-request-hooks.md @@ -72,11 +72,18 @@ 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 +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. @@ -138,8 +145,8 @@ 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 an eleven-second limit; each callback uses the configured -bounded hook timeout. Request-owned state is released after notification. +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 @@ -160,6 +167,11 @@ bounded hook timeout. Request-owned state is released after notification. `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. diff --git a/internal/plugin/gateway.go b/internal/plugin/gateway.go index d76020a35..58dd6a1d0 100644 --- a/internal/plugin/gateway.go +++ b/internal/plugin/gateway.go @@ -3,6 +3,7 @@ package plugin import ( "context" "encoding/json" + "math" "os" "path/filepath" "strings" @@ -130,28 +131,84 @@ func GatewayStates(ctx context.Context) map[string]GatewayState { // plugins.json and each plugin's package.json took ~1ms a request with 12 // plugins on Windows (#3725). func HasGateway() bool { + return gatewayLook().on +} + +// gatewayLook is HasGateway's look at the plugins, with the hooks' budget. +func gatewayLook() *gatewaySeen { now, g, list := time.Now().UnixNano(), filememo.Gen(), listPath() if c := hasGateway.Load(); c != nil && c.gen == g && c.list == list && now < c.until { - return c.on + return c } - on := false + var each []time.Duration for _, e := range Load().Plugins { if !e.Off && Gateway(Target(e.Spec)) != "" { - on = true - break + each = append(each, gatewayTimeout(e.Options)) } } - hasGateway.Store(&gatewaySeen{on: on, gen: g, list: list, until: now + int64(time.Second)}) - return on + c := &gatewaySeen{on: len(each) > 0, budget: gatewayBudget(each), gen: g, list: list, until: now + int64(time.Second)} + hasGateway.Store(c) + return c } // gatewaySeen is HasGateway's last look: for the plugins.json at list, -// while filememo's generation is gen, until until (UnixNano). +// while filememo's generation is gen, until until (UnixNano). budget is +// the hook chain's, as the host reckons it. type gatewaySeen struct { - on bool - gen uint64 - list string - until int64 + on bool + budget time.Duration + gen uint64 + list string + until int64 +} + +// gatewayTimeout is a hook's own timeout, as host.js's gatewayTimeout +// reckons it: gatewayTimeoutMs, a whole number clamped to 100–30000 ms, or +// one second when it isn't one. +func gatewayTimeout(opts map[string]any) time.Duration { + var ms float64 + switch v := opts["gatewayTimeoutMs"].(type) { + case float64: + ms = v + case int: + ms = float64(v) + case int64: + ms = float64(v) + case json.Number: + f, err := v.Float64() + if err != nil { + return time.Second + } + ms = f + default: + return time.Second + } + if math.IsNaN(ms) || ms != math.Trunc(ms) { + return time.Second + } + return time.Duration(min(30000, max(100, ms))) * time.Millisecond +} + +// gatewayBudget is the hook chain's budget, as host.js's gatewayBudget +// reckons it: the hooks' timeouts summed within 2–10 seconds, or the +// longest one's when that is longer (#5890). +func gatewayBudget(each []time.Duration) time.Duration { + var sum, most time.Duration + for _, d := range each { + sum += d + most = max(most, d) + } + return max(min(10*time.Second, max(2*time.Second, sum)), most) +} + +// gatewayStart bounds starting the host (or waiting for one already +// starting) before a hook RPC, whatever the hooks' budget. +const gatewayStart = 11 * time.Second + +// gatewayWait bounds a hook RPC: the chain's budget and a second for the +// host's answer, never less than the eleven seconds it always had. +func gatewayWait() time.Duration { + return max(gatewayStart, gatewayLook().budget+time.Second) } var hasGateway atomic.Pointer[gatewaySeen] @@ -175,8 +232,13 @@ func GatewayBegin(ctx context.Context, body []byte, info GatewayContext) *Gatewa if !HasGateway() { return nil } - start, cancel := context.WithTimeout(ctx, 11*time.Second) + // The whole run is bounded by the hooks' budget and a second; starting + // the host within it by the eleven seconds it always had. With the + // default budget (at most 10s) the two are one deadline, as before. + total, cancel := context.WithTimeout(ctx, gatewayWait()) defer cancel() + start, cancelStart := context.WithTimeout(total, gatewayStart) + defer cancelStart() checkList() // Provider discovery may already be starting the shared host. Wait within // the same hook budget rather than skipping recall on the first request. @@ -203,7 +265,7 @@ func GatewayBegin(ctx context.Context, body []byte, info GatewayContext) *Gatewa 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) + err = h.call(total, "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 } @@ -235,8 +297,9 @@ func (r *GatewayRun) Finish(ctx context.Context, reply json.RawMessage, success if len(request) != 0 && json.Valid(request[0]) { params["request"] = append(json.RawMessage(nil), request[0]...) } + wait := gatewayWait() go func() { - ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 11*time.Second) + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), wait) defer cancel() _ = r.h.call(ctx, "gatewayRequest", params, nil) }() @@ -274,25 +337,29 @@ type SignInEvent struct { // GatewaySignIn hands ev to every request hook's onSignIn, without waiting // for them: the host is started if it isn't, within the request hooks' -// eleven seconds. Nothing is done for a user with no hooks. +// eleven seconds, and the hooks have their budget. Nothing is done for a +// user with no hooks. func GatewaySignIn(ctx context.Context, ev SignInEvent) { if !HasGateway() { return } + total := gatewayWait() go func() { - ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 11*time.Second) + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), total) defer cancel() + start, cancelStart := context.WithTimeout(ctx, gatewayStart) + defer cancelStart() checkList() wait := time.NewTicker(10 * time.Millisecond) defer wait.Stop() for !hostMu.TryLock() { select { - case <-ctx.Done(): + case <-start.Done(): return case <-wait.C: } } - h, err := getLocked(ctx) + h, err := getLocked(start) hostMu.Unlock() if err != nil { return diff --git a/internal/plugin/gateway_budget_test.go b/internal/plugin/gateway_budget_test.go new file mode 100644 index 000000000..4a692e4a9 --- /dev/null +++ b/internal/plugin/gateway_budget_test.go @@ -0,0 +1,219 @@ +package plugin + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// TestGatewayHookSlowRecallUsesConfiguredBudget (#5890, aboat0625-cpu): a +// recall that takes 12s, given 15s, gets its result, past the 10s chain +// and 11s RPC bounds every hook had; and its onResponse gets the same 15s. +func TestGatewayHookSlowRecallUsesConfiguredBudget(t *testing.T) { + sandbox(t) + output := filepath.Join(t.TempDir(), "captured") + spec := gatewayFixture(t, `import fs from "node:fs"; +export async function onRequest(body, ctx) { + await new Promise(resolve => setTimeout(resolve, 12000)); + ctx.report("ready", 12); + return {...body, note: "recalled"}; +} +export async function onResponse(reply, ctx) { + await new Promise(resolve => setTimeout(resolve, 12000)); + if (!ctx.signal.aborted) fs.writeFileSync(ctx.options.output, JSON.stringify(reply)); +}`) + if err := SetOptions(spec, map[string]any{"gatewayTimeoutMs": 15000, "output": output}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 40*time.Second) + defer cancel() + run := GatewayBegin(ctx, []byte(`{"note":"original"}`), GatewayContext{}) + if run == nil || !strings.Contains(string(run.Body), `"recalled"`) { + if run != nil { + run.Close() + } + t.Fatal("slow recall was dropped despite its configured budget") + } + run.Finish(ctx, json.RawMessage(`{"answer":"done"}`), true, run.Body) + for { + if b, err := os.ReadFile(output); err == nil { + if string(b) != `{"answer":"done"}` { + t.Fatalf("captured %s", b) + } + return + } + select { + case <-ctx.Done(): + t.Fatal("a slow onResponse was cut before its configured budget") + case <-time.After(50 * time.Millisecond): + } + } +} + +// TestGatewayHookDefaultBudgetStillCuts: without a longer timeout a slow +// hook is cut where it always was, by the host's own timer ("timeout", not +// the RPC's deadline, which would read "cancelled"): at the default second, +// and at 10s for the 10000 every host took. +func TestGatewayHookDefaultBudgetStillCuts(t *testing.T) { + for _, tc := range []struct { + name string + opts map[string]any + most float64 // ms the hook may have taken: far over its bound, far under the 11s RPC's + }{{"default", nil, 8000}, {"10000", map[string]any{"gatewayTimeoutMs": 10000}, 0}} { + t.Run(tc.name, func(t *testing.T) { + sandbox(t) + spec := gatewayFixture(t, `export async function onRequest(body) { + await new Promise(resolve => setTimeout(resolve, 12000)); + return {...body, note: "recalled"}; +}`) + if tc.opts != nil { + if err := SetOptions(spec, tc.opts); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithTimeout(t.Context(), 40*time.Second) + defer cancel() + if out := gatewayRequest(ctx, []byte(`{"note":"original"}`), GatewayContext{}); string(out) != `{"note":"original"}` { + t.Fatalf("a hook past its default budget was kept: %s", out) + } + state := GatewayStates(t.Context())[spec] + if state.LastOutcome != "timeout" || tc.most > 0 && state.AvgMillis > tc.most { + t.Fatalf("the hook wasn't cut by its own budget: %+v", state) + } + }) + } +} + +// TestGatewayHookChainStillTenSeconds: hooks of 10000 or less share the +// chain's 10s as before. Two of 8000 that take 6s each: the first is kept, +// the second is cut when the chain's 10s are up. +func TestGatewayHookChainStillTenSeconds(t *testing.T) { + sandbox(t) + var specs []string + for _, name := range []string{"first", "second"} { + spec := gatewayFixture(t, `export async function onRequest(body) { + await new Promise(resolve => setTimeout(resolve, 6000)); + return {...body, `+name+`: true}; +}`) + if err := SetOptions(spec, map[string]any{"gatewayTimeoutMs": 8000}); err != nil { + t.Fatal(err) + } + specs = append(specs, spec) + } + ctx, cancel := context.WithTimeout(t.Context(), 40*time.Second) + defer cancel() + out := gatewayRequest(ctx, []byte(`{"note":"original"}`), GatewayContext{}) + if !strings.Contains(string(out), `"first":true`) || strings.Contains(string(out), `"second"`) { + t.Fatalf("the chain's 10s changed: %s", out) + } + if state := GatewayStates(t.Context())[specs[1]]; state.LastOutcome != "timeout" { + t.Fatalf("the second hook wasn't cut by the chain: %+v", state) + } +} + +// TestGatewayHookTimeoutClamps: a timeout over 30000 is taken as 30000, +// not as the default second (the reporter's 130000 fell back to 1000). +func TestGatewayHookTimeoutClamps(t *testing.T) { + sandbox(t) + spec := gatewayFixture(t, `export async function onRequest(body) { + await new Promise(resolve => setTimeout(resolve, 1500)); + return {...body, note: "recalled"}; +}`) + if err := SetOptions(spec, map[string]any{"gatewayTimeoutMs": 130000}); err != nil { + t.Fatal(err) + } + if out := gatewayRequest(t.Context(), []byte(`{"note":"original"}`), GatewayContext{}); !strings.Contains(string(out), `"recalled"`) { + t.Fatalf("an over-long timeout fell back to the default: %s", out) + } +} + +// TestGatewayHookLongBudgetCallerCancellation: a hook given 15s still +// stops at once when the caller goes. +func TestGatewayHookLongBudgetCallerCancellation(t *testing.T) { + sandbox(t) + started, stopped := make(chan struct{}), make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(started) + <-r.Context().Done() + close(stopped) + })) + defer srv.Close() + spec := gatewayFixture(t, `export async function onRequest(body,ctx) { await fetch(`+string(mustJSON(t, srv.URL))+`,{signal:ctx.signal}); return {...body, note: "recalled"} }`) + if err := SetOptions(spec, map[string]any{"gatewayTimeoutMs": 15000}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan []byte, 1) + go func() { done <- gatewayRequest(ctx, []byte(`{"note":"original"}`), GatewayContext{}) }() + select { + case <-started: + case <-time.After(10 * time.Second): + t.Fatal("hook never started") + } + cancel() + // well under the 15s the hook was given + select { + case out := <-done: + if string(out) != `{"note":"original"}` { + t.Fatalf("cancel changed body: %s", out) + } + case <-time.After(5 * time.Second): + t.Fatal("caller cancellation waited for the hook's budget") + } + select { + case <-stopped: + case <-time.After(5 * time.Second): + t.Fatal("caller cancellation did not stop the hook's HTTP") + } +} + +// TestGatewayBudgetMirrorsHost: gateway.go reckons the hooks' timeouts and +// the chain's budget as host.js does, and the RPC bound stays 11s for +// every budget a host had before. +func TestGatewayBudgetMirrorsHost(t *testing.T) { + for v, want := range map[any]time.Duration{ + nil: time.Second, "15000": time.Second, 15000.5: time.Second, true: time.Second, + float64(15000): 15 * time.Second, 15000: 15 * time.Second, float64(99): 100 * time.Millisecond, + float64(-5): 100 * time.Millisecond, float64(130000): 30 * time.Second, json.Number("2000"): 2 * time.Second, + } { + if got := gatewayTimeout(map[string]any{"gatewayTimeoutMs": v}); got != want { + t.Errorf("gatewayTimeout(%v) = %v, want %v", v, got, want) + } + } + s := time.Second + for _, tc := range []struct { + each []time.Duration + want time.Duration + }{ + {nil, 2 * s}, {[]time.Duration{s}, 2 * s}, {[]time.Duration{5 * s, 5 * s, 5 * s}, 10 * s}, + {[]time.Duration{10 * s}, 10 * s}, {[]time.Duration{15 * s, s}, 15 * s}, {[]time.Duration{30 * s, 30 * s}, 30 * s}, + } { + if got := gatewayBudget(tc.each); got != tc.want { + t.Errorf("gatewayBudget(%v) = %v, want %v", tc.each, got, tc.want) + } + } + sandbox(t) + spec := gatewayFixture(t, `export function onRequest(body){return body}`) + if got := gatewayWait(); got != 11*s { + t.Fatalf("default RPC bound %v, want 11s", got) + } + if err := SetOptions(spec, map[string]any{"gatewayTimeoutMs": 10000}); err != nil { + t.Fatal(err) + } + if got := gatewayWait(); got != 11*s { + t.Fatalf("RPC bound for 10000: %v, want 11s", got) + } + if err := SetOptions(spec, map[string]any{"gatewayTimeoutMs": 15000}); err != nil { + t.Fatal(err) + } + if got := gatewayWait(); got != 16*s { + t.Fatalf("RPC bound for 15000: %v, want 16s", got) + } +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 54f48ee58..c05e96c5f 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -1603,8 +1603,15 @@ function bounded(promise, signal) { const gatewayRuns = new Map() const GATEWAY_RUN_LIMIT = 128 const GATEWAY_RUN_TTL = 15 * 60 * 1000 -const gatewayTimeout = (h) => Number.isInteger(h.options.gatewayTimeoutMs) && h.options.gatewayTimeoutMs >= 100 && h.options.gatewayTimeoutMs <= 10000 ? h.options.gatewayTimeoutMs : 1000 -const gatewayBudget = () => Math.min(10000, Math.max(2000, gatewayHooks.reduce((n, h) => n + gatewayTimeout(h), 0))) +// A hook's own timeout: gatewayTimeoutMs, an integer clamped to 100–30000 +// ms (a slow deep recall may take 20s, #5890), or 1000 when it isn't one. +// Keep gatewayTimeout in gateway.go the same. +const GATEWAY_HOOK_LEAST = 100, GATEWAY_HOOK_MOST = 30000 +const gatewayTimeout = (h) => Number.isInteger(h.options.gatewayTimeoutMs) ? Math.min(GATEWAY_HOOK_MOST, Math.max(GATEWAY_HOOK_LEAST, h.options.gatewayTimeoutMs)) : 1000 +// The chain's budget: the hooks' timeouts summed within 2–10s, as before, +// or the longest one's own timeout when that is longer, so a hook given +// more than 10s gets it (at most 30s). gatewayBudget in gateway.go mirrors it. +const gatewayBudget = () => Math.max(Math.min(10000, Math.max(2000, gatewayHooks.reduce((n, h) => n + gatewayTimeout(h), 0))), ...gatewayHooks.map(gatewayTimeout)) function closeGateway(run) { if (!run || run.closed) return diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.html index 6ada0fc73..1bbb0ccf4 100644 --- a/site/public/docs/ja/plugins.html +++ b/site/public/docs/ja/plugins.html @@ -691,7 +691,7 @@ m plugin logout acme
任意の非同期 onResponse(reply, ctx) は出力完了後にベストエフォートの通知を受け取ります。応答やライブストリームは変更せず、ツール宣言と実行ループはクライアントが担当します。
任意の非同期 onSignIn(event, ctx) は、サブスクリプションのアカウントにサインインし直す必要があるときに呼ばれます。event は {provider, providerName, account, state, endsAt?} で、state は signed-out、または Claude のサインインが 3 日以内に切れるときの ending です。アカウントが使えるようになるまで一度だけ通知され、トークンは含みません。フックファイルは onSignIn だけを書き出しても構いません。
Bun でリクエストごとに一度、JS ゲートウェイミドルウェアの前に実行し、Codex 自身の ChatGPT サインインを含むすべてのプロバイダーに適用します。body はエージェント API のオブジェクトです。ctx は protocol、model、stream、path、agent、session、cwd、query、options、signal を持ちます。query は最後のユーザーテキストで、ツール結果と画像を除きます。ない識別情報は空で、Authorization は渡しません。
オブジェクトを返すと置き換え、undefined は元を保ちます。モデル、ストリーミング、クライアントのツールやツール選択を変えたフックは取り消され、失敗として扱われ、そのリクエストでは onResponse が呼ばれません。コピーを渡すので失敗や undefined の直接変更は破棄します。成功した変更は有効な順に渡ります。各フックは既定で 1 秒です。gatewayTimeoutMs は 100〜10000 ミリ秒の整数です。全体は合計予算を 2〜10 秒に制限し、起動と RPC を含めて 11 秒です。設定 → プラグインでオプションと呼び出し回数、時間、失敗、最新の結果を確認できます。ctx.report(code, bytes) は ready/empty/unbound/unauthorized/unavailable/invalid/skipped とバイト数のみを受け付けます。私的なテキストは保存せず、再読み込みで統計をリセットします。fetch に ctx.signal を使ってください。例外、不正な戻り値、タイムアウト、起動中のホストは元を保ちます。Bun はホスト権限で動くので信頼できるコードを使ってください。
オブジェクトを返すと置き換え、undefined は元を保ちます。モデル、ストリーミング、クライアントのツールやツール選択を変えたフックは取り消され、失敗として扱われ、そのリクエストでは onResponse が呼ばれません。コピーを渡すので失敗や undefined の直接変更は破棄します。成功した変更は有効な順に渡ります。各フックは既定で 1 秒です。gatewayTimeoutMs は 100〜30000 ミリ秒の整数で、範囲外の値は近い方の境界に丸めます。全体は合計予算を 2〜10 秒に制限し、最も長いフック自身のタイムアウトがそれより長ければそれを使います。ホストの起動は 11 秒まで、起動と RPC を合わせてチェーンの予算に 1 秒を足した時間(最低 11 秒)です。設定 → プラグインでオプションと呼び出し回数、時間、失敗、最新の結果を確認できます。ctx.report(code, bytes) は ready/empty/unbound/unauthorized/unavailable/invalid/skipped とバイト数のみを受け付けます。私的なテキストは保存せず、再読み込みで統計をリセットします。fetch に ctx.signal を使ってください。例外、不正な戻り値、タイムアウト、起動中のホストは元を保ちます。Bun はホスト権限で動くので信頼できるコードを使ってください。
magpie plugin add ./my-plugin で追加し、magpie plugin options my-plugin '{"serverUrl":"http://127.0.0.1:8000"}' で設定します。on/off と設定変更は再読み込みします。ソースだけの変更は設定の再読み込みが必要です。内部のタイトルや分類リクエストは対象外です。
Optional async onResponse(reply, ctx) receives a best-effort completion notification after output finishes. It cannot change the reply and never holds the live stream. Client tool declarations and tool loops stay with the client.
Optional async onSignIn(event, ctx) hears of a subscription account that has to be signed in again: event is {provider, providerName, account, state, endsAt?}, state signed-out, or ending for a Claude sign-in within three days of its end. It is told once until the account works again, and carries no token. A hooks file may export only onSignIn.
It runs in Bun once per agent request, before the JS gateway middleware, for every provider, Codex's own ChatGPT sign-in included. body is the agent API object. ctx contains protocol, model, stream, path, agent, session, cwd, query, options and signal. The query is the latest user text, excluding tool results and images. Missing identity fields are empty; authorization headers are never included.
Return an object to replace the request, or undefined to keep it. A hook that changes the model, streaming, the client's tools or its tool choice is rolled back, as a failure, and gets no onResponse for that request. Each hook receives a clone; mutations from failed or undefined hooks are discarded. Successful changes follow enabled plugin order. Each hook defaults to one second; gatewayTimeoutMs accepts integers from 100 to 10000 milliseconds. The chain sums budgets, clamped to 2–10 seconds; startup plus RPC is bounded to 11 seconds. Settings → Plugins offers JSON options and call, latency, failure and outcome diagnostics. ctx.report(code, bytes) accepts ready/empty/unbound/unauthorized/unavailable/invalid/skipped and byte counts only. Statistics reset on reload and retain no private text. Use ctx.signal with fetch. Errors, invalid returns, timeouts and a host busy starting keep the request. Bun plugins have host privileges; install trusted code.
Return an object to replace the request, or undefined to keep it. A hook that changes the model, streaming, the client's tools or its tool choice is rolled back, as a failure, and gets no onResponse for that request. Each hook receives a clone; mutations from failed or undefined hooks are discarded. Successful changes follow enabled plugin order. Each hook defaults to one second; gatewayTimeoutMs accepts integers from 100 to 30000 milliseconds; a value outside that range is clamped to the nearer bound. The chain sums budgets, clamped to 2–10 seconds, or takes the longest hook's own timeout when that is longer; host startup is bounded to 11 seconds, and startup plus RPC to the chain budget plus one second (at least 11 seconds). Settings → Plugins offers JSON options and call, latency, failure and outcome diagnostics. ctx.report(code, bytes) accepts ready/empty/unbound/unauthorized/unavailable/invalid/skipped and byte counts only. Statistics reset on reload and retain no private text. Use ctx.signal with fetch. Errors, invalid returns, timeouts and a host busy starting keep the request. Bun plugins have host privileges; install trusted code.
Install with magpie plugin add ./my-plugin; save options with magpie plugin options my-plugin '{"serverUrl":"http://127.0.0.1:8000"}'. On/off and options changes reload the host; source-only edits need a configuration reload. Internal title/classifier requests skip the hook.
可选的异步 onResponse(reply, ctx) 在输出完成后接收尽力投递的通知,不修改回复,也不阻塞实时流。工具声明和工具循环由客户端负责。
可选的异步 onSignIn(event, ctx) 在订阅账号需要重新登录时收到通知:event 为 {provider, providerName, account, state, endsAt?},state 是 signed-out,或 Claude 登录三天内到期时的 ending。每次失效只通知一次,直到账号恢复可用,不含任何令牌。钩子文件可以只导出 onSignIn。
它在 Bun 中运行,每个 Agent 请求调用一次,位于 JS 网关中间件之前,对所有供应商生效,包括 Codex 自己的 ChatGPT 登录。body 是 Agent API 请求对象;ctx 包含 protocol、model、stream、path、agent、session、cwd、query、options、signal。query 是最后一条用户文本,不含工具结果和图片;缺失身份信息为空,HTTP Authorization 不传入。
返回对象替换请求,undefined 保留此前请求。改动模型、流式、客户端工具或工具选择的钩子会被回滚,算作失败,这次请求不会调用它的 onResponse。每个钩子收到独立副本,失败或返回 undefined 时丢弃其原地修改。成功修改按启用顺序传给后续插件。每个钩子默认 1 秒;选项 gatewayTimeoutMs 可设为 100 到 10000 毫秒的整数。整条链按预算求和,限制为 2 到 10 秒,包含宿主启动及 RPC 共 11 秒。设置 → 插件提供选项编辑及调用次数、耗时、失败与最近结果。ctx.report(code, bytes) 只接受 ready/empty/unbound/unauthorized/unavailable/invalid/skipped 和字节数;不保存私有文本,重载后统计清零。fetch 应使用 ctx.signal。异常、畸形返回、超时、宿主正忙于启动时保留原请求。Bun 插件具有宿主权限,只安装可信代码。
返回对象替换请求,undefined 保留此前请求。改动模型、流式、客户端工具或工具选择的钩子会被回滚,算作失败,这次请求不会调用它的 onResponse。每个钩子收到独立副本,失败或返回 undefined 时丢弃其原地修改。成功修改按启用顺序传给后续插件。每个钩子默认 1 秒;选项 gatewayTimeoutMs 可设为 100 到 30000 毫秒的整数,超出范围时取较近的边界。整条链按预算求和,限制为 2 到 10 秒;若最长的单个钩子超时更长,则以它为准。宿主启动最多 11 秒,启动及 RPC 共为链预算加 1 秒(至少 11 秒)。设置 → 插件提供选项编辑及调用次数、耗时、失败与最近结果。ctx.report(code, bytes) 只接受 ready/empty/unbound/unauthorized/unavailable/invalid/skipped 和字节数;不保存私有文本,重载后统计清零。fetch 应使用 ctx.signal。异常、畸形返回、超时、宿主正忙于启动时保留原请求。Bun 插件具有宿主权限,只安装可信代码。
用 magpie plugin add ./my-plugin 安装,magpie plugin options my-plugin '{"serverUrl":"http://127.0.0.1:8000"}' 设置选项。on/off 和选项变更触发宿主重载;仅修改源码需主动触发配置重载。内部标题和分类请求跳过此钩子。