From ea9201df1f612539df7101a5718909e5223dcb85 Mon Sep 17 00:00:00 2001 From: mola <2249464964@qq.com> Date: Thu, 29 Oct 2026 13:40:31 +0800 Subject: [PATCH] mail-watch 0.1.0: mail session ends, failed turns and refusals through your own SMTP (#457) mail-watch 0.1.0: a hooks plugin that mails a rendered event (per event or as a digest) when a session ends, a turn fails, or a request is refused, through the user's own SMTP server. The digest's due time is kept in the state file (digestAt/digestHours), so a restart neither resets nor fires it early; the timer step is capped at 2^31-1 ms and an early wake re-arms for the rest instead of sending. Run at the reviewed head 8415dd9eb (sandbox HOME): - mote: packages/mail-watch `bun test` 44 pass, 0 fail, three times; whole repo `bun test` 2982 pass, 8 skip, 0 fail; `bun scripts/check.mjs` exit 0; e2e.smoke.mjs against a local SMTP sink: onRequest returns undefined, onResponse returns without awaiting the mail, the mail arrives with the rendered event and subject. - Linux (WSL2 Ubuntu 24.04): packages/mail-watch `bun test` 44 pass, 0 fail. - Broken by hand, each red: no step cap (2 red: monthly digest, early wake), no due-time-ahead check (early wake), no persisted due time (restart test), no prune, raw guard, no shrink (1 red each). Making the persist write unconditional stayed green, as expected (a cost fix only). - CI at this head: test and on-npm green. Not tried: a real SMTP provider (Gmail, Fastmail); the smoke test uses a local sink. --- packages/mail-watch/README.md | 90 +++ packages/mail-watch/digest.js | 181 +++++ packages/mail-watch/e2e.smoke.mjs | 78 +++ packages/mail-watch/icon.svg | 11 + packages/mail-watch/mail-watch.hooks.js | 330 ++++++++++ packages/mail-watch/mail-watch.test.mjs | 841 ++++++++++++++++++++++++ packages/mail-watch/package.json | 63 ++ packages/mail-watch/paths.js | 59 ++ packages/mail-watch/smtp.js | 232 +++++++ packages/mail-watch/template.js | 154 +++++ packages/mail-watch/watch.js | 273 ++++++++ registry.json | 2 + scripts/check.mjs | 7 +- 13 files changed, 2318 insertions(+), 3 deletions(-) create mode 100644 packages/mail-watch/README.md create mode 100644 packages/mail-watch/digest.js create mode 100644 packages/mail-watch/e2e.smoke.mjs create mode 100644 packages/mail-watch/icon.svg create mode 100644 packages/mail-watch/mail-watch.hooks.js create mode 100644 packages/mail-watch/mail-watch.test.mjs create mode 100644 packages/mail-watch/package.json create mode 100644 packages/mail-watch/paths.js create mode 100644 packages/mail-watch/smtp.js create mode 100644 packages/mail-watch/template.js create mode 100644 packages/mail-watch/watch.js diff --git a/packages/mail-watch/README.md b/packages/mail-watch/README.md new file mode 100644 index 0000000..544ae0f --- /dev/null +++ b/packages/mail-watch/README.md @@ -0,0 +1,90 @@ +# @magpie-community/hooks-mail-watch + +Email alerts from [magpie](https://usemagpie.ai)'s gateway: a provider error the user should know about, a subscription quota close to or past its line — sent as plain mail through your own SMTP account, with your own words in it. + +Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @magpie-community/hooks-mail-watch`. It has no page and no tab; it watches from beside the gateway. + +## What it watches + +Two signals, both from files magpie already keeps, read after an exchange finishes: + +- **Provider errors** — a model call that ended in a 4xx/5xx (`usage.jsonl`'s own row for the call: status, the vendor's error type and words, provider, model, agent). A try the gateway handed on to another provider is skipped: the request was answered on a later try, so it was no failure of the request. +- **Quota windows** — a subscription account's allowance windows (`quotas.json`), each one a percentage used: exhausted at 100%, or over the low line you set. + +## Options + +Set them in magpie's plugin options for this package. All of it is yours: the mailbox, the words, and what to watch. + +```jsonc +{ + "smtp": { + "preset": "gmail", // or host/port/secure by hand; a preset fills all three + "host": "smtp.example.com", // a hand-set host wins over the preset + "port": 465, // default: 465 with TLS, 587 without + "secure": true, // default true: TLS from the first byte; false = plain relay + "user": "me@example.com", // omit on a plain relay that wants no sign-in + "pass": "the app password", + "from": "magpie@example.com" // default: user + }, + "to": ["me@example.com"], // recipients; a comma string works too + "watch": { + "errors": true, // provider call failures + "quotaExhausted": true, // a window at 100% + "quotaLow": false, // a window over quotaLowPct (but under 100) + "quotaLowPct": 90, + "providers": [] // empty: every provider; else only these + }, + "cooldownMinutes": { "error": 10, "quota": 240 }, // one mail per key per window + "maxMailsPerHour": 20, // the whole hour's budget, on top of the per-key cooldowns + "report": { "hours": 6 }, // opt-in only: a periodic usage digest; unset means none + "template": { + "subject": "[magpie] {{kind}} · {{provider}}{{window}}", + "body": "What: {{kind}}\nProvider: {{provider}}{{account}}\n{{modelLine}}{{windowLine}}When: {{time}}\n\n{{detail}}" + } +} +``` + +A note on `secure`: it defaults to `true` — TLS from the first byte, the usual submission port (465), which every major mailhost offers. A plain relay must say so explicitly (`"secure": false`): a localhost or LAN mailhost that wants no sign-in. A user/password on a plain wire is refused, because AUTH PLAIN is the password in base64 and a plaintext port would broadcast it. STARTTLS (an upgrade offered on a plain port, port 587's habit) is not supported: the runtime's TLS upgrade dies mid-session on some platforms, so rather than a send that breaks at random, use your mailhost's 465 port instead. TLS is verified against your system's certificate store; `smtp.insecure: true` turns that off for a mailhost with a self-signed certificate you know. + +Presets name the mailhosts people actually forward mail through, so the options can just name one and add an address plus an app password: `qq` (smtp.qq.com), `163` (smtp.163.com), `126` (smtp.126.com), `gmail` (smtp.gmail.com), `zoho` (smtp.zoho.com), `yahoo` (smtp.mail.yahoo.com) — all TLS on 465. QQ/163/126 call the password an 授权码, Gmail an app password. A hand-set host or port wins over the preset; an unknown preset is ignored. + +The cooldown keys are `provider` + error type (or status), and `provider` + account + window: one mail per key per window of minutes, so a vendor's bad hour is one mail, not four hundred. The cooldown marks the send before it is attempted — a broken SMTP server collects no backlog; the next matching event tries again after the window. On top of that, `maxMailsPerHour` (default 20) caps the whole hour: a bad hour across many keys still stops at N mails. Sent-marks older than the longest cooldown in force are pruned, so the state file doesn't grow without bound. + +## Usage digest (opt-in) + +Set `report.hours` and the plugin mails a periodic summary of the window since the last digest: calls (ok/failed), credits, tokens in/out, sessions (first 8 characters of the id), agents, providers, models — the shape of your own usage, in English by default (`template.reportSubject` / `template.reportBody` / `template.reportHtml` override the words). It is off unless you set it: filling in SMTP alone never starts a digest. An empty window sends nothing. The digest honours the same `watch.providers` list as the alerts — allow-listed providers only, not the whole gateway — and its timer is armed once per window, so it fires on schedule even while exchanges keep coming (the schedule only moves when you change the hours, or turn the report off). + +Quota windows are read as magpie wrote them: the key is `provider/account` (the account lowercased), and a window whose reset time already passed is a stale last reading, not a window still full, so it is skipped rather than re-alerted every cooldown. + +## Template variables + +| Variable | Fills with | +| --- | --- | +| `{{kind}}` | `error`, `quota exhausted`, `quota low` | +| `{{provider}}`, `{{account}}` | where the call went / whose subscription | +| `{{model}}`, `{{agent}}` | the model asked, the agent that asked | +| `{{status}}`, `{{errType}}`, `{{endpoint}}` | HTTP status, the vendor's error type, the path called | +| `{{window}}`, `{{used}}`, `{{resetsAt}}` | the quota window's name, % used, when it resets | +| `{{time}}` | ISO time the alert was made | +| `{{modelLine}}`, `{{windowLine}}` | ready-made lines, empty when they'd say nothing | +| `{{detail}}` | the whole story: status + error, or window + % + reset | + +A `{{name}}` the event doesn't carry becomes empty; braces that aren't a variable (`{{not a var}}`) are left alone. The subject is UTF-8 encoded for the header (RFC 2047), so any language works. + +## How it runs + +The package is one of magpie's asynchronous gateway hooks (`magpie.hooks`): magpie's Bun host calls `onResponse` once an exchange with a model is over — successfully or not. The hook waits a moment (1.5 s, so a burst of parallel calls is one scan), reads magpie's own log and quota files, and mails what is new through a queue that sends one mail at a time. It never awaits any of this — the bounded hook returns at once, and a broken send must not touch the request or magpie's log. Nothing is imported from npm; the SMTP client is hand-rolled over Bun's own socket API (implicit TLS or a plain relay, full reply-code validation). + +State (how far the log was read, what was sent when) sits in `mail-watch-state.json` beside magpie's own config files, written atomically — one file shared with the digest's cursor, so neither walker disturbs the other's place. Its first run starts from the log as it is — a fresh install does not replay every past failure. + +Where the files are is decided in one place: a plugin installed from the registry lives under magpie's config dir, so the plugin walks up from its own folder to the folder holding magpie's files — which also finds a portable install's data folder — and otherwise reads `$XDG_CONFIG_HOME/magpie`, else `~/.config/magpie`, the same rule magpie itself follows. + +## Privacy + +What a call's error said stays between you and your own mailbox: the mail carries the provider, model, agent, status and the vendor's own error words, cut to 400 characters, and nothing else — no conversation content, no prompt text. The hook reads only magpie's own files and your SMTP server; it sends to no third party. The digest, when you turn it on, carries only counts — sessions as id prefixes, agents, providers, models, tokens and credits — and only for the providers on your list, if you set one. + +## Test + +```sh +bun test packages/mail-watch +``` diff --git a/packages/mail-watch/digest.js b/packages/mail-watch/digest.js new file mode 100644 index 0000000..f7ac779 --- /dev/null +++ b/packages/mail-watch/digest.js @@ -0,0 +1,181 @@ +// The digest: what the gateway did over a window, read from the same +// usage log the alerts scan. Sessions, agents, providers, models, tokens +// and credits — the numbers a user forwards to themselves to see the shape +// of their own usage. Nothing here identifies conversation content; a +// session appears as its id's first eight characters. +// +// readDigest(opts, now) returns the digest for the window ending now and +// saves the cursor, so the next digest covers only what came after — the +// same byte-offset walk the alerts use, one cursor for both. + +import { readFileSync, renameSync, writeFileSync, mkdirSync, openSync, readSync, closeSync, statSync } from "node:fs" +import { paths } from "./paths.js" + +// paths is the one shared rule (see paths.js): the digest used to keep +// its own copy, which read XDG_CONFIG_DIR — a variable magpie never +// reads — and honoured no portable install, so on those machines the +// digest and the alerts read different folders' logs. + +// init loads or plants the shared state file. The digest keeps its own +// cursor (digestOffset) in the same file the alerts use — two walkers, one +// file, neither disturbs the other's offset. +function loadState(p) { + try { + const raw = JSON.parse(readFileSync(p.state, "utf8")) + if (raw && typeof raw === "object") return raw + } catch {} + return {} +} + +function saveState(p, state) { + try { + mkdirSync(p.dir, { recursive: true }) + const tmp = p.state + ".tmp" + writeFileSync(tmp, JSON.stringify(state)) + renameSync(tmp, p.state) + } catch {} +} + +// baseline plants the digest cursor at the log's current end, so the +// first report covers usage from install onward, not a replay of every +// row before it. Called once by the hook on first sight of report hours. +export function baselineDigest() { + const p = paths() + const state = loadState(p) + if (Number.isFinite(Number(state.digestOffset))) return // already set + let size = 0 + try { + size = statSync(p.usage).size + } catch {} + state.digestOffset = size + saveState(p, state) +} + +// digestDue reads the persisted due time: the moment the next digest +// is owed, planted by the hook when it arms the schedule (see +// mail-watch.hooks.js). The host process may end at any time — magpie +// restarts the plugin host on every plugin install, update, toggle or +// options edit, on Bun updates, and on magpie restarts — and a due time +// kept only in memory would restart the window on every one of those. +// Null when nothing is scheduled. +export function digestDue() { + const p = paths() + const s = loadState(p) + const at = Number(s.digestAt) + if (!Number.isFinite(at) || at <= 0) return null + const hours = Number(s.digestHours) + return { at, hours: Number.isFinite(hours) && hours > 0 ? hours : 0 } +} + +// setDigestDue plants (or, with a falsy at, clears) the persisted due +// time next to digestOffset in the same state file. +export function setDigestDue(at, hours) { + const p = paths() + const s = loadState(p) + if (at) { + s.digestAt = at + s.digestHours = hours + } else { + delete s.digestAt + delete s.digestHours + } + saveState(p, s) +} +function listed(list, provider) { + if (!Array.isArray(list) || !list.length) return true + return list.includes(provider) +} + +// short is a session id as the mail shows it: first 8 chars — enough to +// tell sessions apart, not enough to mean anything to anyone else. +function short(id) { + return String(id ?? "").slice(0, 8) +} + +// empty returns the digest skeleton: per-agent, per-provider and +// per-model tables plus a sessions map. +function emptyDigest() { + return { rows: 0, ok: 0, failed: 0, credits: 0, tokensIn: 0, tokensOut: 0, agents: {}, providers: {}, models: {}, sessions: {} } +} + +export function readDigest(opts, now = Date.now()) { + const p = paths() + const state = loadState(p) + let offset = Number(state.digestOffset) + if (!Number.isFinite(offset) || offset < 0) offset = 0 + let size = 0 + try { + size = statSync(p.usage).size + } catch { + return { digest: emptyDigest(), since: now } + } + // a log shorter than remembered was cut or replaced (magpie itself + // never shortens it, but a user deleting it does): start over from + // the beginning and plant the reset, the way the alerts do — leaving + // the stale cursor would keep the digest silent until the log grew + // past the old size, and its first read would start mid-row. + if (size < offset) { + offset = 0 + const reset = loadState(p) + reset.digestOffset = 0 + saveState(p, reset) + } + const rows = [] + const buf = Buffer.alloc(Math.max(0, size - offset)) + let fh + try { + fh = openSync(p.usage, "r") + readSync(fh, buf, 0, buf.length, offset) + } catch { + return { digest: emptyDigest(), since: now } + } finally { + if (fh !== undefined) try { closeSync(fh) } catch {} + } + const cut = buf.lastIndexOf(0x0a) + if (cut < 0) return { digest: emptyDigest(), since: now } + const text = buf.subarray(0, cut + 1).toString("utf8") + const end = offset + cut + 1 + for (const line of text.split("\n")) { + if (!line) continue + let r + try { + r = JSON.parse(line) + } catch { + continue + } + // the digest honours the same provider list the alerts do: a user + // who allow-listed providers mails only those providers' usage, not + // the whole gateway's. An empty list is every provider. Filtered-out + // rows are still consumed — the window covers a span of time, and a + // row left for a later digest would double-count. + if (!listed(opts?.providers, r.provider)) continue + rows.push(r) + } + const d = emptyDigest() + const seen = {} + for (const r of rows) { + d.rows++ + if (typeof r.status === "number" && r.status >= 400) d.failed++ + else d.ok++ + d.credits += Number(r.credits) || 0 + d.tokensIn += Number(r.in) || 0 + d.tokensOut += Number(r.out) || 0 + const a = r.agent || "(none)" + d.agents[a] = (d.agents[a] || 0) + 1 + const pv = r.provider || "(none)" + d.providers[pv] = (d.providers[pv] || 0) + 1 + const m = r.model || "(none)" + d.models[m] = (d.models[m] || 0) + 1 + const sid = short(r.session) + if (sid) { + const s = (seen[sid] = seen[sid] || { rows: 0, agents: {} }) + s.rows++ + s.agents[a] = (s.agents[a] || 0) + 1 + } + } + d.sessions = seen + const next = loadState(p) + next.digestOffset = end + saveState(p, next) + return { digest: d, since: end } +} diff --git a/packages/mail-watch/e2e.smoke.mjs b/packages/mail-watch/e2e.smoke.mjs new file mode 100644 index 0000000..bdb232f --- /dev/null +++ b/packages/mail-watch/e2e.smoke.mjs @@ -0,0 +1,78 @@ +// An end-to-end smoke of the whole hook path, the way magpie would run it: +// onRequest (must return undefined), an exchange "fails", magpie writes its +// row, onResponse fires, the debounce passes, the watch scans, and a mail +// lands on a fake SMTP server. +import { mkdtempSync, writeFileSync, appendFileSync, rmSync, mkdirSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import net from "node:net" + +const dir = mkdtempSync(join(tmpdir(), "mail-watch-e2e-")) +mkdirSync(join(dir, "magpie"), { recursive: true }) +process.env.MAGPIE_CONFIG_DIR = dir + +const { onRequest, onResponse } = await import("./mail-watch.hooks.js") +const { message } = await import("./template.js") + +// the fake SMTP server, holding what it got until the test reads it +let body = "" +const server = net.createServer((s) => { + s.write("220 e2e\r\n") + let inData = false + s.on("data", (d) => { + const t = d.toString("utf8") + if (inData) { + body += t + if (t.endsWith("\r\n.\r\n")) { inData = false; s.write("250 ok\r\n") } + return + } + for (const line of t.split("\r\n").filter(Boolean)) { + if (line === "DATA") { inData = true; s.write("354 go\r\n") } + else if (line === "QUIT") { s.write("221 bye\r\n"); s.end() } + else s.write("250 ok\r\n") + } + }) +}) +const port = await new Promise((res) => server.listen(0, "127.0.0.1", () => res(server.address().port))) + +// options as the user might set them, at the SMTP server above. No +// user/pass: a plain wire with credentials is refused by design, so the +// relay shape here is the sign-in-free one. secure: false is explicit: +// the default is TLS, and a plain relay must say so. +const options = { + smtp: { host: "127.0.0.1", port, secure: false, from: "magpie@example.com" }, + to: ["me@example.com"], + watch: { errors: true, quotaExhausted: true, quotaLow: true, quotaLowPct: 90 }, + cooldownMinutes: { error: 0, quota: 0 }, + template: { subject: "[e2e] {{kind}}: {{provider}}", body: "provider={{provider}} status={{status}} err={{errType}} {{detail}}" }, +} + +// 1. onRequest changes nothing +const b = { model: "x" } +console.log("onRequest returns undefined:", onRequest(b, { options }) === undefined) + +// 2. warm-up: one exchange ends before anything has failed; the scan runs, +// init takes the empty log as its baseline, and the state file is born +await onResponse(null, { options, success: true }) +await new Promise((r) => setTimeout(r, 2200)) + +// 3. an exchange fails; magpie writes the row as it finishes +const row = { t: "2026-10-28T09:00:00Z", agent: "claude", provider: "provA", model: "m1", status: 502, err: "bad gateway", err_type: "server_error", ep: "/v1/messages" } +appendFileSync(join(dir, "magpie", "usage.jsonl"), JSON.stringify(row) + "\n") + +// 4. onResponse fires with success false, reply null — the hook schedules +// the scan and returns at once +const t0 = Date.now() +await onResponse(null, { options, success: false }) +console.log("onResponse returned fast (not awaiting the mail):", Date.now() - t0 < 1000) + +// 4. the debounce (1.5 s) passes; the queue sends. Wait long enough for both. +await new Promise((r) => setTimeout(r, 4500)) + +const ok = body.includes(Buffer.from("provider=provA status=502 err=server_error").toString("base64")) +console.log("mail arrived with the rendered event:", ok) +// an ASCII subject goes out as plain text; only a non-ASCII one is RFC 2047 +console.log("subject line present:", body.includes("Subject: [e2e] error: provA\r\n")) +server.close() +rmSync(dir, { recursive: true, force: true }) +process.exit(ok ? 0 : 1) diff --git a/packages/mail-watch/icon.svg b/packages/mail-watch/icon.svg new file mode 100644 index 0000000..6d0b4f6 --- /dev/null +++ b/packages/mail-watch/icon.svg @@ -0,0 +1,11 @@ + diff --git a/packages/mail-watch/mail-watch.hooks.js b/packages/mail-watch/mail-watch.hooks.js new file mode 100644 index 0000000..3b9304e --- /dev/null +++ b/packages/mail-watch/mail-watch.hooks.js @@ -0,0 +1,330 @@ +// mail-watch as magpie's asynchronous gateway hooks (package.json +// magpie.hooks): magpie calls onRequest as a request comes in (it must +// return undefined — this plugin changes nothing) and onResponse once an +// exchange with the model is over — the reply the client got, or null with +// success false when the request failed — and this file answers with the +// alerts the user asked for, as mail. +// +// The call is bounded (the gateway gives each hook a second by default and +// moves on), so the hooks kick the work off and return at once: the scan +// of magpie's own logs, then the mail, sent through the queue one +// connection at a time, never awaited here. Nothing they do may throw — +// a broken SMTP must not turn into noise in magpie's log, let alone +// touch the request. The scan waits a moment on purpose: magpie writes +// the call's row as (or after) the reply goes out, and a scan that ran at +// once would read a log that doesn't hold it yet. + +import { send, resolveSmtp } from "./smtp.js" +import { fill, message, renderHtml } from "./template.js" +import { fail, quotaScan, save, takeWithinCap } from "./watch.js" +import { readDigest, baselineDigest, digestDue, setDigestDue } from "./digest.js" + +// one mail at a time, however many exchanges finish together +let queue = Promise.resolve() +// the exchange that armed the scan; a second one inside the wait rearms it +let timer = null +// the digest's due time: the next moment the window closes; 0 = unscheduled +let digestAt = 0 +let digestTimer = null +// the delay the armed timer was actually started with: setTimeout clamps +// anything above 2^31-1 ms to 1 ms, so a long window is armed in capped +// steps, never in one clamped delay (see armDigest). +let digestStep = 0 +// a test-only cap on that step: 0 = no cap. It lets a test force an +// early wake (a short step on a long window) and watch the still-ahead +// re-arm, without waiting out the window. Production never sets it. +let digestStepCapForTests = 0 +// the hours the armed timer was set for, and the latest options seen: +// the fired digest mails with the newest options, not the arming one's +let digestHours = 0 +let latestDigest = null + +// PAUSE is how long the scan waits after an exchange ends, for the usage +// row to be written: short enough to stay behind the next exchange's own +// scan, long enough that magpie's append lands first. +const PAUSE = 1500 + +export function onRequest(_body, _ctx) { + // mail-watch changes nothing a request carries + return undefined +} + +export async function onResponse(_reply, ctx) { + try { + const o = ctx?.options + if (!o || typeof o !== "object") return + const to = recipients(o.to) + // the RESOLVED host: a preset-only config has no smtp.host of its + // own, and the old guard turned every such exchange away before the + // scan ever ran — presets could resolve but never send. + if (!to.length || !resolveSmtp(o.smtp ?? {}).host) return + schedule(o, to) + scheduleDigest(o, to) + } catch {} + return +} + +// schedule rearms the debounced scan: 1.5 s after the latest exchange, so +// a burst of parallel calls is scanned once, its rows all written. +function schedule(o, to) { + if (timer) clearTimeout(timer) + timer = setTimeout(() => { + timer = null + scan(o, to).catch(() => {}) + }, PAUSE) +} + +// scheduleDigest arms the periodic usage report — opt-in only: no +// report.hours, no digest, ever (the old package default mailed one every +// 6 hours to anyone who had only filled in SMTP). +// +// The timer arms ONCE and is not moved by later exchanges: the old code +// re-armed on every onResponse, so under continuous traffic the due time +// slid forward forever and the digest never fired. Only two things move +// it: the schedule itself changing (hours edited — re-arm with the new +// wait), or the report being turned off (cancel). The fired digest mails +// with the latest options seen, then arms the next window. +// +// The due time also lives on disk, next to digestOffset in the state +// file: magpie restarts the plugin host when any plugin is installed, +// updated, turned on or off, or has its options edited, when Bun +// updates, and every time magpie itself restarts or updates. A due time +// kept only in memory restarted the window on every one of those, so +// with report.hours: 24 a user who updates magpie or any plugin once a +// day never got a digest — the same outcome as the re-arm bug, by +// another route. On arming, a persisted due time for the same schedule +// that is still ahead is waited for; one already past sends now and arms +// the next window. A changed schedule re-arms with the new wait. +function scheduleDigest(o, to) { + const hours = Number(o.report?.hours) + if (!Number.isFinite(hours) || hours <= 0) { + if (digestTimer) clearTimeout(digestTimer) + digestTimer = null + digestAt = 0 + digestHours = 0 + digestStep = 0 + // a disabled report leaves no due time behind — but only write when + // one is actually due: with the report off (the default) this runs on + // every exchange, and an unconditional write is a state-file read and + // write per exchange for nothing. + if (digestDue()) setDigestDue(0, 0) + return + } + if (!digestAt) baselineDigest() // first sight: report from here on + latestDigest = { o, to } + if (digestTimer && hours === digestHours) return // already armed: leave the due time alone + if (digestTimer) clearTimeout(digestTimer) + digestHours = hours + const persisted = digestDue() + if (persisted && persisted.hours === hours && persisted.at > Date.now()) { + digestAt = persisted.at + armDigest(digestAt - Date.now(), { o, to }) + return + } + if (persisted && persisted.at <= Date.now()) { + // the host died before the due time: the window is owed now. The + // send reads from digestOffset, so a digest that already fired + // before the crash finds an empty window and mails nothing. + const cur = latestDigest + sendDigest(cur.o, cur.to).catch(() => {}) + } + const wait = hours * 3_600_000 + digestAt = Date.now() + wait + setDigestDue(digestAt, hours) + armDigest(wait, { o, to }) +} + +// armDigest starts the timer for the window: on fire it spends the +// persisted due time, mails with the latest options seen, then arms the +// next window. +// +// The step is capped: setTimeout (Bun and Node alike) clamps any delay +// above 2^31-1 ms (24.8 days) to 1 ms with a TimeoutOverflowWarning, so a +// monthly digest (report.hours: 720, 2,592,000,000 ms) used to fire at +// once, clear the due time, send, and re-arm another 1 ms timer — a +// digest on every exchange, flooding the host's log with warnings. A long +// window is armed in capped steps instead: on wake, a due time still +// ahead re-arms for the remainder; only a due time reached sends. +function armDigest(wait, cur) { + const step = Math.min(wait, 2 ** 31 - 1, digestStepCapForTests || Infinity) + digestStep = step + digestTimer = setTimeout(() => { + digestTimer = null + digestStep = 0 + if (Date.now() < digestAt) { + armDigest(digestAt - Date.now(), cur) // still ahead: wait the rest + return + } + digestAt = 0 + setDigestDue(0, 0) + const c = latestDigest ?? cur + sendDigest(c.o, c.to).catch(() => {}) + scheduleDigest(c.o, c.to) // arm the next window + }, step) +} + +// digestScheduleForTests exposes the digest timer's state, and +// resetDigestScheduleForTests clears it: production never calls either. +export function digestScheduleForTests() { + return { at: digestAt, armed: digestTimer !== null, stepMs: digestStep } +} +export function setDigestStepCapForTests(ms) { + digestStepCapForTests = ms +} +export function resetDigestScheduleForTests() { + if (digestTimer) clearTimeout(digestTimer) + digestTimer = null + digestAt = 0 + digestHours = 0 + digestStep = 0 + digestStepCapForTests = 0 + latestDigest = null +} + +// sendDigest reads the window's rows and mails the summary through the +// same queue the alerts use. The window honours the provider list, the +// way the alerts do. +async function sendDigest(o, to) { + const { digest } = readDigest({ providers: o.watch?.providers }) + if (!digest.rows) return // an empty window sends nothing + const t = o.template && typeof o.template === "object" ? o.template : {} + const vars = digestVars(digest) + const subject = fill(t.reportSubject ?? "[magpie] usage digest · {{rows}} calls · {{credits}} credits", vars) + const body = fill(t.reportBody ?? DEFAULT_REPORT_BODY, vars) + const html = t.html === false ? undefined : renderHtml(t.reportHtml, vars) + await send(o.smtp, to, message({ from: o.smtp.from ?? o.smtp.user, to, subject, body, html })) +} + +// bar is a tiny inline bar for the HTML report: a 100px track with the +// share filled. +function bar(share) { + const pct = Math.max(0, Math.min(100, Math.round(share))) + return `
` +} + +// digestVars renders the digest for the templates: sorted tables as text +// lines for the plain body, rows for the HTML layout. +function digestVars(d) { + const rows = d.rows || 1 + const table = (counts) => Object.entries(counts).sort((x, y) => y[1] - x[1]) + const agents = table(d.agents) + const providers = table(d.providers) + const models = table(d.models) + const sessions = Object.entries(d.sessions) + const line = ([k, n]) => `${k} — ${n} calls (${Math.round((n / rows) * 100)}%)` + const modelLine = (kv) => + kv.map(([k, n]) => `rich
" }) + expect(m).toContain('Content-Type: multipart/alternative; boundary="') + const boundary = /boundary="([^"]+)"/.exec(m)[1] + expect(m).toContain(`--${boundary}`) + expect(m.endsWith(`--${boundary}--\r\n\r\n`)).toBe(true) + // the plain part decodes to the text, the html part to the layout + const parts = m.split(`--${boundary}`).slice(1, -1) + const plain = Buffer.from(parts[0].split("\r\n\r\n")[1].replace(/\r\n/g, ""), "base64").toString("utf8") + const rich = Buffer.from(parts[1].split("\r\n\r\n")[1].replace(/\r\n/g, ""), "base64").toString("utf8") + expect(plain).toBe("plain") + expect(rich).toBe("rich
") + }) + + test("renderHtml escapes vars into the user's layout and fills the default card", () => { + // an error's words stay text in the user's own page + const out = renderHtml("{{err}}", { err: "", provider: "p", time: "t" }) + expect(out).toContain("<script>") + expect(out).not.toContain("