notify 0.1.3: a push when a subscription account is signed out

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

magpie v0.1.3443 calls a hooks file's onSignIn once when an account in
use must be signed in again (Codex revoked or refused, Claude, Copilot or
plugin sign-in lapsed, ...), and when a Claude sign-in ends within days.
notify pushes "⚠️ Codex account x signed out / Sign in again in magpie."
(zh with lang "zh") to the same channels. On by default (accounts: true);
one push per account and state per accountCooldownMinutes (60). Webhook
event: {kind: "signed-out"|"ending", provider, account, endsAt?}. ntfy
takes the message's tag, "warning" here. README, registry summary.

Run on mote: bun test packages/notify, 65 pass (7 new: default push, zh,
Claude ending days, accounts false, cooldown, unknown states, webhook
event); bun scripts/check.mjs ok. The new tests can't import onSignIn
from the old notify.hooks.mjs, so they fail there.
Not tried: a real push from a real revoked account.
This commit is contained in:
yetone
2026-11-10 01:45:30 +08:00
parent 7d5a68700e
commit e035ea40bb
7 changed files with 151 additions and 15 deletions
+14 -1
View File
@@ -33,6 +33,17 @@ A *turn* starts when your own words reach the model, and ends when the model ans
- One push per conversation per `cooldownSeconds`.
- Only requests magpie marks as `local` by default: an agent on this computer that uses no gateway key. Requests with a named gateway key (`gateway-key`, which may be a friend's, and includes magpie's sharing key) and requests from another device (`remote`) are left out unless `allOrigins` is on.
## Accounts to sign in again
When a subscription account in use stops working until you sign in again — a Codex sign-in revoked or refused on refresh, a Claude or Copilot sign-in lapsed, a plugin account whose sign-in expired — magpie tells its hooks once (`onSignIn`, Magpie 0.1.3443 or newer), and this plugin pushes:
```
⚠️ Codex account me@example.com signed out
Sign in again in magpie.
```
A Claude sign-in that ends within days is pushed the same way ("sign-in ends in 3 days"). It's on by default (`accounts`), to the same channels, in `lang`; the same account and state is pushed at most once per `accountCooldownMinutes`. The push carries the provider and the account's name as magpie shows it, nothing else: no token, no reason text from the vendor.
The hook changes nothing in a request, and sending never holds one up: it returns at once and posts in the background, with a 10-second limit per channel.
## Options
@@ -58,11 +69,13 @@ The hook changes nothing in a request, and sending never holds one up: it return
"allOrigins": false, // also gateway-key and remote requests
"includeText": false, // add the start of the model's last answer
"maxTextLength": 200,
"accounts": true, // push an account that needs signing in again
"accountCooldownMinutes": 60,
"lang": "en" // "en" or "zh"
}
```
Optional fields are shown with their defaults where they have one. A channel missing what it needs (a topic, a key, a webhook) is skipped; `"off": true` turns one off without deleting it. Feishu's and DingTalk's `secret` is the robot's signing secret (签名校验 / 加签), used when the robot asks for it. Gotify's `priority` falls back to the application's default when omitted; its `extras` accepts an object of `namespace::action` keys (e.g. `{"client::display": {"contentType": "text/markdown"}}`). `webhook` posts `{title, body, event}` where `event` is `{kind, agent, model, project, seconds}`.
Optional fields are shown with their defaults where they have one. A channel missing what it needs (a topic, a key, a webhook) is skipped; `"off": true` turns one off without deleting it. Feishu's and DingTalk's `secret` is the robot's signing secret (签名校验 / 加签), used when the robot asks for it. Gotify's `priority` falls back to the application's default when omitted; its `extras` accepts an object of `namespace::action` keys (e.g. `{"client::display": {"contentType": "text/markdown"}}`). `webhook` posts `{title, body, event}` where `event` is `{kind, agent, model, project, seconds}`, or for an account `{kind: "signed-out" | "ending", provider, account, endsAt}`.
## Privacy
+1 -1
View File
@@ -25,7 +25,7 @@ const trimSlash = (s) => String(s).replace(/\/+$/, "")
export const kinds = {
// ntfy (ntfy.sh or your own server): JSON publish to the server root
ntfy: (c, m) => post(trimSlash(c.server ?? "https://ntfy.sh"), {
topic: c.topic, title: m.title, message: m.body, priority: c.priority ?? 3, tags: c.tags ?? [m.ok ? "white_check_mark" : "x"],
topic: c.topic, title: m.title, message: m.body, priority: c.priority ?? 3, tags: c.tags ?? [m.tag ?? (m.ok ? "white_check_mark" : "x")],
}, c.token ? { authorization: `Bearer ${c.token}` } : {}),
// Bark (iOS): api.day.app or your own bark-server
+61 -7
View File
@@ -35,6 +35,8 @@ const turns = new Map()
const latest = new Map()
// last notification by conversation, for the cooldown
const sentAt = new Map()
// last sign-in push by provider, account and state, for its cooldown
const accountSentAt = new Map()
const MAX_TURNS = 500
const STALE = 24 * 3600 * 1000
// a conversation unseen this long no longer makes a new one nested: the agent
@@ -59,11 +61,23 @@ export const defaults = {
includeText: false,
maxTextLength: 200,
lang: "en",
accounts: true,
accountCooldownMinutes: 60,
}
const words = {
en: { done: "done", failed: "failed", took: "took", model: "Model", h: "h", min: "min", s: "s" },
zh: { done: "完成", failed: "失败", took: "用时", model: "模型", h: "小时", min: "分钟", s: "秒" },
en: {
done: "done", failed: "failed", took: "took", model: "Model", h: "h", min: "min", s: "s",
signedOut: (p, a) => `${p} account ${a} signed out`,
ending: (p, a, d) => `${p} account ${a}: sign-in ends in ${d} day${d === 1 ? "" : "s"}`,
signInAgain: "Sign in again in magpie.",
},
zh: {
done: "完成", failed: "失败", took: "用时", model: "模型", h: "小时", min: "分钟", s: "秒",
signedOut: (p, a) => `${p} 账号 ${a} 已登出`,
ending: (p, a, d) => `${p} 账号 ${a} 的登录将在 ${d} 天后失效`,
signInAgain: "请在 magpie 中重新登录。",
},
}
const names = {
@@ -79,6 +93,8 @@ export function options(raw) {
o.cooldownSeconds = Math.max(0, Number(o.cooldownSeconds) || 0)
o.failureHoldSeconds = Math.max(0, Math.min(600, Number(o.failureHoldSeconds ?? defaults.failureHoldSeconds) || 0))
o.maxTextLength = Math.max(0, Math.min(2000, Number(o.maxTextLength) || 0))
o.accounts = o.accounts !== false
o.accountCooldownMinutes = Math.max(0, Number(o.accountCooldownMinutes ?? defaults.accountCooldownMinutes) || 0)
if (!words[o.lang]) o.lang = "en"
return o
}
@@ -234,16 +250,54 @@ export function onResponse(reply, ctx) {
return
}
// onSignIn: magpie (0.1.3443 and newer) tells its hooks when a
// subscription account has to be signed in again (a revoked or refused
// sign-in), or when a Claude sign-in ends within three days. magpie says
// each once until the account works again; the cooldown keeps an account
// that flaps between the two from pushing every few minutes.
export function onSignIn(ev, ctx) {
try {
const o = options(ctx?.options)
if (!o.accounts || !o.channels.length || !ev || typeof ev !== "object") return
if (ev.state !== "signed-out" && ev.state !== "ending") return
const key = `signin:${ev.provider ?? ""}|${String(ev.account ?? "").toLowerCase()}|${ev.state}`
if (now() - (accountSentAt.get(key) ?? -Infinity) < o.accountCooldownMinutes * 60_000) return
accountSentAt.set(key, now())
for (const [k, v] of accountSentAt) if (now() - v > STALE) accountSentAt.delete(k)
dispatch(o, signInMessage(ev, o))
} catch {}
}
export function signInMessage(ev, o) {
const w = words[o.lang]
const provider = String(ev.providerName || ev.provider || "magpie")
const account = String(ev.account ?? "")
let days = 0
if (ev.state === "ending") {
const at = Date.parse(ev.endsAt ?? "")
days = Number.isFinite(at) ? Math.max(1, Math.ceil((at - now()) / 86_400_000)) : 1
}
const title = `⚠️ ${days ? w.ending(provider, account, days) : w.signedOut(provider, account)}`
return {
title, body: w.signInAgain, ok: false, tag: "warning",
event: { kind: ev.state, provider: ev.provider ?? "", account, ...(ev.endsAt ? { endsAt: ev.endsAt } : {}) },
}
}
function dispatch(o, m) {
const job = Promise.all(o.channels.map((c) => send(c, m)))
.catch(() => {})
.finally(() => pending.delete(job))
pending.add(job)
}
function notify(key, turn, t, ok, text, o) {
const ms = t - turn.start
if (ms < o.minMinutes * 60_000) return
if (now() - (sentAt.get(key) ?? -Infinity) < o.cooldownSeconds * 1000) return
sentAt.set(key, now())
const m = message(turn, ms, ok, text, o)
const job = Promise.all(o.channels.map((c) => send(c, m)))
.catch(() => {})
.finally(() => pending.delete(job))
pending.add(job)
dispatch(o, m)
}
export function duration(ms, w) {
@@ -276,7 +330,7 @@ export function message(turn, ms, ok, text, o) {
// sends in flight
export function reset(clock, timers) {
for (const k of [...turns.keys()]) forget(k)
latest.clear(); sentAt.clear(); pending = new Set()
latest.clear(); sentAt.clear(); accountSentAt.clear(); pending = new Set()
now = clock ?? (() => Date.now())
later = timers?.later ?? ((fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t })
cancel = timers?.cancel ?? ((t) => clearTimeout(t))
+69 -1
View File
@@ -4,7 +4,7 @@
import { afterEach, beforeEach, expect, test } from "bun:test"
import { createHmac } from "node:crypto"
import { readFileSync, readdirSync } from "node:fs"
import { onRequest, onResponse, reset, settled, options, duration, message } from "./notify.hooks.mjs"
import { onRequest, onResponse, onSignIn, signInMessage, reset, settled, options, duration, message } from "./notify.hooks.mjs"
import { opensTurn, ending, hasTools, firstWords, compacting, continued, notificationOnly, background, subagent } from "./turn.mjs"
import { send, usable } from "./channels.mjs"
@@ -817,3 +817,71 @@ test("Gotify's errorDescription is read on failure", async () => {
expect(r.ok).toBe(false)
expect(r.error).toBe("bad token")
})
// ---- accounts signed out (magpie's onSignIn) ----
// shannnnnks on X: in gateway mode one Codex account of several is signed
// out now and then; a push says so, to sign it in again.
const signedOut = { provider: "codex", providerName: "Codex", account: "me@example.com", state: "signed-out" }
const signInCtx = (opts = {}) => ({ options: { channels: [ntfy], ...opts }, signal: new AbortController().signal })
test("an account signed out is pushed, on by default", async () => {
onSignIn(signedOut, signInCtx())
await settled()
expect(calls.length).toBe(1)
const sent = JSON.parse(calls[0].body)
expect(sent.title).toBe("⚠️ Codex account me@example.com signed out")
expect(sent.message).toBe("Sign in again in magpie.")
expect(sent.tags).toEqual(["warning"])
})
test("a sign-in push follows lang", async () => {
onSignIn(signedOut, signInCtx({ lang: "zh" }))
onSignIn({ provider: "claude", providerName: "Claude", account: "a@b.c", state: "ending", endsAt: new Date(clock + 2.5 * 86_400_000).toISOString() }, signInCtx({ lang: "zh" }))
await settled()
expect(calls.map((c) => JSON.parse(c.body).title)).toEqual([
"⚠️ Codex 账号 me@example.com 已登出",
"⚠️ Claude 账号 a@b.c 的登录将在 3 天后失效",
])
expect(JSON.parse(calls[0].body).message).toBe("请在 magpie 中重新登录。")
})
test("a Claude sign-in ending is pushed with its days left", () => {
const m = signInMessage({ provider: "claude", providerName: "Claude", account: "a@b.c", state: "ending", endsAt: new Date(clock + 86_400_000).toISOString() }, options({}))
expect(m.title).toBe("⚠️ Claude account a@b.c: sign-in ends in 1 day")
expect(m.event).toEqual({ kind: "ending", provider: "claude", account: "a@b.c", endsAt: new Date(clock + 86_400_000).toISOString() })
})
test("accounts: false sends no sign-in push", async () => {
onSignIn(signedOut, signInCtx({ accounts: false }))
await settled()
expect(calls.length).toBe(0)
})
test("one account's sign-in push waits out its cooldown", async () => {
onSignIn(signedOut, signInCtx())
onSignIn(signedOut, signInCtx())
onSignIn({ ...signedOut, account: "other@example.com" }, signInCtx())
await settled()
expect(calls.length).toBe(2)
await wait(61 * 60_000)
onSignIn(signedOut, signInCtx())
await settled()
expect(calls.length).toBe(3)
})
test("an event that isn't a sign-in sends nothing", async () => {
onSignIn({ ...signedOut, state: "renewed" }, signInCtx())
onSignIn(null, signInCtx())
onSignIn(signedOut, { options: { channels: [] } })
await settled()
expect(calls.length).toBe(0)
})
test("a webhook gets the sign-in event", async () => {
onSignIn(signedOut, signInCtx({ channels: [{ type: "webhook", url: "https://hook.example.com/x" }] }))
await settled()
expect(JSON.parse(calls[0].body)).toEqual({
title: "⚠️ Codex account me@example.com signed out", body: "Sign in again in magpie.",
event: { kind: "signed-out", provider: "codex", account: "me@example.com" },
})
})
+4 -3
View File
@@ -1,7 +1,7 @@
{
"name": "@magpie-community/gateway-notify",
"version": "0.1.2",
"description": "A push to your phone or team chat when an agent's turn is done: ntfy, Bark, Gotify, Server酱, Feishu, DingTalk, WeCom, Telegram or a webhook",
"version": "0.1.3",
"description": "A push to your phone or team chat when an agent's turn is done or an account is signed out: ntfy, Bark, Gotify, Server酱, Feishu, DingTalk, WeCom, Telegram or a webhook",
"type": "module",
"files": ["notify.hooks.mjs", "turn.mjs", "channels.mjs", "README.md"],
"keywords": ["magpie", "magpie-gateway", "magpie-hooks", "notification", "ntfy", "bark", "gotify", "feishu", "dingtalk", "telegram"],
@@ -16,7 +16,8 @@
"errors": true,
"agents": [],
"includeText": false,
"lang": "en"
"lang": "en",
"accounts": true
}
},
"engines": { "bun": ">=1.4.2" }