diff --git a/README.md b/README.md index dc636ce..c3549dc 100644 --- a/README.md +++ b/README.md @@ -211,7 +211,7 @@ Like middleware, these run on the requests agents send, but in magpie's Bun host | [respire-memory](packages/respire-memory) | [Respire](https://github.com/risense-ai/respire-magpie): per-turn recall and complete policy reads, automatic process diaries, and grounded experience archival with readback; storage runs after reply completion | | [OpenViking](https://github.com/volcengine/OpenViking/tree/main/examples/magpie-memory-plugin) | OpenViking context recall and opt-in completed-conversation capture using existing OpenViking configuration; published as `@openviking/magpie-plugin` and maintained in the OpenViking repository | | [@vshulcz/magpie-deja](https://github.com/vshulcz/deja-vu/tree/main/extensions/magpie) | [deja-vu](https://github.com/vshulcz/deja-vu) local cross-agent session memory: recalls project-scoped (`ctx.cwd`) history from the transcripts Claude Code, Codex, Hermes, Gemini CLI, OpenCode, Cursor and DSH write on disk, scrubs secret patterns, and attaches the recalled excerpt to the request sent to your model provider; when recalled history helped, the model is asked to end its reply with a one-line `déjà vu: … — reusing it.` note | -| [notify](packages/notify) | A push to ntfy, Bark, Gotify, Server酱, Feishu, DingTalk, WeCom, Telegram or a webhook when an agent's turn is done or fails, after it ran `minMinutes` or longer | +| [notify](packages/notify) | A push to ntfy, Bark, Gotify, Server酱, Feishu, DingTalk, WeCom, Telegram or a webhook when an agent's turn is done or fails, after it ran `minMinutes` or longer, and when a subscription account needs signing in again | Use the same plugin management commands as middleware: diff --git a/packages/notify/README.md b/packages/notify/README.md index 6a0b6c9..710f3f3 100644 --- a/packages/notify/README.md +++ b/packages/notify/README.md @@ -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 diff --git a/packages/notify/channels.mjs b/packages/notify/channels.mjs index 8ace982..35988a4 100644 --- a/packages/notify/channels.mjs +++ b/packages/notify/channels.mjs @@ -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 diff --git a/packages/notify/notify.hooks.mjs b/packages/notify/notify.hooks.mjs index 163621a..1ba90a6 100644 --- a/packages/notify/notify.hooks.mjs +++ b/packages/notify/notify.hooks.mjs @@ -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)) diff --git a/packages/notify/notify.test.mjs b/packages/notify/notify.test.mjs index 2cfd8ee..239bdda 100644 --- a/packages/notify/notify.test.mjs +++ b/packages/notify/notify.test.mjs @@ -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" }, + }) +}) diff --git a/packages/notify/package.json b/packages/notify/package.json index 90a7171..23769b8 100644 --- a/packages/notify/package.json +++ b/packages/notify/package.json @@ -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" } diff --git a/registry.json b/registry.json index 02ce7d5..b964a6a 100644 --- a/registry.json +++ b/registry.json @@ -152,7 +152,7 @@ {"package": "@magpie-community/agent-kimi-desktop", "name": "Kimi", "kind": "agent", "community": true, "summary": {"en": "Kimi desktop Work with Magpie models: configure primary and secondary models on its embedded page, select native subagent roles, and disconnect to restore the original service. Not Kimi Code CLI.", "zh": "普通 Kimi 桌面版 Work 使用 Magpie 模型:在内嵌页面配置主、副模型,为原生子代理选择角色,断开时恢复原服务。不是 Kimi Code CLI。"}}, {"package": "@magpie-community/agent-minimax-design", "name": "MiniMax Design", "kind": "agent", "community": true, "icon": "https://design.minimax.io/favicon.ico", "summary": {"en": "MiniMax Design (the local multimodal creation studio) on magpie's Agents page: one switch points Design's custom text model at magpie's gateway, and Design's model menu follows magpie's model list automatically. Quit Design before switching; Windows only (see COMPATIBILITY.md).", "zh": "把 MiniMax Design(本地多模态创作工作室)加到 magpie 的 Agent 页:一个开关把 Design 的自定义文本模型指到 magpie 网关,Design 的模型菜单随 magpie 的模型列表自动同步。切换前先退出 Design;仅支持 Windows,详见 COMPATIBILITY.md。"}}, { "package": "@magpie-community/gateway-notify", "name": "Notify", "kind": "middleware", "community": true, - "summary": { "en": "A push when an agent's turn is done or fails, after it ran long enough to be worth one: ntfy, Bark, Gotify, Server酱, Feishu, DingTalk, WeCom, Telegram or your own webhook. Agent, project, model and time only by default; the reply's text is opt-in.", "zh": "agent 一轮任务跑完或失败时推送提醒(只提醒跑够设定时长的任务):支持 ntfy、Bark、Gotify、Server酱、飞书、钉钉、企业微信、Telegram 和自定义 webhook。默认只发 agent、项目、模型和用时,回复正文需手动开启。" } }, + "summary": { "en": "A push when an agent's turn is done or fails, after it ran long enough to be worth one: ntfy, Bark, Gotify, Server酱, Feishu, DingTalk, WeCom, Telegram or your own webhook. Also pushes when a subscription account is signed out and needs signing in again. Agent, project, model and time only by default; the reply's text is opt-in.", "zh": "agent 一轮任务跑完或失败时推送提醒(只提醒跑够设定时长的任务):支持 ntfy、Bark、Gotify、Server酱、飞书、钉钉、企业微信、Telegram 和自定义 webhook。订阅账号掉线需要重新登录时也会推送。默认只发 agent、项目、模型和用时,回复正文需手动开启。" } }, { "package": "@magpie-community/hooks-mail-watch", "name": "Mail Watch", "kind": "middleware", "community": true, "summary": { "en": "Email alerts when a provider call fails or a quota window runs out: your own SMTP account, your own words in the mail, and your own list of what to watch, with cooldowns and an hourly cap so a bad hour stays bounded — plus an optional periodic usage digest.", "zh": "供应商调用失败或额度窗口用尽时发邮件提醒:用你自己的 SMTP 账号、自己的邮件文案、自己勾选的监控事项;同类事件冷却合并,另有每小时上限,糟糕的一小时不会失控;另可开启定期用量摘要。" } }, { "package": "@magpie-community/opencode-cloudflare-workers-ai-auth", "name": "Cloudflare Workers AI", "providers": ["cloudflare-workers-ai"], "community": true,