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.
This commit is contained in:
@@ -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
|
||||
```
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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)
|
||||
@@ -0,0 +1,11 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<!-- mail-watch: mail alerts from the gateway. Indigo tile, white
|
||||
envelope, amber alert badge with a chunky exclamation mark.
|
||||
Flat shapes only; the badge stays readable down to 16 px. -->
|
||||
<rect x="2" y="2" width="60" height="60" rx="14" fill="#4f46e5"/>
|
||||
<rect x="12" y="20" width="40" height="26" rx="4" fill="#ffffff"/>
|
||||
<path d="M14 23 L32 37 L50 23" fill="none" stroke="#4f46e5" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<circle cx="49" cy="17" r="10" fill="#f59e0b"/>
|
||||
<rect x="47.5" y="11.5" width="3" height="7" rx="1.5" fill="#ffffff"/>
|
||||
<circle cx="49" cy="21.5" r="1.8" fill="#ffffff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 715 B |
@@ -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 `<div style="display:inline-block;vertical-align:middle;width:100px;height:8px;background:#e5e7eb;border-radius:4px;overflow:hidden;"><div style="width:${pct}%;height:100%;background:#2563eb;"></div></div>`
|
||||
}
|
||||
|
||||
// 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]) => `<tr><td style="padding:4px 0;color:#6b7280;">${k}</td><td style="padding:4px 0;">${n} calls ${bar((n / rows) * 100)} <span style="color:#9ca3af;font-size:12px;">${Math.round((n / rows) * 100)}%</span></td></tr>`).join("")
|
||||
return {
|
||||
rows: d.rows,
|
||||
ok: d.ok,
|
||||
failed: d.failed,
|
||||
credits: d.credits.toFixed(2),
|
||||
tokensIn: d.tokensIn.toLocaleString("en-US"),
|
||||
tokensOut: d.tokensOut.toLocaleString("en-US"),
|
||||
sessionCount: sessions.length,
|
||||
agentList: agents.map(line).join("\n"),
|
||||
providerList: providers.map(line).join("\n"),
|
||||
modelList: models.map(line).join("\n"),
|
||||
sessionList: sessions.slice(0, 20).map(([sid, s]) => `${sid}… (${s.rows} calls · ${Object.keys(s.agents).length} agents)`).join("\n"),
|
||||
agentRows: modelLine(agents),
|
||||
providerRows: modelLine(providers),
|
||||
modelRows: modelLine(models),
|
||||
detail: `Calls: ${d.rows} (ok ${d.ok} / failed ${d.failed})\nCredits: ${d.credits.toFixed(2)}\nTokens: ${d.tokensIn.toLocaleString("en-US")} in / ${d.tokensOut.toLocaleString("en-US")} out\nSessions: ${sessions.length}\n\nAgents:\n${agents.map(line).join("\n")}\n\nProviders:\n${providers.map(line).join("\n")}\n\nModels:\n${models.map(line).join("\n")}`,
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_REPORT_BODY = `magpie usage digest
|
||||
|
||||
Calls: {{rows}} (ok {{ok}} / failed {{failed}})
|
||||
Credits: {{credits}}
|
||||
Tokens: {{tokensIn}} in / {{tokensOut}} out
|
||||
Sessions: {{sessionCount}}
|
||||
|
||||
Agents:
|
||||
{{agentList}}
|
||||
|
||||
Providers:
|
||||
{{providerList}}
|
||||
|
||||
Models:
|
||||
{{modelList}}
|
||||
`
|
||||
|
||||
const DEFAULT_REPORT_HTML = `<!DOCTYPE html>
|
||||
<html><body style="margin:0;padding:24px;background:#f4f5f7;font-family:-apple-system,'Segoe UI','Microsoft YaHei',sans-serif;">
|
||||
<div style="max-width:560px;margin:0 auto;background:#ffffff;border-radius:8px;overflow:hidden;border:1px solid #e5e7eb;">
|
||||
<div style="padding:16px 24px;background:#1f2937;color:#ffffff;">
|
||||
<span style="display:inline-block;padding:2px 10px;border-radius:10px;font-size:12px;background:#2563eb;color:#fff;">usage digest</span>
|
||||
<span style="margin-left:8px;font-size:14px;color:#d1d5db;">magpie mail-watch</span>
|
||||
</div>
|
||||
<div style="padding:24px;">
|
||||
<table style="width:100%;border-collapse:collapse;font-size:14px;color:#111827;margin-bottom:16px;">
|
||||
<tr><td style="padding:6px 0;color:#6b7280;width:96px;">Calls</td><td style="padding:6px 0;">{{rows}} <span style="color:#9ca3af;">(ok {{ok}} / failed {{failed}})</span></td></tr>
|
||||
<tr><td style="padding:6px 0;color:#6b7280;">Credits</td><td style="padding:6px 0;">{{credits}}</td></tr>
|
||||
<tr><td style="padding:6px 0;color:#6b7280;">Tokens</td><td style="padding:6px 0;">{{tokensIn}} in / {{tokensOut}} out</td></tr>
|
||||
<tr><td style="padding:6px 0;color:#6b7280;">Sessions</td><td style="padding:6px 0;">{{sessionCount}}</td></tr>
|
||||
</table>
|
||||
<div style="font-size:13px;color:#6b7280;margin:12px 0 4px;">Agents</div>
|
||||
<table style="width:100%;border-collapse:collapse;font-size:13px;color:#111827;">{{agentRows}}</table>
|
||||
<div style="font-size:13px;color:#6b7280;margin:12px 0 4px;">Providers</div>
|
||||
<table style="width:100%;border-collapse:collapse;font-size:13px;color:#111827;">{{providerRows}}</table>
|
||||
<div style="font-size:13px;color:#6b7280;margin:12px 0 4px;">Models</div>
|
||||
<table style="width:100%;border-collapse:collapse;font-size:13px;color:#111827;">{{modelRows}}</table>
|
||||
</div>
|
||||
<div style="padding:12px 24px;background:#f9fafb;color:#9ca3af;font-size:12px;">sent by magpie mail-watch from your own gateway</div>
|
||||
</div>
|
||||
</body></html>`
|
||||
|
||||
async function scan(o, to) {
|
||||
const opts = { watch: o.watch ?? {}, cooldown: o.cooldownMinutes ?? {} }
|
||||
const events = takeWithinCap([...fail(opts).events, ...quotaScan(opts)], o.maxMailsPerHour)
|
||||
if (!events.length) {
|
||||
save()
|
||||
return
|
||||
}
|
||||
save()
|
||||
for (const ev of events) {
|
||||
queue = queue.then(() => mail(o, to, ev)).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
// mail renders one event through the user's template and hands it to the
|
||||
// SMTP client. A failure is swallowed: the next event tries again, the
|
||||
// cooldown keeps a broken server from collecting a backlog.
|
||||
async function mail(o, to, ev) {
|
||||
const vars = {
|
||||
kind: ev.kind === "error" ? "error" : ev.kind === "quotaExhausted" ? "quota exhausted" : "quota low",
|
||||
provider: ev.provider,
|
||||
account: ev.account ? ` · ${ev.account}` : "",
|
||||
model: ev.model ?? "",
|
||||
agent: ev.agent ?? "",
|
||||
status: ev.status ?? "",
|
||||
errType: ev.errType ?? "",
|
||||
endpoint: ev.endpoint ?? "",
|
||||
window: ev.window ? ` · ${ev.window}` : "",
|
||||
used: ev.used ?? "",
|
||||
resetsAt: ev.resetsAt ?? "",
|
||||
time: new Date().toISOString(),
|
||||
modelLine: ev.model ? `Model: ${ev.model}${ev.agent ? ` · ${ev.agent}` : ""}\n` : "",
|
||||
windowLine: ev.window ? `Window: ${ev.window} — ${ev.used}% used${ev.resetsAt ? `, resets ${ev.resetsAt}` : ""}\n` : "",
|
||||
detail:
|
||||
ev.kind === "error"
|
||||
? `Status: ${ev.status}${ev.errType ? ` (${ev.errType})` : ""}\n${ev.endpoint ? `Endpoint: ${ev.endpoint}\n` : ""}${ev.err || "(the vendor said nothing)"}`
|
||||
: `${ev.used}% of the window "${ev.window}" is used${ev.resetsAt ? `; it resets at ${ev.resetsAt}` : ""}.`,
|
||||
}
|
||||
const t = o.template && typeof o.template === "object" ? o.template : {}
|
||||
const subject = fill(t.subject ?? "[magpie] {{kind}} · {{provider}}{{window}}", vars)
|
||||
const body = fill(t.body ?? "What: {{kind}}\nProvider: {{provider}}{{account}}\n{{modelLine}}{{windowLine}}When: {{time}}\n\n{{detail}}", vars)
|
||||
// the HTML layout: the user's own page when they set one (filled with
|
||||
// the same vars, HTML-escaped variants for the interpolations), the
|
||||
// built-in card otherwise; false opts out of the HTML part entirely
|
||||
const html = t.html === false ? undefined : renderHtml(t.html, vars)
|
||||
await send(o.smtp, to, message({ from: o.smtp.from ?? o.smtp.user, to, subject, body, html }))
|
||||
}
|
||||
|
||||
// recipients is the option as a list of addresses: a string with commas,
|
||||
// an array, one address.
|
||||
function recipients(v) {
|
||||
const list = Array.isArray(v) ? v : typeof v === "string" ? v.split(",") : []
|
||||
return list.map((s) => String(s ?? "").trim()).filter(Boolean)
|
||||
}
|
||||
@@ -0,0 +1,841 @@
|
||||
// Tests for mail-watch: the template, the SMTP client against fake
|
||||
// servers, and the watch (usage-log scan, quota scan, cooldown). Everything
|
||||
// runs in a temp config dir (MAGPIE_CONFIG_DIR); the real folder is never
|
||||
// touched.
|
||||
|
||||
import { describe, test, expect, beforeAll, afterAll } from "bun:test"
|
||||
import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync, mkdirSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import net from "node:net"
|
||||
import { execFileSync } from "node:child_process"
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "mail-watch-test-"))
|
||||
process.env.MAGPIE_CONFIG_DIR = dir
|
||||
mkdirSync(join(dir, "magpie"), { recursive: true })
|
||||
|
||||
// the temp dir serves every describe block; it goes when the file's tests
|
||||
// are all done, not when the first block's are
|
||||
afterAll(() => {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const watch = await import("./watch.js")
|
||||
const { fill, message, renderHtml, DEFAULT_HTML } = await import("./template.js")
|
||||
const { send, resolveSmtp, PRESETS } = await import("./smtp.js")
|
||||
const { readDigest, baselineDigest } = await import("./digest.js")
|
||||
const { onResponse, digestScheduleForTests, resetDigestScheduleForTests, setDigestStepCapForTests } = await import("./mail-watch.hooks.js")
|
||||
|
||||
// ---- the fake SMTP servers ---------------------------------------------
|
||||
// Two shapes, matching what the client speaks:
|
||||
// plain (startPlain) — a net server for the relay tests; records every
|
||||
// command and the DATA body.
|
||||
// secure (startSecure) — Bun's own TLS listener (implicit TLS, the 465
|
||||
// shape). Bun's client-side STARTTLS upgrade does not survive against
|
||||
// a Node TLSSocket on every platform (handshake completes, the session
|
||||
// dies seconds later), so STARTTLS is not part of the client; the
|
||||
// secure tests run against the transport it actually uses. A
|
||||
// self-signed certificate made by openssl; a machine without it skips
|
||||
// the TLS tests.
|
||||
let server, got
|
||||
|
||||
const cert = { key: null, cert: null }
|
||||
try {
|
||||
const p = join(dir, "key.pem"), c = join(dir, "cert.pem")
|
||||
execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-keyout", p, "-out", c, "-days", "1", "-nodes", "-subj", "/CN=localhost"], { stdio: "ignore" })
|
||||
cert.key = readFileSync(p)
|
||||
cert.cert = readFileSync(c)
|
||||
} catch {}
|
||||
|
||||
// smtpBrain is the dialog both servers speak: greeting, answers per
|
||||
// command, DATA collected until ".", QUIT ends.
|
||||
function smtpBrain(answers = {}) {
|
||||
got = { commands: [], body: "", bodyInData: false }
|
||||
return {
|
||||
open(s) {
|
||||
s.write("220 fake ready\r\n")
|
||||
},
|
||||
data(s, d) {
|
||||
const text = d.toString("utf8")
|
||||
if (got.bodyInData) {
|
||||
got.body += text
|
||||
if (text.endsWith("\r\n.\r\n")) {
|
||||
got.bodyInData = false
|
||||
s.write("250 queued\r\n")
|
||||
}
|
||||
return
|
||||
}
|
||||
for (const line of text.split("\r\n").filter(Boolean)) {
|
||||
got.commands.push(line)
|
||||
if (line === "DATA") {
|
||||
got.bodyInData = true
|
||||
s.write("354 go\r\n")
|
||||
} else if (line === "QUIT") {
|
||||
s.write("221 bye\r\n")
|
||||
setTimeout(() => s.end(), 20) // let the 221 land before the FIN
|
||||
} else if (/^AUTH PLAIN/.test(line)) {
|
||||
s.write(answers.auth ?? "235 ok\r\n")
|
||||
} else if (answers.failRcpt && /^RCPT/.test(line)) {
|
||||
s.write("550 no such user\r\n")
|
||||
} else if (answers.failMailFrom && /^MAIL/.test(line)) {
|
||||
s.write("503 bad sender\r\n")
|
||||
} else {
|
||||
s.write("250 ok\r\n")
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function startPlain(answers = {}) {
|
||||
const brain = smtpBrain(answers)
|
||||
// a net socket speaks the same .write/.end the brain's Bun-style
|
||||
// handlers call, so the one dialog serves both servers
|
||||
server = net.createServer((s) => {
|
||||
brain.open(s)
|
||||
s.on("data", (d) => brain.data(s, d))
|
||||
})
|
||||
return new Promise((res) => server.listen(0, "127.0.0.1", () => res(server.address().port)))
|
||||
}
|
||||
|
||||
function startSecure(answers = {}) {
|
||||
if (!cert.cert) return Promise.resolve(null)
|
||||
const brain = smtpBrain(answers)
|
||||
server = Bun.listen({
|
||||
hostname: "127.0.0.1", port: 0,
|
||||
tls: { key: cert.key, cert: cert.cert },
|
||||
socket: brain,
|
||||
})
|
||||
return Promise.resolve(server.port)
|
||||
}
|
||||
|
||||
// ---- template ------------------------------------------------------------
|
||||
describe("template", () => {
|
||||
test("fill replaces {{name}} and leaves unknown braces", () => {
|
||||
expect(fill("a {{x}} b {{y}} c {{x}}", { x: "1" })).toBe("a 1 b c 1")
|
||||
expect(fill("keep {{not a var}}", {})).toBe("keep {{not a var}}")
|
||||
expect(fill("{{missing}}", {})).toBe("")
|
||||
})
|
||||
|
||||
test("message builds RFC 5322 headers and a base64 body", () => {
|
||||
const m = message({ from: "magpie@example.com", to: ["a@b.c"], subject: "s", body: "hi" })
|
||||
expect(m).toContain("From: magpie@example.com\r\n")
|
||||
expect(m).toContain("To: a@b.c\r\n")
|
||||
expect(m).toContain("Subject: s\r\n")
|
||||
expect(m).toContain('Content-Type: text/plain; charset="utf-8"\r\n')
|
||||
expect(m.endsWith(Buffer.from("hi").toString("base64") + "\r\n")).toBe(true)
|
||||
})
|
||||
|
||||
test("message encodes a non-ASCII subject as RFC 2047 and a display name", () => {
|
||||
const m = message({ from: "喵喵 <me@example.com>", to: ["you@example.com"], subject: "额度用尽", body: "x" })
|
||||
expect(m).toContain("Subject: =?UTF-8?B?")
|
||||
expect(m).toContain("From: =?UTF-8?B?")
|
||||
expect(m).toContain("<me@example.com>")
|
||||
})
|
||||
|
||||
test("word splits long encoded subjects at the RFC 2047 limit", () => {
|
||||
const m = message({ from: "f@x.y", to: ["t@x.y"], subject: "很长的主题".repeat(20), body: "x" })
|
||||
for (const line of m.split("\r\n")) {
|
||||
// each encoded word stays within RFC 2047 §2's 75 characters, and a
|
||||
// folded continuation line (the leading space) stays short
|
||||
if (line.startsWith("Subject:")) expect(line.length).toBeLessThanOrEqual(998)
|
||||
else if (line.startsWith(" =?")) {
|
||||
expect(line.length).toBeLessThanOrEqual(76)
|
||||
expect(line.trim().length).toBeLessThanOrEqual(75)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("every encoded word decodes on its own (whole codepoints, valid base64)", () => {
|
||||
// the failure mode this locks down: slicing the base64 at a fixed
|
||||
// width cuts quads mid-way, and each word decodes to shifted garbage
|
||||
const subjects = ["很长的主题".repeat(20), "[magpie] 额度用尽 · provider-account-with-a-long-name", "emoji 😀 mixed 中文 text"]
|
||||
for (const s of subjects) {
|
||||
const m = message({ from: "f@x.y", to: ["t@x.y"], subject: s, body: "x" })
|
||||
const line = m.split("\r\n").filter((l) => l.startsWith("Subject:") || l.startsWith(" =?")).join(" ")
|
||||
const joined = line.replace(/^Subject: /, "").replace(/ \r?\n /g, "").replace(/ /g, "")
|
||||
const out = [...joined.matchAll(/=\?UTF-8\?B\?(.+?)\?=/g)].map((w) => Buffer.from(w[1], "base64").toString("utf8")).join("")
|
||||
expect(out).toBe(s)
|
||||
}
|
||||
})
|
||||
|
||||
test("addr keeps a display name with specials quoted", () => {
|
||||
const m = message({ from: '"Acme, Inc." <a@b.c>', to: ["t@x.y"], subject: "s", body: "x" })
|
||||
expect(m).toContain('From: "Acme, Inc." <a@b.c>')
|
||||
})
|
||||
|
||||
test("addr keeps an injected name on one line, as quoted text", () => {
|
||||
// the CRLF is gone, so nothing becomes a header of its own; what the
|
||||
// attacker wrote remains inside the quoted display name
|
||||
const m = message({ from: 'bad\r\nBcc: x@y.z <a@b.c>', to: ["t@x.y"], subject: "s", body: "x" })
|
||||
expect(m.split("\r\n")[0]).toBe('From: "bad Bcc: x@y.z" <a@b.c>')
|
||||
for (const line of m.split("\r\n")) expect(line.startsWith("Bcc:")).toBe(false)
|
||||
})
|
||||
|
||||
test("message with html is multipart/alternative and both parts decode", () => {
|
||||
const m = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "plain", html: "<p>rich</p>" })
|
||||
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("<p>rich</p>")
|
||||
})
|
||||
|
||||
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("<b>{{err}}</b>", { err: "<script>alert(1)</script>", provider: "p", time: "t" })
|
||||
expect(out).toContain("<script>")
|
||||
expect(out).not.toContain("<script>")
|
||||
// the default card fills every slot and leaves no skeleton rows
|
||||
const card = renderHtml("", { kind: "error", provider: "p1", account: "", model: "m1", agent: "a1", window: "", used: "", time: "t", detail: "boom" })
|
||||
expect(card).toContain("p1")
|
||||
expect(card).toContain("m1")
|
||||
expect(card).not.toContain("{{modelRow}}")
|
||||
expect(card).not.toContain("{{windowRow}}")
|
||||
})
|
||||
|
||||
test("resolveSmtp applies a preset under explicit options", () => {
|
||||
expect(resolveSmtp({ preset: "qq", user: "u" })).toEqual({ host: "smtp.qq.com", port: 465, secure: true })
|
||||
expect(resolveSmtp({ preset: "GMAIL" })).toEqual({ host: "smtp.gmail.com", port: 465, secure: true })
|
||||
// a hand-set host and port win; an unknown preset is ignored — and
|
||||
// secure defaults to TLS, so the port follows (465, not 587)
|
||||
expect(resolveSmtp({ preset: "qq", host: "relay.lan", port: 2525 })).toEqual({ host: "relay.lan", port: 2525, secure: true })
|
||||
expect(resolveSmtp({ preset: "nope", host: "relay.lan" })).toEqual({ host: "relay.lan", port: 465, secure: true })
|
||||
expect(resolveSmtp({ host: "relay.lan", secure: false })).toEqual({ host: "relay.lan", port: 587, secure: false })
|
||||
expect(Object.keys(PRESETS)).toContain("163")
|
||||
})
|
||||
})
|
||||
|
||||
// ---- smtp ------------------------------------------------------------------
|
||||
describe("smtp", () => {
|
||||
test("send walks the handshake over implicit TLS and delivers the body", async () => {
|
||||
const port = await startSecure()
|
||||
if (!port) return // no openssl on this machine
|
||||
const body = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "hello" })
|
||||
const r = await send({ host: "127.0.0.1", port, secure: true, user: "u", pass: "p", from: "f@x.y", insecure: true }, ["t@x.y"], body)
|
||||
expect(r.startsWith("250")).toBe(true)
|
||||
expect(got.commands).toEqual([
|
||||
"EHLO magpie", "AUTH PLAIN " + Buffer.from("\0u\0p").toString("base64"),
|
||||
"MAIL FROM:<f@x.y>", "RCPT TO:<t@x.y>", "DATA", "QUIT",
|
||||
])
|
||||
expect(got.body).toContain(Buffer.from("hello").toString("base64"))
|
||||
expect(got.body.endsWith("\r\n.\r\n")).toBe(true)
|
||||
})
|
||||
|
||||
test("a plain port with a user refuses to send the password", async () => {
|
||||
const port = await startPlain()
|
||||
const body = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "x" })
|
||||
expect(send({ host: "127.0.0.1", port, secure: false, user: "u", pass: "p" }, ["t@x.y"], body)).rejects.toThrow(/cleartext/)
|
||||
})
|
||||
|
||||
test("a plain relay with no user sends fine", async () => {
|
||||
const port = await startPlain()
|
||||
const body = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "x" })
|
||||
const r = await send({ host: "127.0.0.1", port, secure: false, from: "f@x.y" }, ["t@x.y"], body)
|
||||
expect(r.startsWith("250")).toBe(true)
|
||||
expect(got.commands).toContain("MAIL FROM:<f@x.y>")
|
||||
})
|
||||
|
||||
test("an unset secure means TLS: a TLS server answers, a plain one is never tried", async () => {
|
||||
const port = await startSecure()
|
||||
if (!port) return // no openssl on this machine
|
||||
const body = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "x" })
|
||||
const r = await send({ host: "127.0.0.1", port, user: "u", pass: "p", from: "f@x.y", insecure: true }, ["t@x.y"], body)
|
||||
expect(r.startsWith("250")).toBe(true)
|
||||
})
|
||||
|
||||
test("a preset's secure is used by send, not just by resolveSmtp", async () => {
|
||||
// the preset-only failure: resolving gave TLS on 465, but send read
|
||||
// cfg.secure (unset) and connected in plain text. Host overridden
|
||||
// here to the fake server; secure still comes from the preset.
|
||||
const port = await startSecure()
|
||||
if (!port) return // no openssl on this machine
|
||||
const body = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "x" })
|
||||
const r = await send({ preset: "qq", host: "127.0.0.1", port, user: "u", pass: "p", from: "f@x.y", insecure: true }, ["t@x.y"], body)
|
||||
expect(r.startsWith("250")).toBe(true)
|
||||
})
|
||||
|
||||
test("a refused AUTH (535) fails the send", async () => {
|
||||
const port = await startSecure({ auth: "535 no\r\n" })
|
||||
if (!port) return
|
||||
const body = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "x" })
|
||||
expect(send({ host: "127.0.0.1", port, secure: true, user: "u", pass: "p", insecure: true }, ["t@x.y"], body)).rejects.toThrow("535")
|
||||
})
|
||||
|
||||
test("a refused MAIL FROM (503) fails the send", async () => {
|
||||
const port = await startPlain({ failMailFrom: true })
|
||||
const body = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "x" })
|
||||
expect(send({ host: "127.0.0.1", port, secure: false, from: "f@x.y" }, ["t@x.y"], body)).rejects.toThrow("503")
|
||||
})
|
||||
|
||||
test("send rejects on a refused recipient", async () => {
|
||||
const port = await startPlain({ failRcpt: true })
|
||||
const body = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "x" })
|
||||
expect(send({ host: "127.0.0.1", port, secure: false, from: "f@x.y" }, ["t@x.y"], body)).rejects.toThrow("550")
|
||||
})
|
||||
|
||||
test("send refuses a host that never answers", async () => {
|
||||
const body = message({ from: "f@x.y", to: ["t@x.y"], subject: "s", body: "x" })
|
||||
expect(send({ host: "127.0.0.1", port: 1, secure: false, from: "f@x.y" }, ["t@x.y"], body, { timeoutMs: 800 })).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
// ---- watch -------------------------------------------------------------------
|
||||
describe("watch", () => {
|
||||
const usage = join(dir, "magpie", "usage.jsonl")
|
||||
const state = join(dir, "magpie", "mail-watch-state.json")
|
||||
|
||||
beforeAll(() => {
|
||||
writeFileSync(usage, "")
|
||||
})
|
||||
|
||||
const opts = (over = {}) => ({ watch: { errors: true, ...over }, cooldown: { error: 0, quota: 0 } })
|
||||
|
||||
test("first init takes the log's size as its start, then sees new rows", () => {
|
||||
writeFileSync(usage, JSON.stringify({ provider: "old", status: 500 }) + "\n")
|
||||
watch.forTests(null)
|
||||
watch.init()
|
||||
const base = watch.forTests().offset
|
||||
expect(base).toBe(Buffer.byteLength(JSON.stringify({ provider: "old", status: 500 }) + "\n"))
|
||||
// a new failure arrives
|
||||
const row = { provider: "p1", status: 500, err: "boom", err_type: "server_error", model: "m", agent: "a" }
|
||||
writeFileSync(usage, readFileSync(usage, "utf8") + JSON.stringify(row) + "\n")
|
||||
const r = watch.fail(opts(), 1000)
|
||||
expect(r.events).toHaveLength(1)
|
||||
expect(r.events[0]).toMatchObject({ kind: "error", provider: "p1", status: 500, err: "boom" })
|
||||
expect(r.offset).toBe(base + Buffer.byteLength(JSON.stringify(row) + "\n"))
|
||||
})
|
||||
|
||||
test("handed_on rows and successes are skipped; a final failure fires", () => {
|
||||
const rows = [
|
||||
JSON.stringify({ provider: "p1", status: 429, handed_on: true }) + "\n",
|
||||
JSON.stringify({ provider: "p2", status: 200 }) + "\n",
|
||||
JSON.stringify({ provider: "p3", status: 401, err_type: "auth" }) + "\n",
|
||||
].join("")
|
||||
writeFileSync(usage, readFileSync(usage, "utf8") + rows)
|
||||
const r = watch.fail(opts(), 2000)
|
||||
expect(r.events).toHaveLength(1)
|
||||
expect(r.events[0].provider).toBe("p3")
|
||||
})
|
||||
|
||||
test("the user's cooldownMinutes option is honoured (not just the default)", () => {
|
||||
const row = JSON.stringify({ provider: "popt", status: 500 }) + "\n"
|
||||
const add = () => writeFileSync(usage, readFileSync(usage, "utf8") + row)
|
||||
add()
|
||||
// 1 minute: the second scan inside a minute is held, past it fires
|
||||
const cool = { watch: { errors: true }, cooldown: { error: 1 } }
|
||||
const r1 = watch.fail(cool, 60_000)
|
||||
expect(r1.events).toHaveLength(1)
|
||||
add()
|
||||
expect(watch.fail(cool, 90_000)).toEqual({ events: [], offset: watch.forTests().offset })
|
||||
add()
|
||||
expect(watch.fail(cool, 121_000).events).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("cooldown holds a repeat back and fires again after its window", () => {
|
||||
const row = JSON.stringify({ provider: "pc", status: 500 }) + "\n"
|
||||
const add = () => writeFileSync(usage, readFileSync(usage, "utf8") + row)
|
||||
add()
|
||||
const cool = { watch: { errors: true }, cooldown: { error: 10 } }
|
||||
const r1 = watch.fail(cool, 10_000)
|
||||
expect(r1.events).toHaveLength(1)
|
||||
add()
|
||||
const r2 = watch.fail(cool, 20_000)
|
||||
expect(r2.events).toHaveLength(0)
|
||||
add()
|
||||
const r3 = watch.fail(cool, 10_000 + 11 * 60_000)
|
||||
expect(r3.events).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("the provider list filters, an empty one lets all through", () => {
|
||||
const rows = [
|
||||
JSON.stringify({ provider: "a1", status: 500 }) + "\n",
|
||||
JSON.stringify({ provider: "b2", status: 500 }) + "\n",
|
||||
].join("")
|
||||
writeFileSync(usage, readFileSync(usage, "utf8") + rows)
|
||||
const r = watch.fail({ watch: { errors: true, providers: ["b2"] }, cooldown: { error: 0 } }, 5000)
|
||||
expect(r.events.map((e) => e.provider)).toEqual(["b2"])
|
||||
})
|
||||
|
||||
test("a log cut shorter than the offset restarts the scan", () => {
|
||||
writeFileSync(usage, "x")
|
||||
const r = watch.fail(opts(), 6000)
|
||||
expect(r.offset).toBe(0) // "x" holds no full line: the byte stays unread
|
||||
watch.forTests({ offset: 10 ** 9 }) // beyond any size
|
||||
const r2 = watch.fail(opts(), 6000)
|
||||
expect(r2.offset).toBe(0) // restarted; nothing scanned
|
||||
writeFileSync(usage, "")
|
||||
watch.forTests({ offset: 0 })
|
||||
})
|
||||
|
||||
test("a byte that is not UTF-8 does not push the offset past a row", () => {
|
||||
// a row with a broken byte, then a good failing row after it
|
||||
const broken = Buffer.from(JSON.stringify({ provider: "pb", status: 200 }) + "\n")
|
||||
broken[5] = 0xff
|
||||
const good = Buffer.from(JSON.stringify({ provider: "pg", status: 503, err_type: "t" }) + "\n")
|
||||
writeFileSync(usage, Buffer.concat([broken, good]))
|
||||
const r = watch.fail(opts(), 6500)
|
||||
expect(r.events).toHaveLength(1)
|
||||
expect(r.events[0].provider).toBe("pg")
|
||||
expect(r.offset).toBe(broken.length + good.length)
|
||||
writeFileSync(usage, "")
|
||||
watch.forTests({ offset: 0 })
|
||||
})
|
||||
|
||||
test("state saves and reloads", () => {
|
||||
watch.forTests({ offset: 1234, sent: { "error|p|500": 42 } })
|
||||
watch.save()
|
||||
const raw = JSON.parse(readFileSync(state, "utf8"))
|
||||
expect(raw.offset).toBe(1234)
|
||||
const st = watch.forTests()
|
||||
expect(st.sent["error|p|500"]).toBe(42)
|
||||
})
|
||||
|
||||
test("quotaScan reports exhausted and low windows, each its own cooldown", () => {
|
||||
writeFileSync(
|
||||
join(dir, "magpie", "quotas.json"),
|
||||
JSON.stringify({
|
||||
// magpie's real key shape: provider/account, account lowercased
|
||||
"prov/me@example.com": { at: "t", quota: { windows: [{ name: "5 hours", used: 100 }, { name: "7 days", used: 92 }] } },
|
||||
"other/u": { quota: { windows: [{ name: "w", used: 55 }] } },
|
||||
}),
|
||||
)
|
||||
const o = { watch: { quotaExhausted: true, quotaLow: true, quotaLowPct: 90 }, cooldown: { quota: 0 } }
|
||||
const ev = watch.quotaScan(o, 7000)
|
||||
expect(ev.map((e) => e.kind + ":" + e.window)).toEqual(["quotaExhausted:5 hours", "quotaLow:7 days"])
|
||||
expect(ev[0].account).toBe("me@example.com")
|
||||
expect(ev[0].provider).toBe("prov")
|
||||
// same again with a long cooldown: nothing — but the low and exhausted
|
||||
// keys are apart, so a window that goes 92→100 still alerts. The sent
|
||||
// map starts clean here: the scan above (cooldown 0) marked it already.
|
||||
watch.forTests({ sent: {} })
|
||||
const cool = { watch: { quotaExhausted: true, quotaLow: true, quotaLowPct: 90 }, cooldown: { quota: 240 } }
|
||||
const w1 = watch.quotaScan(cool, 7100)
|
||||
expect(w1.map((e) => e.kind)).toEqual(["quotaExhausted", "quotaLow"])
|
||||
expect(watch.quotaScan(cool, 7101)).toEqual([])
|
||||
})
|
||||
|
||||
test("quotaScan skips unlisted providers and unconfigured kinds", () => {
|
||||
const o = { watch: { quotaExhausted: true, providers: ["other"] }, cooldown: { quota: 0 } }
|
||||
const ev = watch.quotaScan(o, 8000)
|
||||
expect(ev).toEqual([]) // prov/me is not listed
|
||||
})
|
||||
|
||||
test("quotaScan matches the real key shape and skips windows whose reset passed", () => {
|
||||
// quotas.json holds last readings, not live state: a window whose
|
||||
// reset already passed is stale, not still full. A window with no
|
||||
// parseable reset keeps alerting — its state is unknown.
|
||||
const now = Date.parse("2026-10-28T12:00:00Z")
|
||||
writeFileSync(
|
||||
join(dir, "magpie", "quotas.json"),
|
||||
JSON.stringify({
|
||||
"claude/me@example.com": {
|
||||
quota: {
|
||||
windows: [
|
||||
{ name: "stale", used: 100, resetsAt: "2026-10-28T11:00:00Z" },
|
||||
{ name: "live", used: 100, resetsAt: "2026-10-28T13:00:00Z" },
|
||||
{ name: "unknown", used: 100 },
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
watch.forTests({ sent: {} })
|
||||
const o = { watch: { quotaExhausted: true, providers: ["claude"] }, cooldown: { quota: 0 } }
|
||||
const ev = watch.quotaScan(o, now)
|
||||
expect(ev.map((e) => e.window)).toEqual(["live", "unknown"])
|
||||
expect(ev.every((e) => e.provider === "claude" && e.account === "me@example.com")).toBe(true)
|
||||
})
|
||||
|
||||
test("an alert scan's save keeps the digest cursor (one state, one writer)", () => {
|
||||
// the reported failure: 1000 rows, digest baseline, one new failing
|
||||
// row, an alert scan, a save — then the digest must see exactly the
|
||||
// one new row, not the whole log again.
|
||||
const rows = Array.from({ length: 1000 }, (_, i) => JSON.stringify({ session: `s${i}`, agent: "a", provider: "p", model: "m", status: 200 }) + "\n").join("")
|
||||
writeFileSync(usage, rows)
|
||||
writeFileSync(state, JSON.stringify({}))
|
||||
baselineDigest()
|
||||
const planted = JSON.parse(readFileSync(state, "utf8")).digestOffset
|
||||
expect(planted).toBe(Buffer.byteLength(rows))
|
||||
const failRow = JSON.stringify({ provider: "p9", status: 500, err: "boom" }) + "\n"
|
||||
writeFileSync(usage, rows + failRow)
|
||||
watch.forTests({ offset: Buffer.byteLength(rows), sent: {} })
|
||||
const r = watch.fail({ watch: { errors: true }, cooldown: { error: 0 } }, 9000)
|
||||
expect(r.events).toHaveLength(1)
|
||||
expect(r.events[0].provider).toBe("p9")
|
||||
watch.save()
|
||||
const after = JSON.parse(readFileSync(state, "utf8"))
|
||||
expect(after.digestOffset).toBe(planted) // the scan did not wipe it
|
||||
const { digest } = readDigest({})
|
||||
expect(digest.rows).toBe(1)
|
||||
// clean up: later tests plant their own digest cursor
|
||||
const cleaned = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete cleaned.digestOffset
|
||||
writeFileSync(state, JSON.stringify(cleaned))
|
||||
writeFileSync(usage, "")
|
||||
watch.forTests({ offset: 0 })
|
||||
})
|
||||
|
||||
test("the hourly cap bounds a bad hour (default 20)", () => {
|
||||
const evs = [{ kind: "error" }, { kind: "error" }, { kind: "error" }]
|
||||
watch.forTests({ sent: {}, mailed: [] })
|
||||
expect(watch.takeWithinCap(evs, 2, 1000)).toHaveLength(2)
|
||||
expect(watch.takeWithinCap(evs, 2, 2000)).toHaveLength(0)
|
||||
expect(watch.takeWithinCap(evs, 2, 1000 + 3_600_000 + 1)).toHaveLength(2)
|
||||
watch.forTests({ mailed: [] })
|
||||
expect(watch.takeWithinCap(Array.from({ length: 25 }, () => ({})), undefined, 5000)).toHaveLength(20)
|
||||
})
|
||||
|
||||
test("sent-marks older than the longest cooldown are pruned", () => {
|
||||
writeFileSync(
|
||||
join(dir, "magpie", "quotas.json"),
|
||||
JSON.stringify({ "claude/me@example.com": { quota: { windows: [{ name: "5h", used: 100 }] } } }),
|
||||
)
|
||||
watch.forTests({ sent: { "quota|quotaExhausted|claude/me@example.com|5h": 1000 } })
|
||||
const o = { watch: { quotaExhausted: true }, cooldown: { quota: 240 } }
|
||||
expect(watch.quotaScan(o, 1000 + 60_000)).toEqual([]) // still held
|
||||
const ev = watch.quotaScan(o, 1000 + 241 * 60_000) // past the window: pruned, alerts again
|
||||
expect(ev).toHaveLength(1)
|
||||
expect(ev[0].provider).toBe("claude")
|
||||
// the prune itself, not just the cooldown: a mark this scan never
|
||||
// touches must be gone afterwards, or the map grows without bound.
|
||||
// (The old test passed with pruning as a no-op: the cooldown alone
|
||||
// re-fires the event, so it never proved the key was deleted.)
|
||||
watch.forTests({ sent: { "error|stale|500": 1000 } })
|
||||
watch.quotaScan(o, 1000 + 241 * 60_000)
|
||||
expect(watch.forTests().sent["error|stale|500"]).toBeUndefined()
|
||||
})
|
||||
|
||||
test("save writes atomically and leaves no temp file", () => {
|
||||
watch.save()
|
||||
expect(existsSync(state + ".tmp")).toBe(false)
|
||||
expect(existsSync(state)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
// ---- digest ----------------------------------------------------------------
|
||||
describe("digest", () => {
|
||||
const usage = join(dir, "magpie", "usage.jsonl")
|
||||
const state = join(dir, "magpie", "mail-watch-state.json")
|
||||
|
||||
test("readDigest aggregates sessions, agents, providers, models, tokens", () => {
|
||||
writeFileSync(usage, "")
|
||||
watch.forTests(null)
|
||||
watch.init()
|
||||
watch.forTests({ offset: 0, sent: {} })
|
||||
// the digest cursor starts independent of the alert offset
|
||||
baselineDigest()
|
||||
const rows = [
|
||||
{ session: "aaaaaaaa-1111", agent: "claude", provider: "p1", model: "m1", status: 200, credits: 0.5, in: 100, out: 50 },
|
||||
{ session: "aaaaaaaa-1111", agent: "claude", provider: "p1", model: "m2", status: 200, credits: 0.25, in: 80, out: 30 },
|
||||
{ session: "bbbbbbbb-2222", agent: "node", provider: "p2", model: "m1", status: 502, credits: 0, in: 10, out: 0 },
|
||||
]
|
||||
writeFileSync(usage, rows.map((r) => JSON.stringify(r)).join("\n") + "\n")
|
||||
const { digest } = readDigest({})
|
||||
expect(digest.rows).toBe(3)
|
||||
expect(digest.ok).toBe(2)
|
||||
expect(digest.failed).toBe(1)
|
||||
expect(digest.credits).toBeCloseTo(0.75)
|
||||
expect(digest.tokensIn).toBe(190)
|
||||
expect(digest.tokensOut).toBe(80)
|
||||
expect(digest.agents).toEqual({ claude: 2, node: 1 })
|
||||
expect(digest.providers).toEqual({ p1: 2, p2: 1 })
|
||||
expect(digest.models).toEqual({ m1: 2, m2: 1 })
|
||||
expect(Object.keys(digest.sessions).sort()).toEqual(["aaaaaaaa", "bbbbbbbb"])
|
||||
expect(digest.sessions["aaaaaaaa"]).toEqual({ rows: 2, agents: { claude: 2 } })
|
||||
// the cursor moved: a second read sees nothing
|
||||
expect(readDigest({}).digest.rows).toBe(0)
|
||||
})
|
||||
|
||||
test("baselineDigest plants the log's end; later rows land in the window", () => {
|
||||
writeFileSync(usage, JSON.stringify({ session: "cccccccc-3333", agent: "claude", provider: "p", model: "m", status: 200 }) + "\n")
|
||||
// state already has a digestOffset from the previous test — reset it
|
||||
const raw = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete raw.digestOffset
|
||||
writeFileSync(state, JSON.stringify(raw))
|
||||
baselineDigest()
|
||||
const st = JSON.parse(readFileSync(state, "utf8"))
|
||||
const before = st.digestOffset
|
||||
expect(before).toBeGreaterThan(0)
|
||||
// a new row arrives; the digest sees exactly it
|
||||
const row = JSON.stringify({ session: "dddddddd-4444", agent: "node", provider: "p", model: "m", status: 200 }) + "\n"
|
||||
writeFileSync(usage, readFileSync(usage, "utf8") + row)
|
||||
const { digest } = readDigest({})
|
||||
expect(digest.rows).toBe(1)
|
||||
expect(Object.keys(digest.sessions)).toEqual(["dddddddd"])
|
||||
})
|
||||
|
||||
test("a log cut shorter than the digest cursor restarts from the start", () => {
|
||||
writeFileSync(usage, "x")
|
||||
const { digest } = readDigest({})
|
||||
expect(digest.rows).toBe(0)
|
||||
// the stale cursor is reset, not kept: the next read starts at the
|
||||
// beginning of the new log instead of staying silent until the log
|
||||
// grows past the old size and then starting mid-row. (The old code
|
||||
// returned nothing and left the cursor where it was; the old test
|
||||
// locked that in.)
|
||||
expect(JSON.parse(readFileSync(state, "utf8")).digestOffset).toBe(0)
|
||||
const row = JSON.stringify({ session: "iiiiiiii-9999", agent: "claude", provider: "p", model: "m", status: 200 }) + "\n"
|
||||
writeFileSync(usage, row)
|
||||
expect(readDigest({}).digest.rows).toBe(1)
|
||||
writeFileSync(usage, "")
|
||||
})
|
||||
|
||||
test("readDigest honours the provider list, the way the alerts do", () => {
|
||||
writeFileSync(usage, "")
|
||||
const raw = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete raw.digestOffset
|
||||
writeFileSync(state, JSON.stringify(raw))
|
||||
baselineDigest()
|
||||
const rows = [
|
||||
{ session: "ffffffff-6666", agent: "claude", provider: "p1", model: "m", status: 200 },
|
||||
{ session: "ffffffff-6666", agent: "claude", provider: "p1", model: "m", status: 200 },
|
||||
{ session: "gggggggg-7777", agent: "node", provider: "p2", model: "m", status: 200 },
|
||||
]
|
||||
writeFileSync(usage, rows.map((r) => JSON.stringify(r)).join("\n") + "\n")
|
||||
const { digest } = readDigest({ providers: ["p1"] })
|
||||
expect(digest.rows).toBe(2)
|
||||
expect(digest.providers).toEqual({ p1: 2 })
|
||||
writeFileSync(usage, "")
|
||||
})
|
||||
})
|
||||
|
||||
// ---- hooks -------------------------------------------------------------------
|
||||
describe("hooks", () => {
|
||||
const usage = join(dir, "magpie", "usage.jsonl")
|
||||
const state = join(dir, "magpie", "mail-watch-state.json")
|
||||
// the watch is off in these tests: the alert scan they schedule is a
|
||||
// no-op (save only), so no stray scan disturbs another test's rows.
|
||||
const quiet = (over = {}) => ({
|
||||
smtp: { host: "127.0.0.1", port: 1, secure: false },
|
||||
to: ["t@x.y"],
|
||||
watch: { errors: false, quotaExhausted: false, quotaLow: false },
|
||||
...over,
|
||||
})
|
||||
|
||||
// waitFor polls until a state appears instead of sleeping a fixed
|
||||
// duration: fixed waits race a loaded machine (and CI) — a poll returns
|
||||
// as soon as the state is there and still passes when slow. A state
|
||||
// read that throws (a file not written yet) counts as not ready.
|
||||
const waitFor = async (ok, ms = 15000) => {
|
||||
const deadline = Date.now() + ms
|
||||
for (;;) {
|
||||
try {
|
||||
if (ok()) return true
|
||||
} catch {}
|
||||
if (Date.now() >= deadline) return false
|
||||
await Bun.sleep(50)
|
||||
}
|
||||
}
|
||||
|
||||
test("the digest timer is armed once: later exchanges don't move its due time", async () => {
|
||||
const o = quiet({ report: { hours: 6 } })
|
||||
await onResponse(null, { options: o, success: true })
|
||||
const s1 = digestScheduleForTests()
|
||||
expect(s1.armed).toBe(true)
|
||||
await Bun.sleep(20)
|
||||
await onResponse(null, { options: o, success: true })
|
||||
expect(digestScheduleForTests().at).toBe(s1.at)
|
||||
// a changed schedule re-arms; turning the report off cancels
|
||||
await onResponse(null, { options: quiet({ report: { hours: 12 } }), success: true })
|
||||
const s3 = digestScheduleForTests()
|
||||
expect(s3.armed).toBe(true)
|
||||
expect(s3.at).not.toBe(s1.at)
|
||||
await onResponse(null, { options: quiet(), success: true })
|
||||
expect(digestScheduleForTests()).toEqual({ at: 0, armed: false, stepMs: 0 })
|
||||
resetDigestScheduleForTests()
|
||||
})
|
||||
|
||||
test("the digest fires on its original schedule under continuous traffic", async () => {
|
||||
const port = await startSecure()
|
||||
if (!port) return // no openssl on this machine
|
||||
writeFileSync(usage, "")
|
||||
const raw = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete raw.digestOffset
|
||||
writeFileSync(state, JSON.stringify(raw))
|
||||
const o = {
|
||||
smtp: { host: "127.0.0.1", port, secure: true, insecure: true, from: "f@x.y" },
|
||||
to: ["t@x.y"],
|
||||
report: { hours: 300 / 3_600_000 }, // due 300 ms after the first exchange
|
||||
watch: { errors: false, quotaExhausted: false, quotaLow: false },
|
||||
}
|
||||
await onResponse(null, { options: o, success: true }) // baseline + arm
|
||||
writeFileSync(usage, JSON.stringify({ session: "eeeeeeee-5555", agent: "claude", provider: "p", model: "m", status: 200 }) + "\n")
|
||||
// exchanges keep coming; the digest must still fire on its original
|
||||
// schedule instead of sliding with the traffic (the old code re-armed
|
||||
// on each exchange and would not fire until the traffic stopped).
|
||||
// Poll for the mail rather than a fixed span: under load the old
|
||||
// fixed loop ran past the test timeout before the mail landed.
|
||||
const deadline = Date.now() + 15000
|
||||
while (got.body.length === 0 && Date.now() < deadline) {
|
||||
await onResponse(null, { options: o, success: true })
|
||||
await Bun.sleep(10)
|
||||
}
|
||||
expect(got.commands).toContain("DATA")
|
||||
expect(got.body.length).toBeGreaterThan(0)
|
||||
resetDigestScheduleForTests()
|
||||
}, 20000)
|
||||
|
||||
test("onResponse with a preset-only smtp still runs the scan", async () => {
|
||||
// the other half of the preset fix: send reading the resolved secure
|
||||
// is covered, but the onResponse gate reading the resolved host was
|
||||
// not — putting the old guard back passed all tests. A preset-only
|
||||
// config has no smtp.host of its own, so the old guard turned the
|
||||
// exchange away before the scan ever ran. The scan here has no
|
||||
// failing rows and sends nothing (no network): it proves itself by
|
||||
// the state file's offset moving to the log's end.
|
||||
const rows = JSON.stringify({ provider: "p", status: 200 }) + "\n" + JSON.stringify({ provider: "p", status: 200 }) + "\n"
|
||||
writeFileSync(usage, rows)
|
||||
writeFileSync(state, JSON.stringify({ offset: 0 }))
|
||||
watch.forTests({ offset: 0, sent: {} })
|
||||
const o = {
|
||||
smtp: { preset: "qq", user: "u", pass: "p" },
|
||||
to: ["t@x.y"],
|
||||
watch: { errors: true, quotaExhausted: false, quotaLow: false },
|
||||
}
|
||||
await onResponse(null, { options: o, success: true })
|
||||
// the scan's 1.5 s pause is a floor, not a schedule: poll for the
|
||||
// state instead of sleeping past it (a fixed 1700 ms sleep left only
|
||||
// 200 ms of room and failed under load).
|
||||
expect(await waitFor(() => JSON.parse(readFileSync(state, "utf8")).offset === Buffer.byteLength(rows))).toBe(true)
|
||||
writeFileSync(usage, "")
|
||||
watch.forTests({ offset: 0 })
|
||||
}, 20000)
|
||||
|
||||
test("the digest survives a plugin host restart: the due time lives on disk", async () => {
|
||||
const port = await startSecure()
|
||||
if (!port) return // no openssl on this machine
|
||||
writeFileSync(usage, "")
|
||||
const raw = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete raw.digestOffset
|
||||
delete raw.digestAt
|
||||
delete raw.digestHours
|
||||
writeFileSync(state, JSON.stringify(raw))
|
||||
const o = {
|
||||
smtp: { host: "127.0.0.1", port, secure: true, insecure: true, from: "f@x.y" },
|
||||
to: ["t@x.y"],
|
||||
report: { hours: 0.0005 }, // due 1.8 s after the first exchange
|
||||
watch: { errors: false, quotaExhausted: false, quotaLow: false },
|
||||
}
|
||||
await onResponse(null, { options: o, success: true }) // baseline + arm, due persisted
|
||||
// the due time the first exchange armed: every restart below must
|
||||
// keep it, not arm a fresh window. Waiting on the mail alone cannot
|
||||
// prove that — a fresh 1.8 s window fires inside the 15 s poll, so
|
||||
// the mail arrives whether or not the due time survived. The
|
||||
// assertions on `at` are what make this test fail when persistence
|
||||
// is gone (a fresh arm moves `at` to now + hours).
|
||||
const kept = digestScheduleForTests().at
|
||||
expect(kept).toBeGreaterThan(Date.now())
|
||||
writeFileSync(usage, JSON.stringify({ session: "hhhhhhhh-8888", agent: "claude", provider: "p", model: "m", status: 200 }) + "\n")
|
||||
// the host restarts every 400 ms: the old module's timer is dropped
|
||||
// (resetDigestScheduleForTests stands in for the process ending) and
|
||||
// the hooks are imported fresh. The old code started the window
|
||||
// again at now + hours on every restart and never fired; the due
|
||||
// time on disk is waited for instead.
|
||||
let mod = { onResponse, resetDigestScheduleForTests }
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await Bun.sleep(400)
|
||||
mod.resetDigestScheduleForTests()
|
||||
mod = await import(`./mail-watch.hooks.js?restart=${Date.now()}-${i}`)
|
||||
await mod.onResponse(null, { options: o, success: true })
|
||||
// still the first exchange's due time, not a fresh window
|
||||
expect(mod.digestScheduleForTests().at).toBe(kept)
|
||||
}
|
||||
// poll for the mail instead of sleeping a fixed span past the
|
||||
// original due time, so a loaded machine still passes.
|
||||
expect(await waitFor(() => got.body.length > 0)).toBe(true)
|
||||
expect(got.commands).toContain("DATA")
|
||||
// clean up: the fired digest re-armed the next window; drop it and
|
||||
// the persisted due time so later runs start clean.
|
||||
mod.resetDigestScheduleForTests()
|
||||
const cleaned = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete cleaned.digestAt
|
||||
delete cleaned.digestHours
|
||||
writeFileSync(state, JSON.stringify(cleaned))
|
||||
writeFileSync(usage, "")
|
||||
}, 20000)
|
||||
|
||||
test("an early wake re-arms for the rest instead of sending", async () => {
|
||||
// the still-ahead re-arm had no test of its own: a probe covered it,
|
||||
// but a probe is not a test — removing the re-arm passed the suite.
|
||||
// A test-only step cap forces early wakes on a long window: the
|
||||
// timer fires every 50 ms, finds the due time still ahead, and
|
||||
// re-arms instead of sending. A usage row is present, so a misfire
|
||||
// would mail and this test would see it.
|
||||
const port = await startSecure()
|
||||
if (!port) return // no openssl on this machine
|
||||
writeFileSync(usage, "")
|
||||
const raw = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete raw.digestOffset
|
||||
delete raw.digestAt
|
||||
delete raw.digestHours
|
||||
writeFileSync(state, JSON.stringify(raw))
|
||||
const o = {
|
||||
smtp: { host: "127.0.0.1", port, secure: true, insecure: true, from: "f@x.y" },
|
||||
to: ["t@x.y"],
|
||||
report: { hours: 1 },
|
||||
watch: { errors: false, quotaExhausted: false, quotaLow: false },
|
||||
}
|
||||
setDigestStepCapForTests(50)
|
||||
await onResponse(null, { options: o, success: true })
|
||||
const s = digestScheduleForTests()
|
||||
expect(s.armed).toBe(true)
|
||||
expect(s.stepMs).toBe(50) // the cap, not the 1 h window
|
||||
writeFileSync(usage, JSON.stringify({ session: "iiiiiiii-9999", agent: "claude", provider: "p", model: "m", status: 200 }) + "\n")
|
||||
try {
|
||||
// several early wakes pass; the due time never moves and no mail
|
||||
// goes out before it.
|
||||
await Bun.sleep(300)
|
||||
expect(digestScheduleForTests().at).toBe(s.at)
|
||||
expect(digestScheduleForTests().stepMs).toBe(50)
|
||||
expect(got.commands).not.toContain("DATA")
|
||||
} finally {
|
||||
// the cap is module-global: a failure above must not leak it into
|
||||
// the monthly test's step assertion.
|
||||
resetDigestScheduleForTests()
|
||||
}
|
||||
const cleaned = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete cleaned.digestAt
|
||||
delete cleaned.digestHours
|
||||
writeFileSync(state, JSON.stringify(cleaned))
|
||||
writeFileSync(usage, "")
|
||||
})
|
||||
|
||||
test("a monthly digest does not fire at once: the timer step is capped", async () => {
|
||||
const port = await startSecure()
|
||||
if (!port) return // no openssl on this machine
|
||||
writeFileSync(usage, "")
|
||||
const raw = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete raw.digestOffset
|
||||
delete raw.digestAt
|
||||
delete raw.digestHours
|
||||
writeFileSync(state, JSON.stringify(raw))
|
||||
const o = {
|
||||
smtp: { host: "127.0.0.1", port, secure: true, insecure: true, from: "f@x.y" },
|
||||
to: ["t@x.y"],
|
||||
report: { hours: 720 }, // 2,592,000,000 ms: past setTimeout's 2^31-1 ms limit
|
||||
watch: { errors: false, quotaExhausted: false, quotaLow: false },
|
||||
}
|
||||
await onResponse(null, { options: o, success: true })
|
||||
const s = digestScheduleForTests()
|
||||
expect(s.armed).toBe(true)
|
||||
// the delay actually passed to setTimeout: capped, not the 2.59e9 ms
|
||||
// the old code passed (which Bun/Node clamp to 1 ms with a warning,
|
||||
// so the digest fired at once and re-armed another 1 ms timer).
|
||||
expect(s.stepMs).toBe(2 ** 31 - 1)
|
||||
// and nothing fires promptly: give it a chance to misfire, then check.
|
||||
await Bun.sleep(300)
|
||||
expect(got.commands).not.toContain("DATA")
|
||||
resetDigestScheduleForTests()
|
||||
const cleaned = JSON.parse(readFileSync(state, "utf8"))
|
||||
delete cleaned.digestAt
|
||||
delete cleaned.digestHours
|
||||
writeFileSync(state, JSON.stringify(cleaned))
|
||||
writeFileSync(usage, "")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"name": "@magpie-community/hooks-mail-watch",
|
||||
"version": "0.1.0",
|
||||
"description": "Email alerts from the gateway: provider errors and exhausted quotas, with your own recipients, templates and watch list",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"mail-watch.hooks.js",
|
||||
"smtp.js",
|
||||
"watch.js",
|
||||
"digest.js",
|
||||
"template.js",
|
||||
"paths.js",
|
||||
"README.md",
|
||||
"icon.svg"
|
||||
],
|
||||
"keywords": [
|
||||
"magpie",
|
||||
"magpie-hooks",
|
||||
"mail",
|
||||
"smtp",
|
||||
"alerts",
|
||||
"quota",
|
||||
"errors"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/mail-watch"
|
||||
},
|
||||
"magpie": {
|
||||
"icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+CiAgPCEtLSBtYWlsLXdhdGNoOiBtYWlsIGFsZXJ0cyBmcm9tIHRoZSBnYXRld2F5LiBJbmRpZ28gdGlsZSwgd2hpdGUKICAgICAgIGVudmVsb3BlLCBhbWJlciBhbGVydCBiYWRnZSB3aXRoIGEgY2h1bmt5IGV4Y2xhbWF0aW9uIG1hcmsuCiAgICAgICBGbGF0IHNoYXBlcyBvbmx5OyB0aGUgYmFkZ2Ugc3RheXMgcmVhZGFibGUgZG93biB0byAxNiBweC4gLS0+CiAgPHJlY3QgeD0iMiIgeT0iMiIgd2lkdGg9IjYwIiBoZWlnaHQ9IjYwIiByeD0iMTQiIGZpbGw9IiM0ZjQ2ZTUiLz4KICA8cmVjdCB4PSIxMiIgeT0iMjAiIHdpZHRoPSI0MCIgaGVpZ2h0PSIyNiIgcng9IjQiIGZpbGw9IiNmZmZmZmYiLz4KICA8cGF0aCBkPSJNMTQgMjMgTDMyIDM3IEw1MCAyMyIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjNGY0NmU1IiBzdHJva2Utd2lkdGg9IjMuNSIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+CiAgPGNpcmNsZSBjeD0iNDkiIGN5PSIxNyIgcj0iMTAiIGZpbGw9IiNmNTllMGIiLz4KICA8cmVjdCB4PSI0Ny41IiB5PSIxMS41IiB3aWR0aD0iMyIgaGVpZ2h0PSI3IiByeD0iMS41IiBmaWxsPSIjZmZmZmZmIi8+CiAgPGNpcmNsZSBjeD0iNDkiIGN5PSIyMS41IiByPSIxLjgiIGZpbGw9IiNmZmZmZmYiLz4KPC9zdmc+Cg==",
|
||||
"hooks": "./mail-watch.hooks.js",
|
||||
"options": {
|
||||
"smtp": {
|
||||
"host": "smtp.example.com",
|
||||
"port": 465,
|
||||
"secure": true,
|
||||
"user": "me@example.com",
|
||||
"pass": "the app password",
|
||||
"from": "magpie@example.com"
|
||||
},
|
||||
"to": [
|
||||
"me@example.com"
|
||||
],
|
||||
"watch": {
|
||||
"errors": true,
|
||||
"quotaExhausted": true,
|
||||
"quotaLow": false,
|
||||
"quotaLowPct": 90,
|
||||
"providers": []
|
||||
},
|
||||
"cooldownMinutes": {
|
||||
"error": 10,
|
||||
"quota": 240
|
||||
},
|
||||
"template": {
|
||||
"subject": "[magpie] {{kind}} · {{provider}}{{window}}",
|
||||
"body": "What: {{kind}}\nProvider: {{provider}}{{account}}\n{{modelLine}}{{windowLine}}When: {{time}}\n\n{{detail}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// Where magpie keeps its own files, decided in exactly one place —
|
||||
// watch.js and digest.js used to each keep their own rule, and they had
|
||||
// drifted (one read XDG_CONFIG_DIR, which magpie never reads; neither
|
||||
// honoured a portable install).
|
||||
//
|
||||
// magpie's own rule (internal/appdir): a portable install — a "data"
|
||||
// folder, or a ".portable" marker, beside the magpie executable — keeps
|
||||
// everything in that data folder; an installed one keeps them in
|
||||
// $XDG_CONFIG_HOME/magpie, else ~/.config/magpie. The hook's context
|
||||
// carries no config dir, so this module finds it another way: a plugin
|
||||
// installed from the registry lives under the config dir's plugins/
|
||||
// folder, so walking up from this file to the nearest folder holding one
|
||||
// of magpie's own files (usage.jsonl, quotas.json, providers.json,
|
||||
// plugins.json) lands on the config dir — portable or installed, with
|
||||
// no need to know where the executable is. A locally developed plugin
|
||||
// (its files outside any config dir) finds no marker and falls back to
|
||||
// the installed rule, which is what a dev install reads.
|
||||
//
|
||||
// MAGPIE_CONFIG_DIR is the test override (it names the parent, the way
|
||||
// XDG_CONFIG_HOME does: the dir below it is "magpie"). Production never
|
||||
// sets it.
|
||||
|
||||
import { existsSync } from "node:fs"
|
||||
import { join, dirname, isAbsolute } from "node:path"
|
||||
import { homedir } from "node:os"
|
||||
|
||||
// MARKERS are files magpie itself writes at the root of its config dir:
|
||||
// usage.jsonl (every call's row), quotas.json (the last readings),
|
||||
// providers.json (the sign-ins' file), plugins.json (the plugin list —
|
||||
// present from the moment a registry plugin is installed, before any
|
||||
// usage exists).
|
||||
const MARKERS = ["usage.jsonl", "quotas.json", "providers.json", "plugins.json"]
|
||||
|
||||
// anchorDir walks up from this package's own folder to the config dir
|
||||
// that holds it, or null when the package lives outside one.
|
||||
function anchorDir() {
|
||||
const here = import.meta.dir ?? import.meta.dirname
|
||||
if (!here) return null
|
||||
let dir = here
|
||||
for (let i = 0; i < 32; i++) {
|
||||
if (MARKERS.some((m) => existsSync(join(dir, m)))) return dir
|
||||
const up = dirname(dir)
|
||||
if (up === dir) return null
|
||||
dir = up
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function paths() {
|
||||
const testRoot = process.env.MAGPIE_CONFIG_DIR
|
||||
if (testRoot) {
|
||||
const dir = join(testRoot, "magpie")
|
||||
return { dir, state: join(dir, "mail-watch-state.json"), usage: join(dir, "usage.jsonl"), quotas: join(dir, "quotas.json") }
|
||||
}
|
||||
const anchored = anchorDir()
|
||||
const xdg = process.env.XDG_CONFIG_HOME
|
||||
const dir = anchored ?? (xdg && isAbsolute(xdg) ? join(xdg, "magpie") : join(homedir(), ".config", "magpie"))
|
||||
return { dir, state: join(dir, "mail-watch-state.json"), usage: join(dir, "usage.jsonl"), quotas: join(dir, "quotas.json") }
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// A small SMTP client over Bun.connect, with nothing to import from npm:
|
||||
// the registry's packages ship no dependencies, and a hooks file runs where
|
||||
// Bun's own socket API is the dependable one.
|
||||
//
|
||||
// One mail per run: connect, EHLO, AUTH PLAIN when a user was given, MAIL
|
||||
// FROM, RCPT TO each recipient, one DATA, QUIT. Every reply is checked
|
||||
// against the code its command expects, so a refused auth fails the send
|
||||
// rather than stumble on. send resolves once the server has accepted the
|
||||
// mail for its queue; failures reject with the server's last word.
|
||||
//
|
||||
// Two transports:
|
||||
// secure: true — TLS from the first byte (implicit TLS, port 465): the
|
||||
// usual mailhost submission port. Verified by default; cfg.insecure
|
||||
// turns that off for a mailhost with a self-signed certificate the
|
||||
// user knows. An IP host goes without a server name (TLS wants a
|
||||
// name; an IP is the certificate's own).
|
||||
// secure: false — a plain relay on the user's own network (a localhost
|
||||
// or LAN mailhost that wants no sign-in). A user/password on a plain
|
||||
// wire is refused: AUTH PLAIN is the password in base64, and the
|
||||
// STARTTLS upgrade Bun offers dies mid-session on some platforms
|
||||
// (handshake completes, close_notify follows unprompted), so rather
|
||||
// than a send that breaks at random, credentials are not sent at all.
|
||||
// A plain relay without credentials works as it is.
|
||||
|
||||
import net from "node:net"
|
||||
|
||||
// PRESETS are the mailhosts people actually forward mail through, so the
|
||||
// options can just name one: host, port and TLS come from the preset and
|
||||
// the user adds their address and an app password (QQ/163/126 call it
|
||||
// 授权码, Gmail an app password). All of these speak TLS from the first
|
||||
// byte on 465 — the transport this client speaks.
|
||||
export const PRESETS = {
|
||||
qq: { host: "smtp.qq.com", port: 465, secure: true },
|
||||
"163": { host: "smtp.163.com", port: 465, secure: true },
|
||||
"126": { host: "smtp.126.com", port: 465, secure: true },
|
||||
gmail: { host: "smtp.gmail.com", port: 465, secure: true },
|
||||
zoho: { host: "smtp.zoho.com", port: 465, secure: true },
|
||||
yahoo: { host: "smtp.mail.yahoo.com", port: 465, secure: true },
|
||||
}
|
||||
|
||||
// resolveSmtp applies a preset under the explicit options: a host given by
|
||||
// hand wins, an unset secure/port takes the preset's, an unknown preset is
|
||||
// ignored (and a missing host then fails as before). secure defaults to
|
||||
// TLS: a mailhost that wants no TLS must say so explicitly
|
||||
// ("secure": false) — the safe direction for credentials, and the port
|
||||
// follows (465 with TLS, 587 without).
|
||||
export function resolveSmtp(cfg) {
|
||||
const preset = PRESETS[String(cfg.preset ?? "").toLowerCase()]
|
||||
const host = cfg.host ?? preset?.host
|
||||
const secure = cfg.secure ?? preset?.secure ?? true
|
||||
const port = Number(cfg.port) || preset?.port || (secure ? 465 : 587)
|
||||
return { host: host === undefined ? undefined : String(host), port, secure }
|
||||
}
|
||||
|
||||
// send is one mail. host, port, user, pass and from come from the options;
|
||||
// to is an array of addresses; body is the RFC 5322 text template.message
|
||||
// made.
|
||||
export async function send(cfg, to, body, { timeoutMs = 30000 } = {}) {
|
||||
const { host, port, secure } = resolveSmtp(cfg)
|
||||
if (!host) throw new Error(`smtp.host is required (or set smtp.preset to one of: ${Object.keys(PRESETS).join(", ")})`)
|
||||
const verify = cfg.insecure !== true
|
||||
const name = net.isIP(host) ? undefined : host
|
||||
// The connection as one object: connect makes it, and every reader below
|
||||
// reads through it. next() arms a waiter the data/error handlers fire;
|
||||
// one waiter at a time — the dialog is strictly command, reply.
|
||||
const link = { sock: null, waiter: null, openRes: null, openRej: null, pending: "" }
|
||||
// opened finishes when open() fires — or rejects at once when the socket
|
||||
// errors or closes before the handshake (a TLS attempt against a plain
|
||||
// port, a server that resets on connect), so the send fails now instead
|
||||
// of stalling to the connect timeout.
|
||||
const opened = new Promise((res, rej) => { link.openRes = res; link.openRej = rej })
|
||||
const handlers = {
|
||||
// open never answers a command; it only finishes the connect wait
|
||||
open() {
|
||||
link.openRes?.()
|
||||
link.openRes = null
|
||||
},
|
||||
data(_s, d) {
|
||||
const chunk = d.toString("utf8")
|
||||
// Bytes can land before a waiter is armed — a greeting that races the
|
||||
// client's own continuation (Bun can deliver it in the same tick that
|
||||
// fires open), or anything else between two commands. They wait in
|
||||
// pending; the next next() picks them up. Dropped, the send would
|
||||
// stall to its timeout.
|
||||
if (!link.waiter) {
|
||||
link.pending += chunk
|
||||
return
|
||||
}
|
||||
link.waiter.buf += chunk
|
||||
// a reply ends at a complete final line: "NNN<space>text\r\n", or a
|
||||
// bare "NNN\r\n" (RFC 5321 allows the parameterless form). A chunk
|
||||
// that stops mid-line is not one — more bytes are coming.
|
||||
if (endsReply(link.waiter.buf)) {
|
||||
const q = link.waiter
|
||||
link.waiter = null
|
||||
q.res(q.buf.trim())
|
||||
} else if (link.waiter.buf.length > 65536) {
|
||||
const q = link.waiter
|
||||
link.waiter = null
|
||||
q.rej(new Error("smtp reply too long"))
|
||||
}
|
||||
},
|
||||
error(_s, e) {
|
||||
link.openRej?.(e)
|
||||
link.openRej = null
|
||||
const q = link.waiter
|
||||
link.waiter = null
|
||||
if (q) q.rej(e)
|
||||
},
|
||||
end() {
|
||||
link.openRej?.(new Error("smtp server closed the connection"))
|
||||
link.openRej = null
|
||||
const q = link.waiter
|
||||
link.waiter = null
|
||||
if (q) q.rej(new Error("smtp server closed the connection"))
|
||||
},
|
||||
close() {
|
||||
link.openRej?.(new Error("smtp server closed the connection"))
|
||||
link.openRej = null
|
||||
const q = link.waiter
|
||||
link.waiter = null
|
||||
if (q) q.rej(new Error("smtp server closed the connection"))
|
||||
},
|
||||
timeout() {
|
||||
const q = link.waiter
|
||||
link.waiter = null
|
||||
if (q) q.rej(new Error("smtp reply timed out"))
|
||||
},
|
||||
}
|
||||
try {
|
||||
link.sock = await Bun.connect({
|
||||
hostname: host,
|
||||
port,
|
||||
// the RESOLVED secure: send used to read cfg.secure here, so a
|
||||
// preset-only config (secure true from the preset, unset in cfg)
|
||||
// connected in plain text to a TLS port and timed out — the
|
||||
// preset never worked, though resolving it did.
|
||||
tls: secure ? { rejectUnauthorized: verify, serverName: name } : undefined,
|
||||
socket: handlers,
|
||||
})
|
||||
await withTimeout(opened, timeoutMs, "connect")
|
||||
const greet = await next(link, timeoutMs)
|
||||
if (!greet.startsWith("220")) throw new Error(greet)
|
||||
const ehlo = await speak(link, "EHLO magpie", timeoutMs)
|
||||
if (!ehlo.startsWith("250")) throw new Error(ehlo)
|
||||
if (!secure && cfg.user) {
|
||||
throw new Error("a plain connection sends the password in cleartext; set \"secure\": true (TLS, port 465) or drop the user to use an open relay")
|
||||
}
|
||||
if (cfg.user) {
|
||||
const tok = Buffer.from(`\0${cfg.user}\0${cfg.pass ?? ""}`, "utf8").toString("base64")
|
||||
const auth = await speak(link, `AUTH PLAIN ${tok}`, timeoutMs)
|
||||
if (!auth.startsWith("235")) throw new Error(auth)
|
||||
}
|
||||
// MAIL FROM: the explicit from, else the sign-in, else postmaster —
|
||||
// a null sender reads as a bounce to many relays
|
||||
const mail = await speak(link, `MAIL FROM:<${bare(cfg.from ?? cfg.user ?? "postmaster@localhost")}>`, timeoutMs)
|
||||
if (!mail.startsWith("250")) throw new Error(mail)
|
||||
for (const r of to) {
|
||||
const rep = await speak(link, `RCPT TO:<${bare(r)}>`, timeoutMs)
|
||||
if (!rep.startsWith("25")) throw new Error(rep)
|
||||
}
|
||||
const data = await speak(link, "DATA", timeoutMs)
|
||||
if (!data.startsWith("354")) throw new Error(data)
|
||||
write(link, body)
|
||||
write(link, "\r\n.\r\n")
|
||||
const done = await next(link, timeoutMs)
|
||||
if (!done.startsWith("250")) throw new Error(done)
|
||||
// QUIT's 221 (or the server hanging up) is waited for, so every byte
|
||||
// the mail needs is known to have left before the socket is ended
|
||||
write(link, "QUIT\r\n")
|
||||
await next(link, timeoutMs).catch(() => {})
|
||||
return done
|
||||
} finally {
|
||||
try { link.sock?.end() } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// next is the next full reply. Replies that landed while no waiter was
|
||||
// armed sit in pending: a complete one answers at once, a partial one
|
||||
// becomes the waiter's starting bytes. data and error handlers fire the
|
||||
// rest in.
|
||||
function next(link, timeoutMs) {
|
||||
if (endsReply(link.pending)) {
|
||||
const out = link.pending.trim()
|
||||
link.pending = ""
|
||||
return Promise.resolve(out)
|
||||
}
|
||||
const p = new Promise((res, rej) => {
|
||||
link.waiter = { res, rej, buf: link.pending }
|
||||
link.pending = ""
|
||||
})
|
||||
const t = setTimeout(() => {
|
||||
const q = link.waiter
|
||||
link.waiter = null
|
||||
if (q) q.rej(new Error("smtp reply timed out"))
|
||||
}, timeoutMs)
|
||||
return p.finally(() => clearTimeout(t))
|
||||
}
|
||||
|
||||
// speak arms the reply's waiter first, then writes, so a fast answer can't
|
||||
// pass between the write and the reader.
|
||||
function speak(link, cmd, timeoutMs) {
|
||||
const r = next(link, timeoutMs)
|
||||
write(link, cmd + "\r\n")
|
||||
return r
|
||||
}
|
||||
|
||||
function write(link, data) {
|
||||
link.sock.write(data)
|
||||
}
|
||||
|
||||
function withTimeout(promise, timeoutMs, what) {
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((_, rej) => setTimeout(() => rej(new Error(`smtp ${what} timed out`)), timeoutMs)),
|
||||
])
|
||||
}
|
||||
|
||||
// endsReply is whether buf holds a complete reply: continuation lines
|
||||
// "NNN-text\r\n" zero or more, then one final line "NNN text\r\n" or
|
||||
// "NNN\r\n", the \r\n included — a chunk cut mid-line keeps waiting.
|
||||
function endsReply(buf) {
|
||||
if (!buf.endsWith("\r\n")) return false
|
||||
const lines = buf.split("\r\n")
|
||||
const last = lines[lines.length - 2]
|
||||
return /^\d{3}( |$)/.test(last)
|
||||
}
|
||||
|
||||
function bare(a) {
|
||||
const m = /<([^>]*)>/.exec(String(a ?? ""))
|
||||
return m ? m[1] : String(a ?? "").trim()
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
// Template rendering and the MIME message, with nothing to import.
|
||||
//
|
||||
// fill replaces {{name}} with vars[name]: a missing name becomes "", a
|
||||
// value that isn't a string is JSON. Unknown braces are left as they are,
|
||||
// so a template that means to show an example still does.
|
||||
|
||||
export function fill(text, vars) {
|
||||
return String(text ?? "").replace(/\{\{([A-Za-z0-9_.-]+)\}\}/g, (_, k) => {
|
||||
const v = vars[k]
|
||||
if (v === undefined || v === null) return ""
|
||||
return typeof v === "string" ? v : JSON.stringify(v)
|
||||
})
|
||||
}
|
||||
|
||||
// escape is text into HTML: a mail body the user's template wrote must not
|
||||
// turn an error's words into markup or a link.
|
||||
export function escape(text) {
|
||||
return String(text ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c])
|
||||
}
|
||||
|
||||
// DEFAULT_HTML is the layout a mail goes out in when the user's html
|
||||
// option is unset: a card with a kind badge, the facts as a table, and the
|
||||
// error's words in a pre block. Everything inline-styled — mail clients
|
||||
// strip <style> and class more often than they keep them.
|
||||
export const DEFAULT_HTML = `<!DOCTYPE html>
|
||||
<html><body style="margin:0;padding:24px;background:#f4f5f7;font-family:-apple-system,'Segoe UI','Microsoft YaHei',sans-serif;">
|
||||
<div style="max-width:560px;margin:0 auto;background:#ffffff;border-radius:8px;overflow:hidden;border:1px solid #e5e7eb;">
|
||||
<div style="padding:16px 24px;background:#1f2937;color:#ffffff;">
|
||||
<span style="display:inline-block;padding:2px 10px;border-radius:10px;font-size:12px;background:#dc2626;color:#fff;">{{kind}}</span>
|
||||
<span style="margin-left:8px;font-size:14px;color:#d1d5db;">magpie mail-watch</span>
|
||||
</div>
|
||||
<div style="padding:24px;">
|
||||
<table style="width:100%;border-collapse:collapse;font-size:14px;color:#111827;">
|
||||
<tr><td style="padding:6px 0;color:#6b7280;width:96px;">Provider</td><td style="padding:6px 0;">{{provider}}{{account}}</td></tr>
|
||||
{{modelRow}}
|
||||
{{windowRow}}
|
||||
<tr><td style="padding:6px 0;color:#6b7280;">When</td><td style="padding:6px 0;">{{time}}</td></tr>
|
||||
</table>
|
||||
<div style="margin-top:16px;padding:12px 16px;background:#f9fafb;border-left:3px solid #dc2626;border-radius:0 4px 4px 0;font-size:13px;color:#374151;white-space:pre-wrap;word-break:break-word;">{{detail}}</div>
|
||||
</div>
|
||||
<div style="padding:12px 24px;background:#f9fafb;color:#9ca3af;font-size:12px;">sent by magpie mail-watch from your own gateway</div>
|
||||
</div>
|
||||
</body></html>`
|
||||
|
||||
// renderHtml is the mail's HTML body: the user's own layout (filled with
|
||||
// the same vars) when they set one, the default card otherwise. Every var
|
||||
// interpolated into HTML is escaped first — an error's words are text, not
|
||||
// markup, whoever wrote the layout. The rows the default needs — model,
|
||||
// window — are built here so an empty model or a non-quota event leaves no
|
||||
// skeleton behind.
|
||||
export function renderHtml(templateHtml, vars) {
|
||||
const safe = {}
|
||||
for (const [k, v] of Object.entries(vars)) safe[k] = typeof v === "string" ? escape(v) : v
|
||||
return fill(templateHtml || DEFAULT_HTML, {
|
||||
...safe,
|
||||
modelRow: vars.model
|
||||
? `<tr><td style="padding:6px 0;color:#6b7280;">Model</td><td style="padding:6px 0;">${escape(vars.model)}${vars.agent ? ` <span style="color:#9ca3af;">· ${escape(vars.agent)}</span>` : ""}</td></tr>`
|
||||
: "",
|
||||
windowRow: vars.window
|
||||
? `<tr><td style="padding:6px 0;color:#6b7280;">Window</td><td style="padding:6px 0;">${escape(String(vars.window).replace(/^ · /, ""))} — ${escape(String(vars.used))}% used${vars.resetsAt ? `, resets ${escape(String(vars.resetsAt))}` : ""}</td></tr>`
|
||||
: "",
|
||||
})
|
||||
}
|
||||
|
||||
// message builds one RFC 5322 mail as a string. With an html part it is
|
||||
// multipart/alternative — the plain text first (a client that shows text
|
||||
// takes it), the HTML layout after; without, the single text part as
|
||||
// before. Headers are RFC 2047 encoded words; bodies go out base64.
|
||||
export function message({ from, to, subject, body, html, now = new Date() }) {
|
||||
const id = `<${now.getTime()}.${Math.random().toString(36).slice(2)}@magpie-mail-watch>`
|
||||
const date = now.toUTCString().replace("GMT", "+0000")
|
||||
const head = [
|
||||
`From: ${addr(from)}`,
|
||||
`To: ${to.map(addr).join(", ")}`,
|
||||
`Subject: ${word(subject ?? "")}`,
|
||||
`Date: ${date}`,
|
||||
`Message-ID: ${id}`,
|
||||
"MIME-Version: 1.0",
|
||||
]
|
||||
if (html === undefined || html === false) {
|
||||
return head.concat([
|
||||
'Content-Type: text/plain; charset="utf-8"',
|
||||
"Content-Transfer-Encoding: base64",
|
||||
"",
|
||||
]).join("\r\n") + "\r\n" + b64(body ?? "") + "\r\n"
|
||||
}
|
||||
const boundary = "magpie-" + now.getTime().toString(36) + "-" + Math.random().toString(36).slice(2, 8)
|
||||
return head.concat([
|
||||
`Content-Type: multipart/alternative; boundary="${boundary}"`,
|
||||
"",
|
||||
`--${boundary}`,
|
||||
'Content-Type: text/plain; charset="utf-8"',
|
||||
"Content-Transfer-Encoding: base64",
|
||||
"",
|
||||
b64(body ?? ""),
|
||||
`--${boundary}`,
|
||||
'Content-Type: text/html; charset="utf-8"',
|
||||
"Content-Transfer-Encoding: base64",
|
||||
"",
|
||||
b64(html),
|
||||
`--${boundary}--`,
|
||||
"",
|
||||
]).join("\r\n") + "\r\n"
|
||||
}
|
||||
|
||||
function b64(text) {
|
||||
return Buffer.from(text, "utf8").toString("base64").replace(/(.{76})/g, "$1\r\n")
|
||||
}
|
||||
|
||||
// addr is one address as the header wants it: bare as given, or the
|
||||
// display name kept as quoted-text when ASCII with specials (a comma, a
|
||||
// colon) and RFC 2047 encoded when it holds anything outside ASCII —
|
||||
// "喵喵 <me@example.com>" and "Acme, Inc." <a@b.c> both survive.
|
||||
// CR/LF is stripped first: an option is trusted, a header is a protocol.
|
||||
function addr(a) {
|
||||
const s = String(a ?? "").replace(/[\r\n]+/g, " ").trim()
|
||||
if (!s) return "<postmaster@localhost>"
|
||||
const m = /^(.*)<([^>]*)>\s*$/.exec(s)
|
||||
if (!m) return s
|
||||
const name = m[1].trim()
|
||||
const box = m[2].trim()
|
||||
if (!name) return `<${box}>`
|
||||
if (/[^\x20-\x7e]/.test(name)) return `${word(name)} <${box}>`
|
||||
const quoted = name.replace(/^"|"$/g, "")
|
||||
// a name with specials (a comma, a colon) must stay quoted-text —
|
||||
// "Acme, Inc." <a@b.c> parsed bare would read as two addresses
|
||||
const shown = /[,;:()]/.test(quoted) ? `"${quoted}"` : quoted
|
||||
return `${shown} <${box}>`
|
||||
}
|
||||
|
||||
// word is a header value as RFC 2047 encoded-words when it has anything
|
||||
// outside ASCII, separated by a space-fold so a decoder joins them. Each
|
||||
// encoded-word must decode on its own: the text is chunked by whole
|
||||
// codepoints BEFORE encoding — at most 45 UTF-8 bytes a chunk, 60 base64
|
||||
// characters, an encoded word of 72 — so no codepoint is split across
|
||||
// words and every chunk's base64 is a valid, self-contained unit. (Slicing
|
||||
// the base64 itself would cut quads mid-way: 63 is not a multiple of 4,
|
||||
// and each word would decode to shifted garbage.) CR/LF never survives.
|
||||
function word(s) {
|
||||
const v = String(s ?? "").replace(/[\r\n]+/g, " ")
|
||||
if (!/[^\x20-\x7e]/.test(v)) return v
|
||||
const parts = []
|
||||
let cur = ""
|
||||
for (const ch of v) {
|
||||
if (cur && Buffer.byteLength(cur + ch, "utf8") > 45) {
|
||||
parts.push(Buffer.from(cur, "utf8").toString("base64"))
|
||||
cur = ch
|
||||
} else {
|
||||
cur += ch
|
||||
}
|
||||
}
|
||||
if (cur) parts.push(Buffer.from(cur, "utf8").toString("base64"))
|
||||
return parts.map((p) => "=?UTF-8?B?" + p + "?=").join("\r\n ")
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
// The watch: what mail-watch notices, and what it does about it.
|
||||
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, statSync, openSync, readSync, closeSync } from "node:fs"
|
||||
import { paths } from "./paths.js"
|
||||
|
||||
// One watch per host process: st holds the paths, the offset and the
|
||||
// sent-times the cooldown reads. init() plants it once.
|
||||
let st = null
|
||||
|
||||
// init loads the state file and, when there is none (first run), takes the
|
||||
// usage log's size now as the start, so the first scan doesn't replay
|
||||
// every past failure as if new. Safe to call again; only the first counts.
|
||||
export function init() {
|
||||
if (st) return
|
||||
const p = paths()
|
||||
st = { ...p, offset: -1, sent: {} }
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(st.state, "utf8"))
|
||||
if (raw && typeof raw === "object") {
|
||||
const n = Number(raw.offset)
|
||||
if (Number.isFinite(n)) st.offset = n
|
||||
if (typeof raw.sent === "object" && raw.sent) st.sent = raw.sent
|
||||
if (Array.isArray(raw.mailed)) st.mailed = raw.mailed.filter((t) => typeof t === "number")
|
||||
}
|
||||
} catch {}
|
||||
if (st.offset < 0) {
|
||||
try {
|
||||
st.offset = existsSync(st.usage) ? statSync(st.usage).size : 0
|
||||
} catch {
|
||||
st.offset = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// init runs as the module loads too: the host imports this file as the
|
||||
// plugin host starts, before any request, so a first failure right after
|
||||
// the start lands ahead of the baseline, not behind it. An import-time
|
||||
// failure (a folder magpie can't read) leaves st null and fail() inits
|
||||
// later, from the state file or an empty log, as below.
|
||||
try {
|
||||
init()
|
||||
} catch {}
|
||||
|
||||
// forTests hands the state out and takes one in (its offset and sent-map,
|
||||
// merged over what init loaded, paths kept); null resets to the state
|
||||
// init would load, so a test can start over. Production never calls it.
|
||||
export function forTests(s) {
|
||||
if (s === null) {
|
||||
st = null
|
||||
init()
|
||||
return st
|
||||
}
|
||||
if (!st) init()
|
||||
if (s) st = { ...st, ...s }
|
||||
return st
|
||||
}
|
||||
|
||||
// tail reads the log's bytes from offset. Nothing is decoded here: the
|
||||
// caller cuts at a newline in bytes first, so a byte that isn't UTF-8 can't
|
||||
// grow into a replacement character and push the offset past a row.
|
||||
function tail(from) {
|
||||
let size = 0
|
||||
try {
|
||||
size = statSync(st.usage).size
|
||||
} catch {
|
||||
return Buffer.alloc(0)
|
||||
}
|
||||
if (size <= from) return Buffer.alloc(0)
|
||||
let fh
|
||||
try {
|
||||
fh = openSync(st.usage, "r")
|
||||
const buf = Buffer.alloc(size - from)
|
||||
readSync(fh, buf, 0, buf.length, from)
|
||||
return buf
|
||||
} catch {
|
||||
return Buffer.alloc(0)
|
||||
} finally {
|
||||
if (fh !== undefined) try { closeSync(fh) } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// fail reads the usage log's new bytes and returns one event per failure
|
||||
// worth an alert: watched, the request's own outcome (a try the gateway
|
||||
// handed on is not — its request was answered by a later row), and past
|
||||
// its cooldown. The caller saves the returned offset when the mail went.
|
||||
export function fail(opts, now = Date.now()) {
|
||||
init()
|
||||
const o = opts.watch ?? {}
|
||||
const cd = opts.cooldown ?? {}
|
||||
if (!o.errors) return { events: [], offset: st.offset }
|
||||
pruneSent(cd, now)
|
||||
let size = 0
|
||||
try {
|
||||
size = statSync(st.usage).size
|
||||
} catch {
|
||||
return { events: [], offset: st.offset }
|
||||
}
|
||||
// a log shorter than remembered was cut or replaced: start over
|
||||
if (size < st.offset) st.offset = 0
|
||||
const buf = tail(st.offset)
|
||||
// the last line may be half-written as magpie logs the call that just
|
||||
// finished: cut at the last newline in bytes, decode only that, and leave
|
||||
// the rest for the next exchange's scan
|
||||
const cut = buf.lastIndexOf(0x0a)
|
||||
if (cut < 0) return { events: [], offset: st.offset }
|
||||
const text = buf.subarray(0, cut + 1).toString("utf8")
|
||||
const end = st.offset + cut + 1
|
||||
const events = []
|
||||
for (const line of text.split("\n")) {
|
||||
if (!line) continue
|
||||
let r
|
||||
try {
|
||||
r = JSON.parse(line)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (r.handed_on) continue
|
||||
if (typeof r.status !== "number" || r.status < 400) continue
|
||||
if (!listed(o.providers, r.provider)) continue
|
||||
const key = ["error", r.provider ?? "", r.err_type || String(r.status)].join("|")
|
||||
if (cooled(cd, "error", key, now)) continue
|
||||
events.push({
|
||||
kind: "error",
|
||||
provider: r.provider ?? "",
|
||||
account: r.providerAccount ?? "",
|
||||
model: r.model ?? "",
|
||||
agent: r.agent ?? "",
|
||||
status: r.status,
|
||||
err: String(r.err ?? "").slice(0, 400),
|
||||
errType: r.err_type ?? "",
|
||||
endpoint: r.ep ?? "",
|
||||
})
|
||||
}
|
||||
st.offset = end
|
||||
return { events, offset: end }
|
||||
}
|
||||
|
||||
// quotaScan reads the quotas file as magpie wrote it and returns the
|
||||
// windows the user watches: exhausted, or over the low line. A window the
|
||||
// cooldown already sent is left out. The caller saves afterwards.
|
||||
export function quotaScan(opts, now = Date.now()) {
|
||||
init()
|
||||
const o = opts.watch ?? {}
|
||||
const cd = opts.cooldown ?? {}
|
||||
const wantExhausted = o.quotaExhausted !== false
|
||||
const lowAt = Number(o.quotaLowPct)
|
||||
const wantLow = o.quotaLow === true && Number.isFinite(lowAt) && lowAt > 0 && lowAt < 100
|
||||
if (!wantExhausted && !wantLow) return []
|
||||
pruneSent(cd, now)
|
||||
let quotas
|
||||
try {
|
||||
quotas = JSON.parse(readFileSync(st.quotas, "utf8"))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
if (!quotas || typeof quotas !== "object") return []
|
||||
const out = []
|
||||
for (const [key, entry] of Object.entries(quotas)) {
|
||||
// magpie's own key shape (internal/provider keepLast): provider + "/"
|
||||
// + the account lowercased — "claude/me@example.com". The provider is
|
||||
// everything before the first slash, the account everything after.
|
||||
const slash = key.indexOf("/")
|
||||
const provider = slash < 0 ? key : key.slice(0, slash)
|
||||
const account = slash < 0 ? "" : key.slice(slash + 1)
|
||||
if (!listed(o.providers, provider)) continue
|
||||
const windows = entry?.quota?.windows
|
||||
if (!Array.isArray(windows)) continue
|
||||
for (const w of windows) {
|
||||
const used = Number(w?.used)
|
||||
if (!Number.isFinite(used)) continue
|
||||
// quotas.json holds the last readings, not the live state: a window
|
||||
// whose reset already passed is a stale reading, not a window still
|
||||
// full — skip it, or it re-alerts every cooldown forever. A window
|
||||
// with no parseable reset keeps alerting: its state is unknown,
|
||||
// and silence would hide a real exhaustion.
|
||||
if (expired(w?.resetsAt, now)) continue
|
||||
const exhausted = wantExhausted && used >= 100
|
||||
const low = wantLow && used >= lowAt && used < 100
|
||||
if (!exhausted && !low) continue
|
||||
const kind = exhausted ? "quotaExhausted" : "quotaLow"
|
||||
// the kind is in the key: a "low" mail sent an hour ago must not
|
||||
// silence the "exhausted" one when the window reaches 100%
|
||||
if (cooled(cd, "quota", ["quota", kind, key, w.name].join("|"), now)) continue
|
||||
out.push({ kind, provider, account, window: w.name ?? "", used, resetsAt: w.resetsAt ?? "" })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// expired is whether a window's reset time has already passed: magpie
|
||||
// writes resetsAt as an RFC 3339 string (Go's time.Time in JSON), a
|
||||
// millisecond number, or a second number — all three parse here.
|
||||
function expired(resetsAt, now) {
|
||||
if (resetsAt === undefined || resetsAt === null || resetsAt === "") return false
|
||||
let t
|
||||
if (typeof resetsAt === "number") t = resetsAt > 1e12 ? resetsAt : resetsAt * 1000
|
||||
else t = Date.parse(String(resetsAt))
|
||||
return Number.isFinite(t) && t < now
|
||||
}
|
||||
|
||||
// the cooldown: a key that sent within its kind's minutes is left out, and
|
||||
// a key about to be sent is marked now. Unconfigured, errors wait 10
|
||||
// minutes and quota windows 4 hours. st must be inited.
|
||||
function cooled(cooldownOpts, kind, key, now) {
|
||||
const mins = Number(cooldownOpts?.[kind])
|
||||
const ms = Number.isFinite(mins) && mins >= 0 ? mins * 60_000 : (kind === "error" ? 10 : 240) * 60_000
|
||||
const last = st.sent[key]
|
||||
if (typeof last === "number" && now - last < ms) return true
|
||||
st.sent[key] = now
|
||||
return false
|
||||
}
|
||||
|
||||
// listed is whether provider is one the user asked for: an empty list is
|
||||
// every provider, a non-empty one only those on it.
|
||||
function listed(list, provider) {
|
||||
if (!Array.isArray(list) || !list.length) return true
|
||||
return list.includes(provider)
|
||||
}
|
||||
|
||||
// pruneSent drops sent-marks older than the longest cooldown still in
|
||||
// force, so the map doesn't grow without bound: a mark's only job is to
|
||||
// hold its key quiet for its own window, and the longest window (the
|
||||
// quota one, 4 hours by default) bounds how long any mark can matter.
|
||||
// Suppression itself still reads each kind's own window in cooled().
|
||||
function pruneSent(cd, now) {
|
||||
const eff = (kind, def) => {
|
||||
const n = Number(cd?.[kind])
|
||||
return Number.isFinite(n) && n >= 0 ? n : def
|
||||
}
|
||||
const keepAfter = now - Math.max(eff("error", 10), eff("quota", 240)) * 60_000
|
||||
for (const k of Object.keys(st.sent)) {
|
||||
if (typeof st.sent[k] !== "number" || st.sent[k] < keepAfter) delete st.sent[k]
|
||||
}
|
||||
}
|
||||
|
||||
// takeWithinCap slices events to the mail budget left this hour and
|
||||
// records the mails about to be queued, so a bad hour can't send one
|
||||
// mail per key without bound: the per-key cooldown caps each key, this
|
||||
// caps the hour. cap is maxMailsPerHour; unset or invalid means 20.
|
||||
// The count is of mails queued, not delivered — a queued mail that then
|
||||
// fails still spent its slot, the way a sent one would.
|
||||
export function takeWithinCap(events, cap, now = Date.now()) {
|
||||
init()
|
||||
const limit = Number.isFinite(Number(cap)) && Number(cap) > 0 ? Math.floor(Number(cap)) : 20
|
||||
if (!Array.isArray(st.mailed)) st.mailed = []
|
||||
const hourAgo = now - 3_600_000
|
||||
st.mailed = st.mailed.filter((t) => typeof t === "number" && t > hourAgo)
|
||||
const room = Math.max(0, limit - st.mailed.length)
|
||||
const taken = events.slice(0, room)
|
||||
for (let i = 0; i < taken.length; i++) st.mailed.push(now)
|
||||
return taken
|
||||
}
|
||||
|
||||
// save writes the state file, atomically — and it merges, never replaces:
|
||||
// the file is one object shared with the digest (digest.js keeps its
|
||||
// cursor, digestOffset, in it), and a scan that stringified only the
|
||||
// watch's own fields used to wipe that cursor on every exchange, so the
|
||||
// digest re-read the whole log. Disk fields the watch doesn't own survive;
|
||||
// the watch's own fields (offset, sent, mailed) always win.
|
||||
export function save() {
|
||||
if (!st) return
|
||||
try {
|
||||
mkdirSync(st.dir, { recursive: true })
|
||||
let disk = {}
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(st.state, "utf8"))
|
||||
if (raw && typeof raw === "object") disk = raw
|
||||
} catch {}
|
||||
const tmp = st.state + ".tmp"
|
||||
writeFileSync(tmp, JSON.stringify({ ...disk, ...st }))
|
||||
renameSync(tmp, st.state)
|
||||
} catch {}
|
||||
}
|
||||
@@ -90,6 +90,8 @@
|
||||
{ "package": "@magpie-community/page-chat", "name": "Chat", "kind": "page", "community": true,
|
||||
"summary": { "en": "A chat page in magpie's window by Magic_zero: talk to magpie's own models with your MCP servers, instructions and skills, images and LaTeX. Runs a local service on 127.0.0.1 that only its own page can use.", "zh": "Magic_zero 做的 magpie 窗口内「对话」页面:用 magpie 自己的模型聊天,带上你的 MCP 服务器、指令和技能,支持图片与 LaTeX。本地服务只在 127.0.0.1,只给自己的页面用。" } },
|
||||
{"package": "@magpie-community/agent-kimi-desktop", "name": "Kimi", "kind": "agent", "community": true, "summary": {"en": "Kimi desktop Work on Magpie's Agents page: select a model from Magpie, then disconnect to restore the original service. Not Kimi Code CLI.", "zh": "把普通 Kimi 桌面版 Work 接入 Magpie Agent 页,使用已配置的模型;断开恢复原连接。不是 Kimi Code CLI。"}},
|
||||
{ "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,
|
||||
"summary": { "en": "Cloudflare Workers AI with your API token (Workers AI:Edit): 28+ models discovered live from models.dev, the 8 paid-only models flagged, and a Neurons/day allowance row in magpie quota.", "zh": "用你的 Cloudflare API Token(Workers AI:Edit 权限)登录 Workers AI:28+ 模型经 models.dev 实时发现,付费专属模型自动标注,magpie quota 显示每日 Neurons 免费额度。" } },
|
||||
{ "package": "officeace-auth", "name": "OfficeAce", "providers": ["officeace"], "community": true,
|
||||
|
||||
+4
-3
@@ -15,9 +15,10 @@ for (const name of readdirSync(root)) {
|
||||
const pj = join(dir, "package.json")
|
||||
if (!existsSync(pj)) continue
|
||||
const pkg = JSON.parse(readFileSync(pj, "utf8"))
|
||||
// gateway middleware and routings, agents and pages have no OpenCode
|
||||
// plugin; their own tests check them
|
||||
if (pkg.magpie?.middleware || pkg.magpie?.gateway || pkg.magpie?.agent) continue
|
||||
// gateway middleware and routings, agents, pages and asynchronous hooks
|
||||
// (magpie.hooks, Bun's own import) have no OpenCode plugin; their own
|
||||
// tests check them
|
||||
if (pkg.magpie?.middleware || pkg.magpie?.gateway || pkg.magpie?.agent || pkg.magpie?.hooks) continue
|
||||
if (pkg.magpie?.page && !pkg.main && !pkg.exports) continue
|
||||
const problems = []
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user