hooks: onSignIn tells a request hook of an account to sign in again

shannnnnks on X: with several Codex accounts behind the gateway, one is
now and then signed out, and they want the notify plugin to push it.

The magpie that serves the gateway now looks every 2 minutes (first
after 1) at the same sign-in states the desktop alert reads
(provider.WatchSignIns' checkSignIns, so every provider: Claude, Copilot
and plugin accounts that lapsed, and built-ins whose mark says the
sign-in expired or must be done again, Codex's revoked and refused
refreshes among them; accounts in use only). Each account to sign in
again, and each Claude sign-in ending within days, goes to every hooks
file that exports onSignIn, once until the account works again, kept in
signin-hooks.json beside the desktop alert's own file. The event is
{provider, providerName, account, state: "signed-out"|"ending", endsAt?}:
the account is its display label; no token and no vendor reason text.
It is fire-and-forget in the Bun host (gatewayRequest operation
"signIn"), each hook under its own timeout, one that throws doesn't stop
the next. With no hooks file nothing is looked at or marked. A hooks
file may now export onSignIn alone, without onRequest.

Docs: gateway-request-hooks.md (Sign-in notification),
providers-accounts.md, site plugins.html en/zh/ja.

Run on mote at d939dd699 (on origin/main 835439ebf; then rebased on
3d49ac069, whose three commits touch only GUI assets, GUI tests and site):
- gofmt -l internal: clean. go vet of internal/plugin, gateway and
  provider for darwin, linux and windows: ok.
- go test -count=1 ./internal/plugin ./internal/gateway: ok (123s, 950s).
- ./internal/provider: crashed in TestCodexAppWorkspaceSwitchReadsEachWorkspace
  (concurrent map writes in its fake server, #5800, not this change);
  run again with -skip WorkspaceSwitch: ok (130s).
- Red on the old code: with origin/main's host.js both new tests fail
  (TestGatewaySignInHook: "magpie.hooks exports no onRequest";
  TestRevokedAccountToldToHooksOnce: the hook never heard of it).
- Broken by hand: without the HasGateway gate, the gateway test fails
  with "told with no hook".

Not run: the full ./... suite (queued behind ~10 suites on mote's
suite.lock). Not tried: the real app with a real revoked Codex account;
the GUI suite (no GUI file changed).
This commit is contained in:
yetone
2026-11-10 01:44:24 +08:00
parent 769a625548
commit ab3710de3a
12 changed files with 350 additions and 3 deletions
+40
View File
@@ -103,6 +103,40 @@ 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 an eleven-second limit; each callback uses the configured
bounded hook timeout. Request-owned state is released after notification.
@@ -121,8 +155,14 @@ bounded hook timeout. Request-owned state is released after notification.
cap is fitted in the gateway itself, not by a hook (`body_cap.go`).
- `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.
`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:
File diff suppressed because one or more lines are too long
+2
View File
@@ -853,6 +853,8 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
// the magpie serving the gateway, and only it, keeps the saved accounts
// signed in, so two never refresh one sign-in at once
go provider.KeepLoginsAlive(ctx)
// and tells the request hooks of an account to sign in again
go keepHooksToldOfSignIns(ctx)
// and signs Codex and Claude Code in to their next account when the
// one they are on is spent
go provider.KeepOnAnAccountWithRoom(ctx)
+63
View File
@@ -0,0 +1,63 @@
package gateway
// The gateway's request hooks told of an account that has to be signed in
// again (shannnnnks on X: of several Codex accounts, one is signed out now
// and then, to be pushed by the notify plugin). The alert is the one the
// app notifies (provider.WatchSignIns): every subscription the Providers
// page says to sign in again (Claude, Copilot, ChatGPT's revoked or
// refused sign-ins, a plugin's), and a Claude sign-in about to end, each
// said once until the account is usable again. The hooks' marks are their
// own (provider.SignInHooksPath), so the app's notification and the hooks
// are each told.
import (
"context"
"log"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
)
// signInEvent is what a hook's onSignIn is handed for a: the provider,
// the account's label and its state, never a token or the vendor's words.
func signInEvent(a provider.SignInAlert) plugin.SignInEvent {
state := "signed-out"
if a.Kind == "ending" {
state = "ending"
}
return plugin.SignInEvent{Provider: a.Provider, ProviderName: a.Name, Account: a.User, State: state, EndsAt: a.EndsAt}
}
// tellHooksOfSignIns is one look: each alert due handed to the hooks. With
// no hook installed nothing is looked at, nor marked told, so a hook
// installed later hears of an account signed out before.
func tellHooksOfSignIns(ctx context.Context) {
if !plugin.HasGateway() {
return
}
for _, a := range provider.SignInAlertsAt(provider.SignInHooksPath()) {
log.Printf("sign-in hook: %s %s %s", a.Kind, a.Name, a.User)
signInToHooks(ctx, signInEvent(a))
}
}
// keepHooksToldOfSignIns looks a minute after the gateway starts and every
// two minutes after, as the app's alert does: a mark is set as a request is
// refused, so a look reads magpie's own files and asks no vendor.
func keepHooksToldOfSignIns(ctx context.Context) {
t := time.NewTimer(time.Minute)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
tellHooksOfSignIns(ctx)
t.Reset(2 * time.Minute)
}
}
// signInToHooks hands an event to the hooks; a test counts the calls.
var signInToHooks = plugin.GatewaySignIn
+95
View File
@@ -0,0 +1,95 @@
package gateway
import (
"context"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
// A ChatGPT account of several whose sign-in OpenAI revoked (shannnnnks
// on X: in gateway mode one Codex account is signed out now and then) is
// told to the request hooks' onSignIn once, with the provider, the
// account's label and "signed-out", and no token; not before a hook is
// installed to hear it, and not again on the next look.
func TestRevokedAccountToldToHooksOnce(t *testing.T) {
codexSignedIn(t, "spare@example.com")
t.Setenv("MAGPIE_BUN", testenv.Bun(t))
t.Cleanup(plugin.Settle)
access := codexAccessToken(t)
revokedUpstream(t, access)
if rec := codexPostTo(New(), `{"model":"gpt-5.5","stream":true,"input":"ping"}`); rec.Code != 200 {
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
}
if got := codexLapsed(t, "me@example.com"); got == "" {
t.Fatal("the revoked account isn't marked")
}
var mu sync.Mutex
var told []plugin.SignInEvent
was := signInToHooks
signInToHooks = func(ctx context.Context, ev plugin.SignInEvent) {
mu.Lock()
told = append(told, ev)
mu.Unlock()
was(ctx, ev)
}
t.Cleanup(func() { signInToHooks = was })
// no hook yet: nothing looked at, nothing marked told
tellHooksOfSignIns(t.Context())
if len(told) != 0 {
t.Fatalf("told with no hook: %+v", told)
}
if _, err := os.Stat(provider.SignInHooksPath()); !os.IsNotExist(err) {
t.Fatalf("marked told with no hook: %v", err)
}
out := filepath.Join(t.TempDir(), "signins.jsonl")
hook := filepath.Join(t.TempDir(), "notify.hooks.js")
os.WriteFile(hook, []byte(`import fs from "node:fs";
export function onSignIn(ev, ctx) { fs.appendFileSync(ctx.options.out, JSON.stringify(ev) + "\n") }`), 0o644)
if _, err := plugin.Add(t.Context(), hook); err != nil {
t.Fatal(err)
}
if err := plugin.SetOptions(hook, map[string]any{"out": out}); err != nil {
t.Fatal(err)
}
provider.ForgetAccounts()
tellHooksOfSignIns(t.Context())
tellHooksOfSignIns(t.Context())
mu.Lock()
n := len(told)
var first plugin.SignInEvent
if n > 0 {
first = told[0]
}
mu.Unlock()
if n != 1 || first.Provider != "codex" || first.Account != "me@example.com" || first.State != "signed-out" || first.ProviderName == "" {
t.Fatalf("told %d times: %+v", n, first)
}
deadline := time.Now().Add(15 * time.Second)
var b []byte
for !strings.Contains(string(b), "\n") {
if time.Now().After(deadline) {
t.Fatal("the hook never heard of it")
}
time.Sleep(20 * time.Millisecond)
b, _ = os.ReadFile(out)
}
if !strings.Contains(string(b), `"account":"me@example.com"`) || !strings.Contains(string(b), `"state":"signed-out"`) {
t.Fatalf("the hook heard %s", b)
}
for _, private := range []string{access, "r-acct", "token_revoked", "invalidated"} {
if strings.Contains(string(b), private) {
t.Fatalf("the event carries %q: %s", private, b)
}
}
}
+42
View File
@@ -258,3 +258,45 @@ func (r *GatewayRun) Close() {
defer cancel()
_ = r.h.call(ctx, "gatewayRequest", map[string]any{"operation": "close", "id": r.id, "token": r.token}, nil)
}
// SignInEvent is a subscription account that has to be signed in again
// (State "signed-out"), or whose sign-in ends at EndsAt (State "ending",
// Claude's), as magpie's own sign-in alert tells it. Account is the
// account's label as the Providers page shows it; no token, mark or
// vendor text is sent.
type SignInEvent struct {
Provider string `json:"provider"`
ProviderName string `json:"providerName"`
Account string `json:"account"`
State string `json:"state"`
EndsAt *time.Time `json:"endsAt,omitempty"`
}
// 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.
func GatewaySignIn(ctx context.Context, ev SignInEvent) {
if !HasGateway() {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 11*time.Second)
defer cancel()
checkList()
wait := time.NewTicker(10 * time.Millisecond)
defer wait.Stop()
for !hostMu.TryLock() {
select {
case <-ctx.Done():
return
case <-wait.C:
}
}
h, err := getLocked(ctx)
hostMu.Unlock()
if err != nil {
return
}
_ = h.call(ctx, "gatewayRequest", map[string]any{"operation": "signIn", "event": ev}, nil)
}()
}
+63
View File
@@ -0,0 +1,63 @@
package plugin
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// waitLines waits for path to hold n lines, and fails past ten seconds.
func waitLines(t *testing.T, path string, n int) string {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for {
b, _ := os.ReadFile(path)
if strings.Count(string(b), "\n") >= n {
return string(b)
}
if time.Now().After(deadline) {
t.Fatalf("%d lines not written: %q", n, b)
}
time.Sleep(10 * time.Millisecond)
}
}
// A request hook's onSignIn hears of an account to sign in again
// (shannnnnks on X): a hook that exports only onSignIn loads, gets the
// event with its own options, and one that throws holds up none after it.
// A hook with onRequest only is untouched, and requests still pass the
// sign-in-only hook by.
func TestGatewaySignInHook(t *testing.T) {
sandbox(t)
out := filepath.Join(t.TempDir(), "signins.jsonl")
gatewayFixture(t, `export function onSignIn(){ throw new Error("first fails") }`)
only := gatewayFixture(t, `import fs from "node:fs";
export function onSignIn(ev, ctx) {
fs.appendFileSync(ctx.options.out, JSON.stringify({ev, keys: Object.keys(ctx).sort(), aborted: ctx.signal.aborted}) + "\n");
}`)
if err := SetOptions(only, map[string]any{"out": out}); err != nil {
t.Fatal(err)
}
gatewayFixture(t, `export function onRequest(body){ return {...body, note: "kept"} }`)
loaded, err := Plugins(t.Context())
if err != nil {
t.Fatal(err)
}
for _, p := range loaded {
if p.Error != "" {
t.Fatalf("a hook failed to load: %+v", p)
}
}
GatewaySignIn(t.Context(), SignInEvent{Provider: "codex", ProviderName: "Codex", Account: "me@example.com", State: "signed-out"})
got := waitLines(t, out, 1)
want := `{"ev":{"provider":"codex","providerName":"Codex","account":"me@example.com","state":"signed-out"},"keys":["options","signal"],"aborted":false}`
if strings.TrimSpace(got) != want {
t.Fatalf("onSignIn got\n%s\nnot\n%s", got, want)
}
body := gatewayRequest(t.Context(), []byte(`{"note":"original"}`), GatewayContext{})
if !strings.Contains(string(body), `"kept"`) {
t.Fatalf("a sign-in-only hook stopped the request hooks: %s", body)
}
}
+30 -2
View File
@@ -1508,7 +1508,8 @@ async function loadPlugins(list) {
let gateway
if (p.gateway) {
gateway = await import(pathToFileURL(p.gateway).href)
if (typeof gateway.onRequest !== "function") throw new Error("magpie.hooks exports no onRequest")
// a hook that only listens for sign-ins needs no onRequest
if (typeof gateway.onRequest !== "function" && typeof gateway.onSignIn !== "function") throw new Error("magpie.hooks exports no onRequest")
}
let fns = []
// A gateway-only package needs no OpenCode entry. Mixed packages
@@ -1541,7 +1542,7 @@ async function loadPlugins(list) {
}
for (const x of r.got) hooks.push(x)
if (r.gateway) gatewayHooks.push({ spec: p.spec, options: p.options ?? {}, onRequest: r.gateway.onRequest,
onResponse: r.gateway.onResponse,
onResponse: r.gateway.onResponse, onSignIn: r.gateway.onSignIn,
state: { calls: 0, failures: 0, totalMillis: 0, lastOutcome: "idle", lastBytes: 0 } })
if (!isPi) loaded.push({ spec: p.spec })
}
@@ -1625,6 +1626,7 @@ async function gatewayBegin(p, signal) {
const total = AbortSignal.any([signal, run.controller.signal, AbortSignal.timeout(gatewayBudget())])
for (const h of gatewayHooks) {
if (total.aborted) break
if (typeof h.onRequest !== "function") continue
const ctl = new AbortController()
const timer = setTimeout(() => ctl.abort(), gatewayTimeout(h))
const ownSignal = AbortSignal.any([total, ctl.signal])
@@ -1708,8 +1710,34 @@ async function gatewayFinish(run, p, signal) {
return null
}
// An account that has to be signed in again, or whose sign-in ends soon,
// told to each hook's onSignIn once, as magpie's own alert is. The event
// holds the provider, the account's label and the state, never a token.
async function gatewaySignIn(p, signal) {
const ev = p.event
if (!ev || typeof ev !== "object") return null
const total = AbortSignal.any([signal, AbortSignal.timeout(gatewayBudget())])
for (const h of gatewayHooks) {
if (total.aborted) break
if (typeof h.onSignIn !== "function") continue
const ctl = new AbortController()
const timer = setTimeout(() => ctl.abort(), gatewayTimeout(h))
const ctx = { options: structuredClone(h.options), signal: AbortSignal.any([total, ctl.signal]) }
try {
await bounded(Promise.resolve().then(() => h.onSignIn(structuredClone(ev), ctx)), ctx.signal)
} catch {
if (!signal.aborted) send({ event: "log", level: "warn", message: `${h.spec}: gateway sign-in hook failed or timed out` })
} finally {
clearTimeout(timer)
ctl.abort()
}
}
return null
}
async function gatewayRequest(p, signal) {
if (p.operation === "begin") return gatewayBegin(p, signal)
if (p.operation === "signIn") return gatewaySignIn(p, signal)
const run = gatewayRuns.get(p.id)
if (!run || run.closed || run.token !== p.token) return null
if (p.operation === "close") { closeGateway(run); return null }
+11
View File
@@ -207,3 +207,14 @@ func WatchSignIns(ctx context.Context, send func(SignInAlert)) {
t.Reset(signInAlertEvery)
}
}
// SignInHooksPath keeps what the gateway's request hooks were told, apart
// from the app's notifications' marks (signInAlertPath): the magpie
// serving the gateway tells its hooks, and the app the user, each once.
func SignInHooksPath() string { return filepath.Join(filepath.Dir(Path()), "signin-hooks.json") }
// SignInAlertsAt is one look at the accounts: the sign-in alerts due, as
// WatchSignIns tells them, with what was told kept in path.
func SignInAlertsAt(path string) []SignInAlert {
return checkSignIns(path, signInStates(), time.Now())
}
+1
View File
@@ -686,6 +686,7 @@ m plugin logout acme</pre>
<h2 id="gateway-request"><a class="anchor" href="#gateway-request">非同期ゲートウェイリクエストフック</a></h2>
<p>プラグインはエージェントのリクエストをルーティングする前に I/O を待てます。package.json に <code>"magpie": { "hooks": "./hooks.js" }</code> を宣言するか、<code>*.hooks.js</code> / <code>.mjs</code> / <code>.ts</code> / <code>.mts</code> を追加し(Bun は TypeScript をビルドなしで実行します)、名前付きの非同期 <code>onRequest(body, ctx)</code> をエクスポートします。専用パッケージに OpenCode main/exports は不要です。</p>
<p>任意の非同期 <code>onResponse(reply, ctx)</code> は出力完了後にベストエフォートの通知を受け取ります。応答やライブストリームは変更せず、ツール宣言と実行ループはクライアントが担当します。</p>
<p>任意の非同期 <code>onSignIn(event, ctx)</code> は、サブスクリプションのアカウントにサインインし直す必要があるときに呼ばれます。<code>event</code> は <code>{provider, providerName, account, state, endsAt?}</code> で、<code>state</code> は <code>signed-out</code>、または Claude のサインインが 3 日以内に切れるときの <code>ending</code> です。アカウントが使えるようになるまで一度だけ通知され、トークンは含みません。フックファイルは <code>onSignIn</code> だけを書き出しても構いません。</p>
<p>Bun でリクエストごとに一度、JS ゲートウェイミドルウェアの前に実行し、Codex 自身の ChatGPT サインインを含むすべてのプロバイダーに適用します。body はエージェント API のオブジェクトです。ctx は <code>protocol</code>、<code>model</code>、<code>stream</code>、<code>path</code>、<code>agent</code>、<code>session</code>、<code>cwd</code>、<code>query</code>、<code>options</code>、<code>signal</code> を持ちます。query は最後のユーザーテキストで、ツール結果と画像を除きます。ない識別情報は空で、Authorization は渡しません。</p>
<p>オブジェクトを返すと置き換え、undefined は元を保ちます。モデル、ストリーミング、クライアントのツールやツール選択を変えたフックは取り消され、失敗として扱われ、そのリクエストでは <code>onResponse</code> が呼ばれません。コピーを渡すので失敗や undefined の直接変更は破棄します。成功した変更は有効な順に渡ります。各フックは既定で 1 秒です。<code>gatewayTimeoutMs</code> は 100〜10000 ミリ秒の整数です。全体は合計予算を 2〜10 秒に制限し、起動と RPC を含めて 11 秒です。設定 → プラグインでオプションと呼び出し回数、時間、失敗、最新の結果を確認できます。<code>ctx.report(code, bytes)</code> は ready/empty/unbound/unauthorized/unavailable/invalid/skipped とバイト数のみを受け付けます。私的なテキストは保存せず、再読み込みで統計をリセットします。fetch に <code>ctx.signal</code> を使ってください。例外、不正な戻り値、タイムアウト、起動中のホストは元を保ちます。Bun はホスト権限で動くので信頼できるコードを使ってください。</p>
<p><code>magpie plugin add ./my-plugin</code> で追加し、<code>magpie plugin options my-plugin '&lbrace;"serverUrl":"http://127.0.0.1:8000"&rbrace;'</code> で設定します。on/off と設定変更は再読み込みします。ソースだけの変更は設定の再読み込みが必要です。内部のタイトルや分類リクエストは対象外です。</p>
+1
View File
@@ -686,6 +686,7 @@ m plugin logout acme</pre>
<h2 id="gateway-request"><a class="anchor" href="#gateway-request">Async gateway request hooks</a></h2>
<p>A plugin can await I/O before an agent request is routed, for example to recall project context. Declare <code>"magpie": { "hooks": "./hooks.js" }</code> in package.json, or add a <code>*.hooks.js</code> / <code>.mjs</code> / <code>.ts</code> / <code>.mts</code> file (Bun runs TypeScript without a build step). Export a named async <code>onRequest(body, ctx)</code>. A gateway-only package needs no OpenCode main/exports.</p>
<p>Optional async <code>onResponse(reply, ctx)</code> 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.</p>
<p>Optional async <code>onSignIn(event, ctx)</code> hears of a subscription account that has to be signed in again: <code>event</code> is <code>{provider, providerName, account, state, endsAt?}</code>, <code>state</code> <code>signed-out</code>, or <code>ending</code> 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 <code>onSignIn</code>.</p>
<p>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 <code>protocol</code>, <code>model</code>, <code>stream</code>, <code>path</code>, <code>agent</code>, <code>session</code>, <code>cwd</code>, <code>query</code>, <code>options</code> and <code>signal</code>. The query is the latest user text, excluding tool results and images. Missing identity fields are empty; authorization headers are never included.</p>
<p>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 <code>onResponse</code> 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; <code>gatewayTimeoutMs</code> 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. <code>ctx.report(code, bytes)</code> accepts ready/empty/unbound/unauthorized/unavailable/invalid/skipped and byte counts only. Statistics reset on reload and retain no private text. Use <code>ctx.signal</code> with fetch. Errors, invalid returns, timeouts and a host busy starting keep the request. Bun plugins have host privileges; install trusted code.</p>
<p>Install with <code>magpie plugin add ./my-plugin</code>; save options with <code>magpie plugin options my-plugin '&lbrace;"serverUrl":"http://127.0.0.1:8000"&rbrace;'</code>. On/off and options changes reload the host; source-only edits need a configuration reload. Internal title/classifier requests skip the hook.</p>
+1
View File
@@ -686,6 +686,7 @@ m plugin logout acme</pre>
<h2 id="gateway-request"><a class="anchor" href="#gateway-request">异步网关请求钩子</a></h2>
<p>插件可以在 Agent 请求路由前等待外部 I/O,例如召回项目上下文。在 package.json 声明 <code>"magpie": { "hooks": "./hooks.js" }</code>,或者添加 <code>*.hooks.js</code> / <code>.mjs</code> / <code>.ts</code> / <code>.mts</code> 文件(Bun 直接运行 TypeScript,无需构建)。导出具名异步 <code>onRequest(body, ctx)</code>。纯网关插件不需要 OpenCode 的 main/exports。</p>
<p>可选的异步 <code>onResponse(reply, ctx)</code> 在输出完成后接收尽力投递的通知,不修改回复,也不阻塞实时流。工具声明和工具循环由客户端负责。</p>
<p>可选的异步 <code>onSignIn(event, ctx)</code> 在订阅账号需要重新登录时收到通知:<code>event</code> 为 <code>{provider, providerName, account, state, endsAt?}</code>,<code>state</code> 是 <code>signed-out</code>,或 Claude 登录三天内到期时的 <code>ending</code>。每次失效只通知一次,直到账号恢复可用,不含任何令牌。钩子文件可以只导出 <code>onSignIn</code>。</p>
<p>它在 Bun 中运行,每个 Agent 请求调用一次,位于 JS 网关中间件之前,对所有供应商生效,包括 Codex 自己的 ChatGPT 登录。body 是 Agent API 请求对象;ctx 包含 <code>protocol</code>、<code>model</code>、<code>stream</code>、<code>path</code>、<code>agent</code>、<code>session</code>、<code>cwd</code>、<code>query</code>、<code>options</code>、<code>signal</code>。query 是最后一条用户文本,不含工具结果和图片;缺失身份信息为空,HTTP Authorization 不传入。</p>
<p>返回对象替换请求,undefined 保留此前请求。改动模型、流式、客户端工具或工具选择的钩子会被回滚,算作失败,这次请求不会调用它的 <code>onResponse</code>。每个钩子收到独立副本,失败或返回 undefined 时丢弃其原地修改。成功修改按启用顺序传给后续插件。每个钩子默认 1 秒;选项 <code>gatewayTimeoutMs</code> 可设为 100 到 10000 毫秒的整数。整条链按预算求和,限制为 2 到 10 秒,包含宿主启动及 RPC 共 11 秒。设置 → 插件提供选项编辑及调用次数、耗时、失败与最近结果。<code>ctx.report(code, bytes)</code> 只接受 ready/empty/unbound/unauthorized/unavailable/invalid/skipped 和字节数;不保存私有文本,重载后统计清零。fetch 应使用 <code>ctx.signal</code>。异常、畸形返回、超时、宿主正忙于启动时保留原请求。Bun 插件具有宿主权限,只安装可信代码。</p>
<p>用 <code>magpie plugin add ./my-plugin</code> 安装,<code>magpie plugin options my-plugin '&lbrace;"serverUrl":"http://127.0.0.1:8000"&rbrace;'</code> 设置选项。on/off 和选项变更触发宿主重载;仅修改源码需主动触发配置重载。内部标题和分类请求跳过此钩子。</p>