diff --git a/docs/subsystems/gateway-request-hooks.md b/docs/subsystems/gateway-request-hooks.md index d1d62843d..7662dbf7c 100644 --- a/docs/subsystems/gateway-request-hooks.md +++ b/docs/subsystems/gateway-request-hooks.md @@ -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: diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 6db987622..aa7252866 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -48,7 +48,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Codex's credential store | Codex 0.162 keeps its ChatGPT sign-in where `cli_auth_credentials_store` in `$CODEX_HOME/config.toml` says (`codex-rs/login/src/auth/storage.rs`): `file` (default) is `auth.json`; `keyring` the system keychain alone; `auto` the keychain, else `auth.json`, on read and on save; `ephemeral` Codex's memory. Saved to the keychain, Codex removes `auth.json` (#2312, #2367, Dony2050). On macOS magpie reads that item through `security`, as it reads Claude Code's: service `Codex Auth`, account `cli|` + the first 16 hex digits of SHA-256 of the canonical CODEX_HOME (`codexKeychainAccount`), the value auth.json's JSON on one line. `readCodexLogin` is the one reader: `codexAccount`, `codexToken`, `liveLogin`, `CodexAPIKeySignedIn`, `codexLoginAuth`, `codexUntil` (the usage card's and each saved account row's `Until`, from the sign-in Codex holds when it holds that one), session identities and the agent's wiring (`provider.CodexSignIn`: `codexChatGPT`, `Agent.Source`) go through it. `keyring` with no item is signed out; `auto` with no item, or one the keychain wouldn't give, is `auth.json`, as Codex does. An item the keychain wouldn't give under `keyring` is not known (`codexStoreError`), never signed out. With `[features] secret_auth_storage` on (Codex's default on Windows) keyring and auto mean Codex's encrypted auth storage, which magpie doesn't read; nor does it read the Linux or Windows keychain. There `keyring` and `ephemeral` are not known, `auto` is `auth.json` when Codex left one, and the saved accounts' reason says to set `file` (`codexSignedOutWhy`). Requirements an admin manages (`requirements.cli_auth_credentials_store`) aren't read. Reading the secret can put up to two macOS prompts in front of the user, who may type their password, so one read per item is in flight at a time and waits up to 2 minutes for them (`keychainAsk`, `askCodexKeychain`), outside the cache's lock. A reader waits at most 5s from when that ask started (`keychainHold`) and is otherwise told magpie is waiting for an answer (`errKeychainWaiting`); no request or page waits out the prompt. `security` exit 44 is no item; 51 (errSecAuthFailed) or 128 (errSecUserCanceled) is denied or cancelled (`errKeychainRefused`); the 2 minutes running out is no answer (`errKeychainNoAnswer`); anything else is `errKeychainUnread`. Each says so in the saved accounts' reason, and none of them is signed out. A read the keychain gave is kept while the item is unchanged: after 10s a reader asks only the item's modification date (`Stat`, `find-generic-password` without `-w`, which shows no prompt) and reads the secret again only when Codex or magpie changed it (#2367: with "Allow" once, background polls asked again every ~30s). A refusal or no answer is kept 10 minutes (#2408). magpie's own writes (`codexStore.write`, `keepCodexKeychain`) keep the date of what they wrote; a switch, sign-out or refresh forgets a read (`forgetCodexKeychain`) so the next one checks the date, but keeps a refusal; switching and refreshing read afresh. Beside a refusal, no answer or waiting, the saved accounts' line has Try again (`Exclusion.Retry`, `keychain-retry`, `RetryCodexKeychain`), which reads once past the refusal, and the reason says "Always Allow" lets `/usr/bin/security` read the item, so macOS stops asking each time Codex changes it. A switch or a first sign-in (`saveCodexLogin`) writes the store Codex reads, and refuses when that store couldn't be read, when config.toml doesn't parse, or when it is one magpie doesn't read; it leaves an `auth.json` beside the item to Codex. Signing the last account out (`deleteCodexLogin`) removes the item, then `auth.json`, as `codex logout`. Not tried against an item Codex itself wrote: macOS may ask whether magpie can read it, and Codex whether it can read one magpie rewrote. | [`codex_store.go`](../../internal/provider/codex_store.go), [`codex_store_test.go`](../../internal/provider/codex_store_test.go), [`codex_keychain_ask_unix_test.go`](../../internal/provider/codex_keychain_ask_unix_test.go) | | Codex's other folders | Codex keeps one ChatGPT sign-in a folder (`codex-rs/login/src/auth/storage.rs`: `$CODEX_HOME/auth.json`, or the keychain item named by the folder) and writes its sessions there (`rollout/src/lib.rs`); `--profile` only lays `$CODEX_HOME/.config.toml` over `config.toml`, the sign-in shared (`config/src/loader/mod.rs`). So a second account is Codex run with `CODEX_HOME=~/.codex-work`. `appdir.CodexHomes` finds those folders: `CodexHome` first, then folders in the home folder or beside `CodexHome` named `codex*` or `.codex*`, or one folder down in one (`~/.codex-profiles/work`), that hold `auth.json` or `sessions/`. Sessions and the usage ledger read every one (`sessions.codexFiles`, `Dirs`). `rememberLogins` saves each folder's account with `Home` set to it (`codexHomeLogins`); the one `~/.codex` is signed in to is that one's. Such an account is renewed in its folder, as Codex's own (`codexHeldIn` in `renewSaved`, as `heldByCodex` does for `~/.codex`), so the quota, the gateway and the keep-alive never spend a copy's refresh token under that folder's Codex. It isn't switched into `~/.codex` (`switchSavedLogin`, `NextLogin`'s spares): the error names the folder and the `CODEX_HOME=… codex` command. A refresh OpenAI refuses there marks the account signed out (`codexHeldRefusal`, `codexSignInRead`), so its row has Sign in again, and magpie's sign-in writes the new tokens back to that folder (`codexHeldFolder` in `addLogin`), never to `~/.codex` (`TestCodexHeldInOtherFolderSignedOutThenSignedInAgain`). Remove forgets it and sets that folder's sign-in aside in `codex-homes-removed.json` (the folder to a SHA-256 of its refresh token, `setCodexAside`), the folder's files left as they are; `codexHomeLogins` passes over the folder while it holds that sign-in, and a sign-in made there again is listed again. An unreadable record reads no other folder's account that look (charliepu on Discord: a `.codex-db-backup-…` folder no Codex runs in, refused with "codex logout"; `TestCodexHeldFolderAccountRemoved`). phantom3792 on X: only the default folder's sessions counted, and an account added from another folder read no quota (`TestCodexOtherHome*`, `TestCodexHomesIn`). Not done: Codex's thread names (`session_index.jsonl`) and a `sqlite_home` are read from `CodexHome` only (#3530). | [`codex.go`](../../internal/appdir/codex.go), [`logins.go`](../../internal/provider/logins.go), [`codex_homes_test.go`](../../internal/provider/codex_homes_test.go) | | A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. A ChatGPT account's usage read marks it too (`codexSignInRead` in `loginQuota`, charliepu on Discord: an account OpenAI signed out showed only a blank allowance): `/wham/usage` answering 401 with those words is refreshed once (`codexWindowsRenewing`), and the account is marked for the token turned away when the refreshed read is turned away the same (`codexSignInGone`), or, for the one Codex is signed in to, when its refresh is refused (its row used to say nothing, its allowance line "run codex login"; a saved one's refused refresh is `savedRefreshFailed`'s). Any other 401, a 403, a 5xx or a network error is unknown and marks nothing. Each failed read says why on the account's row (`codexUsageWords`, `codex_usage_words.go`; hmy on Discord: five ChatGPT accounts each said only "Allowance unavailable", the error being Go's bare status text or decode error, which the GUI read none of): Cloudflare's challenge page in place of an answer (a proxy or VPN address, usually), `HTTP ` with the backend's own `detail` or `error` words, chatgpt.com not reached, or a reply magpie doesn't read; `quotaError` in app.js turns each into a line of the card's language, the raw error in the row's tooltip. The words keep what was matched before: the status text that `passing` (`quota_last.go`) reads to keep the last reading over a 429 or a 5xx, and the answer itself under `Unwrap` for `codexExpired`. An error with no words of its own says "Allowance unavailable — hover for why". A ChatGPT API account (`chatgpt-api`, `chatgpt_api.go`) has no usage read: OpenAI's API tells none, only chatgpt.com/settings/usage does. `loginQuota` says so (`siwcNoUsage`, with that page as `SeeAt`) and asks nothing; it used to read the account as a Codex one, so an active one read Codex's own sign-in ("Codex is signed out; run codex login", or another account's allowance under its name) and the card said only that it couldn't be read (danzi002 on Discord). Guarded by `TestChatGPTAPIUsageSaysWhere`. Sign in again runs magpie's own sign-in for the account (`addLogin`), which replaces its tokens, in Codex's `auth.json` too when Codex is signed in to it. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, served a request (`ServedSignIn`), or its usage read going through, it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) | -| Sign-in alerts | A system notification tells of an account in use (`On` or `Active`) of a subscription switched on whose row says Sign in again (steven_4422 on Discord: before, only the row and its Signed out pill said so). The test is the Providers page's (`renderAccounts`): any `Lapsed` on a Claude, Copilot or plugin account, and on another built-in one a mark `signInGone` matches (`needsSignIn`); a plugin's usage read that says so marks the account too. A Claude account is told of three days before its sign-in ends as well, as Claude Code's own "Your login expires in N days" is: its credentials' `refreshTokenExpiresAt` (Claude Code sets it from the token reply's `refresh_token_expires_in`, else 30 days from the sign-in, and keeps it over a refresh that sends none; past it, Claude Code takes the sign-in for none), unless the access token outlasts it by more than the three days (`claudeSignInEnds`). Each is told once (`dueSignIns`): a lapse until the account is usable again, an end until it moves; the marks are kept in `signin-alerts.json` beside `providers.json`, so a restart doesn't tell again, and an account not listed keeps them `alertKeep`. An unreadable marks file tells nothing. `WatchSignIns` looks a minute after start and every two minutes after, reading magpie's own files only. It is always on. The GUI sends it under `magpie-signin-|` (`signInKind`, `signInText` in five languages), and a click opens that provider's editor (`clickView` → `providers&edit=`), where the account's Sign in again is; a Linux dismissal opens nothing. Guarded by `TestSignInAlertClaudeSignedOut`, `TestSignInAlertClaudeEnding`, `TestDueSignIns` and `TestSignInAlertOpensItsProvider`. | [`signin_alert.go`](../../internal/provider/signin_alert.go), [`quota_alert_notify.go`](../../internal/gui/quota_alert_notify.go) | +| Sign-in alerts | A system notification tells of an account in use (`On` or `Active`) of a subscription switched on whose row says Sign in again (steven_4422 on Discord: before, only the row and its Signed out pill said so). The test is the Providers page's (`renderAccounts`): any `Lapsed` on a Claude, Copilot or plugin account, and on another built-in one a mark `signInGone` matches (`needsSignIn`); a plugin's usage read that says so marks the account too. A Claude account is told of three days before its sign-in ends as well, as Claude Code's own "Your login expires in N days" is: its credentials' `refreshTokenExpiresAt` (Claude Code sets it from the token reply's `refresh_token_expires_in`, else 30 days from the sign-in, and keeps it over a refresh that sends none; past it, Claude Code takes the sign-in for none), unless the access token outlasts it by more than the three days (`claudeSignInEnds`). Each is told once (`dueSignIns`): a lapse until the account is usable again, an end until it moves; the marks are kept in `signin-alerts.json` beside `providers.json`, so a restart doesn't tell again, and an account not listed keeps them `alertKeep`. An unreadable marks file tells nothing. `WatchSignIns` looks a minute after start and every two minutes after, reading magpie's own files only. It is always on. The GUI sends it under `magpie-signin-|` (`signInKind`, `signInText` in five languages), and a click opens that provider's editor (`clickView` → `providers&edit=`), where the account's Sign in again is; a Linux dismissal opens nothing. The magpie serving the gateway tells the same alerts to request hooks' `onSignIn`, with marks of their own in `signin-hooks.json` ([gateway-request-hooks](gateway-request-hooks.md#sign-in-notification)). Guarded by `TestSignInAlertClaudeSignedOut`, `TestSignInAlertClaudeEnding`, `TestDueSignIns`, `TestSignInAlertOpensItsProvider` and `TestRevokedAccountToldToHooksOnce`. | [`signin_alert.go`](../../internal/provider/signin_alert.go), [`quota_alert_notify.go`](../../internal/gui/quota_alert_notify.go) | | A token called expired | A ChatGPT 401 whose words say the access token has expired and ask for a refresh (`SignInExpired`: `token_expired`, "Provided authentication token is expired. Please try refreshing it."; never `refresh_token_expired`, which is revoked) while the token's own `exp` is still ahead (willz on Discord, #2973: two saved Team accounts) is mended by one refresh. `codexToken` refreshes only as `exp` nears, so before this the token went out as it was until the user signed in again, and the card said only Unauthorized. The usage read (`codexWindowsRenewing`: `loginQuota`, `codexSubscriptionUsage`, and the reset spenders through `codexUserWindows`) refreshes once and reads once more, never again: a refresh refused says to sign in again (a saved account is marked lapsed, `savedRefreshFailed`; Codex's own is marked revoked, see A revoked sign-in, through `loginQuota`, while `codexSubscriptionUsage`'s card still says `codex login`), and a token refreshed for it and still called expired says so too (`errCodexStillExpired`) and is marked revoked the same. The gateway renews the account a request went with (`NoteExpiredSignIn` from `noteSignIn`, 20s at most); the request itself fails over as before, and the next goes with the new token. Each refresh is keyed on the token turned away (`codexTokenRenewing`, `renewSavedLoginFrom`), under the lock signing waits on: a sign-in holding another token by then, renewed by Codex or another reply, is used as it is, so two replies for one token spend one rotation. Codex's own sign-in is read from its store afresh for it and written back through `codexStore.write` (temp and rename), a saved one's through `writeLogins`. Not tried against the real backend. | [`codex_expired.go`](../../internal/provider/codex_expired.go), [`account.go`](../../internal/provider/account.go), [`logins_on.go`](../../internal/provider/logins_on.go) | | Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. While Claude Code is signed out, a saved Claude account stands in for its own (`claudeStandIn`); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (`claudeListed`), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still `Held` is never listed that way, since the sign-in it may have left on disk would be served. An account whose every login in use has lapsed is `Provider.SignedOut`: `magpie providers` and the TUI say " is signed out", as the app's row does. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go), [`claude_dirs.go`](../../internal/provider/claude_dirs.go) | | Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). ChatGPT also signs in by device code, as `codex login --device-auth` does (`CodexDeviceSite`, `startCodexDeviceSignIn` in `codex_device_signin.go`): magpie asks `auth.openai.com/api/accounts/deviceauth/usercode` for a code, the box shows it with ChatGPT's device page, and magpie polls `deviceauth/token` (403 or 404 is not entered yet, up to 15 minutes), then trades the code at the token endpoint with the verifier it got and the `/deviceauth/callback` redirect. Nothing listens on this machine. The window starts this way when `magpie web` is opened from another computer (`remotePage` in `app.js`: a host other than localhost or loopback; curtinp118 on Discord, magpie on a VPS), and the box offers the other way as a link either way; a device code ChatGPT turns away (404) fails with a link to the browser's way. A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. The window or `magpie web` opens the sign-in page in the default browser (`openSignIn` in `internal/gui/api.go`; `openSignInPage` in `app.js` for a web tab), and the waiting box always shows the link with Copy link. With Settings › Privacy › Sign-in pages off (`SignInLinkOnly`, max2020 on Discord, who signs in from a separate fingerprint browser), magpie opens nothing: the reply carries `linkOnly`, the box says the page wasn't opened, with a Settings › link to the row, and offers Open, and `magpie accounts add` and a plugin's browser login from the command line (`pluginLogin`) print the link without opening it. A callback on this machine still comes back from another browser on it, and the pasted address covers one that can't reach it. A plugin whose own CLI opens the page (`opened`, Grok Build's device sign-in on macOS and Windows) still opens it. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`codex_device_signin.go`](../../internal/provider/codex_device_signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) | diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 3bde346cc..40b6b4696 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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) diff --git a/internal/gateway/signin_hooks.go b/internal/gateway/signin_hooks.go new file mode 100644 index 000000000..7405393bf --- /dev/null +++ b/internal/gateway/signin_hooks.go @@ -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 diff --git a/internal/gateway/signin_hooks_test.go b/internal/gateway/signin_hooks_test.go new file mode 100644 index 000000000..c2290f18e --- /dev/null +++ b/internal/gateway/signin_hooks_test.go @@ -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) + } + } +} diff --git a/internal/plugin/gateway.go b/internal/plugin/gateway.go index 4bdc0826e..d76020a35 100644 --- a/internal/plugin/gateway.go +++ b/internal/plugin/gateway.go @@ -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) + }() +} diff --git a/internal/plugin/gateway_signin_test.go b/internal/plugin/gateway_signin_test.go new file mode 100644 index 000000000..b4c9c0b47 --- /dev/null +++ b/internal/plugin/gateway_signin_test.go @@ -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) + } +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 5530e9ab2..6e1fe51be 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -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 } diff --git a/internal/provider/signin_alert.go b/internal/provider/signin_alert.go index c92602d91..d8d41961e 100644 --- a/internal/provider/signin_alert.go +++ b/internal/provider/signin_alert.go @@ -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()) +} diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.html index b74842133..480fc7b67 100644 --- a/site/public/docs/ja/plugins.html +++ b/site/public/docs/ja/plugins.html @@ -686,6 +686,7 @@ m plugin logout acme

非同期ゲートウェイリクエストフック

プラグインはエージェントのリクエストをルーティングする前に I/O を待てます。package.json に "magpie": { "hooks": "./hooks.js" } を宣言するか、*.hooks.js / .mjs / .ts / .mts を追加し(Bun は TypeScript をビルドなしで実行します)、名前付きの非同期 onRequest(body, ctx) をエクスポートします。専用パッケージに OpenCode main/exports は不要です。

任意の非同期 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 はホスト権限で動くので信頼できるコードを使ってください。

magpie plugin add ./my-plugin で追加し、magpie plugin options my-plugin '{"serverUrl":"http://127.0.0.1:8000"}' で設定します。on/off と設定変更は再読み込みします。ソースだけの変更は設定の再読み込みが必要です。内部のタイトルや分類リクエストは対象外です。

diff --git a/site/public/docs/plugins.html b/site/public/docs/plugins.html index 7ce5e905e..80ddb4840 100644 --- a/site/public/docs/plugins.html +++ b/site/public/docs/plugins.html @@ -686,6 +686,7 @@ m plugin logout acme

Async gateway request hooks

A plugin can await I/O before an agent request is routed, for example to recall project context. Declare "magpie": { "hooks": "./hooks.js" } in package.json, or add a *.hooks.js / .mjs / .ts / .mts file (Bun runs TypeScript without a build step). Export a named async onRequest(body, ctx). A gateway-only package needs no OpenCode main/exports.

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.

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.

diff --git a/site/public/docs/zh/plugins.html b/site/public/docs/zh/plugins.html index 8108f5a3b..f1e876668 100644 --- a/site/public/docs/zh/plugins.html +++ b/site/public/docs/zh/plugins.html @@ -686,6 +686,7 @@ m plugin logout acme

异步网关请求钩子

插件可以在 Agent 请求路由前等待外部 I/O,例如召回项目上下文。在 package.json 声明 "magpie": { "hooks": "./hooks.js" },或者添加 *.hooks.js / .mjs / .ts / .mts 文件(Bun 直接运行 TypeScript,无需构建)。导出具名异步 onRequest(body, ctx)。纯网关插件不需要 OpenCode 的 main/exports。

可选的异步 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 插件具有宿主权限,只安装可信代码。

用 magpie plugin add ./my-plugin 安装,magpie plugin options my-plugin '{"serverUrl":"http://127.0.0.1:8000"}' 设置选项。on/off 和选项变更触发宿主重载;仅修改源码需主动触发配置重载。内部标题和分类请求跳过此钩子。