From 7153e59d787c291eac2e732e5ea8cfd7cf05863b Mon Sep 17 00:00:00 2001 From: 1sh1ro <2855020996@qq.com> Date: Wed, 11 Nov 2026 10:49:01 +0800 Subject: [PATCH] page-model-quota 0.1.0: the tokens each model has left, across accounts (#932) A page that shows how many tokens each model has left across your accounts. It is estimated from magpie's quota windows (/v1/magpie/quotas) and past usage rounds: the median tokens per percent over the rounds that can be used, or one round, or "sparse". The report carries no prose. The page words everything in English or Chinese. The service binds only to loopback, checks the Host, refuses a foreign Origin, wants a per-run key for Origin null, serves index.html to navigations only, and writes nothing under HOME. page-model-quota 0.1.0. Run at the reviewed head dd8d44164d505088efeb07d80784128134aad213, on the Windows box (mote's sshd was refusing connections): - node --test test/*.test.mjs: 14 pass. bun test: 14 pass. bun scripts/check.mjs: exit 0. It merges cleanly with main 86d3febf. - Broken by hand: taking the space out of " (from past rounds)" again turns i18n.test red (13 of 14). At a5d9a8c5, on mote and in WSL (from the review): the Host, Origin, key and navigate-only checks each went red when broken. Wrong Hosts got 403, Origin null without a key got 401, traversal got 404, and a restart rotated the key. The page rendered in Chromium and WebKit at 1200px and 420px, with no Chinese in English. Since then, only the English note's space, an unused usableRounds, the English gateway error and template-literal coverage in the i18n test have changed. Not tried: in a real magpie window with real quota windows. --- README.md | 1 + packages/page-model-quota/LICENSE | 21 + packages/page-model-quota/README.md | 96 ++++ packages/page-model-quota/assets/icon.svg | 8 + packages/page-model-quota/index.mjs | 25 + packages/page-model-quota/lib/report.mjs | 448 ++++++++++++++++++ packages/page-model-quota/lib/server.mjs | 389 +++++++++++++++ packages/page-model-quota/package.json | 69 +++ packages/page-model-quota/page/boot.js | 121 +++++ packages/page-model-quota/page/icon.svg | 8 + packages/page-model-quota/page/index.html | 38 ++ packages/page-model-quota/serve.mjs | 11 + packages/page-model-quota/test/i18n.test.mjs | 45 ++ packages/page-model-quota/test/page.test.mjs | 47 ++ packages/page-model-quota/test/quota.test.mjs | 159 +++++++ packages/page-model-quota/ui/app.js | 359 ++++++++++++++ packages/page-model-quota/ui/index.html | 82 ++++ packages/page-model-quota/ui/style.css | 101 ++++ registry.json | 5 +- 19 files changed, 2030 insertions(+), 3 deletions(-) create mode 100644 packages/page-model-quota/LICENSE create mode 100644 packages/page-model-quota/README.md create mode 100644 packages/page-model-quota/assets/icon.svg create mode 100644 packages/page-model-quota/index.mjs create mode 100644 packages/page-model-quota/lib/report.mjs create mode 100644 packages/page-model-quota/lib/server.mjs create mode 100644 packages/page-model-quota/package.json create mode 100644 packages/page-model-quota/page/boot.js create mode 100644 packages/page-model-quota/page/icon.svg create mode 100644 packages/page-model-quota/page/index.html create mode 100644 packages/page-model-quota/serve.mjs create mode 100644 packages/page-model-quota/test/i18n.test.mjs create mode 100644 packages/page-model-quota/test/page.test.mjs create mode 100644 packages/page-model-quota/test/quota.test.mjs create mode 100644 packages/page-model-quota/ui/app.js create mode 100644 packages/page-model-quota/ui/index.html create mode 100644 packages/page-model-quota/ui/style.css diff --git a/README.md b/README.md index 6f2c6a9..0ffad9e 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,7 @@ These add a page to magpie's window, in the app and in `magpie web`, under Plugi | [agent-office](packages/agent-office) | What are my agents doing: a real WebGL 3D office with six scenes, an isometric/2D office, grouped workbench, Today usage and recent conversations | no `magpie.read`; its host part reads local session files of Claude Code, Codex, Copilot CLI, Kimi Code, dsh, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy, CodeBuddy and Grok Build, including prompts, replies and tool commands (`text:false` keeps statuses and tool names only) | | [page-usage-tree](packages/page-usage-tree) | Account usage: usage as provider -> account -> model, each level expandable, with per-account calls, errors and cost; adds the account layer Usage glance's `usage:summary` does not contain | none (its local service calls Magpie's local usage API) | | [page-usage-board](packages/page-usage-board) | Full usage board: quota cards with expiry tiers, daily/per-provider charts, 24h cache-hit and token curves, optional remote attribution and account detail | none (the page reads nothing through the bridge; its local service reads your usage.jsonl, magpie's usage/quota API, and — for optional remote attribution — your magpie config's provider key to query the configured remote magpie) | +| [page-model-quota](packages/page-model-quota) | Model quota: how many tokens each model has left, merged across every account and provider; each quota window is turned into tokens from your usage history and split by the model's share in it | none (its local service reads `usage.jsonl` and `quota-history.json`, and calls magpie's local quota API) | | [fingerprint](packages/fingerprint) | Numeric response fingerprints to investigate suspected model substitution across providers, with shared challenges, candidate rankings, local evidence and JSON export | none (its local service calls magpie’s gateway; sampling uses provider quota) | | [chat](packages/chat) | Chat with magpie's models, your MCP servers, instructions and skills, by Magic_zero ([Magiczerowxy](https://github.com/Magiczerowxy)). Has a host part: a local service the page goes to | none (its service calls magpie's gateway) | | [window-warmup](packages/window-warmup) | Window warmup: send one fixed short message ("hi", max_tokens 16) to a provider, account and model you pick, right after its quota window resets, daily at set times or every few hours, so the next subscription window opens early, by [YangHonghang](https://github.com/YangHonghang). Has a host part: a local service on 127.0.0.1 the page goes to | none; its service calls magpie's gateway and reads magpie's providers.json (keys only as sha256 fingerprints, plus key names and account models) and model cache. Each send uses the chosen account's quota | diff --git a/packages/page-model-quota/LICENSE b/packages/page-model-quota/LICENSE new file mode 100644 index 0000000..22e1c9c --- /dev/null +++ b/packages/page-model-quota/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 magpie-model-quota contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/page-model-quota/README.md b/packages/page-model-quota/README.md new file mode 100644 index 0000000..f5bd441 --- /dev/null +++ b/packages/page-model-quota/README.md @@ -0,0 +1,96 @@ +## 中文说明 + +在 Magpie 窗口里看到**每个模型在所有账号、所有供应商的池子里还剩多少 token**。 +它把每个额度窗口换算成 token,再按模型在窗口内的占比摊开,最后跨账号、跨供应商合并。 + +```sh +magpie plugin add @magpie-community/page-model-quota +``` + +# @magpie-community/page-model-quota + +## English + +A page in Magpie's window that answers one question: **how many tokens does each +model have left, across every account and every provider at once**. + +Every quota window Magpie tracks — a 5-hour window, a 7-day window, a month of +credits, a token package — is turned into tokens using your own usage history, +split by each model's share inside that window, and then added up per model +across accounts and providers. + +```sh +magpie plugin add @magpie-community/page-model-quota +``` + +## How the number is made + +1. **Tokens per 1% of a window.** For each account and window, the page takes the + readings in `quota-history.json`, cuts them into rounds (a round ends where the + percentage jumps back up), and divides the tokens spent during a round by the + percentage that round dropped. The median over the complete rounds is that + window's tokens per 1%. Rounds with fewer than five calls are left out, so one + oversized request cannot define a window. +2. **Tokens left in the window.** Remaining percentage × tokens per 1%. +3. **Split by model.** The usage rows inside that same round carry a model, so the + window's tokens are split by the share each model had in it. Model names are + normalized: `grok-4.7@500k` and `grok-4.7@256k` are one model. +4. **Merge.** The same model's share from every account and provider is added up. + +Nested rate windows are handled as one allowance: a 5-hour window only throttles +speed, so the longest window of an account (7 days, Month, Weekly) is what counts +as its remaining allowance. If that longest window is spent, the account counts as +used up, and its shorter windows are not counted as available either. + +Credit windows (`Credits`, `Extra credits`, token packages, trials) are counted one +by one; a window named `Total credits` or `总积分` is the sum of the others, so it +replaces them instead of adding to them. Windows measured in something other than +credits or tokens (requests, questions) are skipped. + +## Where the data comes from + +- `usage.jsonl` — one line per request, with `in`, `out`, `cache_read`, + `cache_write` and `reasoning`. Tokens are their sum. +- `quota-history.json` — the remaining percentage Magpie recorded for each account + and window, with the time of the reading. +- `quotas.json` — the current quota snapshot, used when the gateway does not answer. +- `GET /v1/magpie/quotas?kept=1` on the local gateway — the current remaining + percentage, preferred over the snapshot. + +Nothing leaves the machine. The service asks the local gateway and reads the files +above; there is no telemetry and no other request. + +## Architecture + +- `page/index.html` and `page/boot.js` are the launcher Magpie sandboxes. They read + the theme, the language and this plugin's options, then navigate the frame to the + local service. They never probe it: a plugin page's CSP is `connect-src 'none'`. +- `lib/server.mjs` is that service, started from `index.mjs` by Magpie's Bun host + and stopped with the plugin. It serves `ui/` and `/api/report`. +- `lib/report.mjs` holds the estimation itself and has no I/O, so the tests can call + it directly. + +The service binds `127.0.0.1` only, on port 3496 by default; set `port` in the +plugin's options to change it. `Host` must be `127.0.0.1:` or +`localhost:`. Every `/api` route except `/api/ping` needs a key generated at +each start and injected into the HTML this instance serves; that HTML is returned +only to navigation requests, so another page cannot fetch it to read the key. A +sandboxed frame's `Origin: null` is accepted only together with the key. + +## What it does not do + +- It does not ask providers for quota. Magpie's own plugin does that; this page + reads what Magpie recorded. +- It cannot estimate a window with no history: no readings, or no usage to line up + with them, means no number, and the window is named in the footer. +- A window whose latest round has far fewer records than its history is marked + "from past rounds" — the number is still shown, with that caveat. + +## Tests + +```sh +node --test test/*.test.mjs +``` + +They build a small config directory in a temp folder, start the service on port 0 +and check the guards (host, origin, key) and the estimate itself. diff --git a/packages/page-model-quota/assets/icon.svg b/packages/page-model-quota/assets/icon.svg new file mode 100644 index 0000000..b6e6325 --- /dev/null +++ b/packages/page-model-quota/assets/icon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/packages/page-model-quota/index.mjs b/packages/page-model-quota/index.mjs new file mode 100644 index 0000000..50fbfa3 --- /dev/null +++ b/packages/page-model-quota/index.mjs @@ -0,0 +1,25 @@ +// 插件的宿主部分:magpie 的 Bun 宿主加载本模块,向它要页面服务。 +// 服务跑在这个宿主进程里,magpie 停掉插件时一起停。 +import { startServer } from "./lib/server.mjs"; + +let started = null; + +export default { + id: "magpie-model-quota", + server: async (input, options) => { + if (!started) { + // 端口 0 或非法值归成 undefined:页面从同一份 options 读到的与这里一致。 + const value = Number(options?.port); + const port = Number.isInteger(value) && value > 0 && value < 65536 ? value : undefined; + started = startServer({ + port, + configDir: input?.directory, + }).catch((error) => { + started = null; + throw error; + }); + } + await started; + return {}; + }, +}; diff --git a/packages/page-model-quota/lib/report.mjs b/packages/page-model-quota/lib/report.mjs new file mode 100644 index 0000000..8ce8b19 --- /dev/null +++ b/packages/page-model-quota/lib/report.mjs @@ -0,0 +1,448 @@ +// 估算每个模型在所有额度池里还剩多少 token。 +// +// 口径:token 指一次请求实际处理的全部 token,即 in + out + cache_read + cache_write + reasoning。 +// 某个窗口“1% 额度值多少 token”由历史推得:取该窗口当前这一轮的读数区间, +// 用区间内该账号消耗的 token 除以掉掉的百分比。 +// +// 一个窗口的剩余 token = 剩余百分比 × 每百分比 token。 +// 再把窗口的剩余 token 按该账号在窗口内的模型占比摊到各模型,最后跨账号、跨供应商按模型相加。 + +const DAY = 24 * 60 * 60 * 1000 + +export function tokensOf(row) { + return Number(row.in || 0) + Number(row.out || 0) + Number(row.cache_read || 0) + + Number(row.cache_write || 0) + Number(row.reasoning || 0) +} + +// 去掉模型名后面的上下文容量后缀,让同一个模型的 500k、256k 之类归到一起: +// grok-4.7@500k / grok-4.7@256k -> grok-4.7 +// claude-fable-5-1[1m] -> claude-fable-5-1 +// grok-4.7-500k -> grok-4.7 +export function cleanModelName(name) { + let s = String(name ?? "").trim() + s = s.replace(/\s*@\S*$/, "") + s = s.replace(/\s*\[[^\]]*\]\s*$/, "") + s = s.replace(/[-_ ]\d+k$/i, "") + return s.trim() +} + +// 模型名归一:跨供应商、跨大小写、跨分隔符归到同一个键。 +export function canonModel(name) { + return cleanModelName(name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") +} + +// 把逐条 usage 记录按账号建索引,并附上按时间排序的前缀和,便于任意区间求和。 +export function indexUsage(rows, { now = Date.now(), shareWindowMs = 7 * DAY } = {}) { + const accounts = new Map() + const modelDaily = new Map() // canon -> {tokens} + const displayCount = new Map() // canon -> Map(全量统计,名字更全) + + for (const row of rows) { + const key = `${row.provider || ""}|${row.providerAccount || ""}` + if (!accounts.has(key)) accounts.set(key, { rows: [] }) + accounts.get(key).rows.push(row) + + const c = canonModel(row.model || row.served || "?") + if (!displayCount.has(c)) displayCount.set(c, new Map()) + const dc = displayCount.get(c) + const raw = cleanModelName(row.model || row.served || "?") + dc.set(raw, (dc.get(raw) || 0) + 1) + + const t = Date.parse(row.t) + const tk = tokensOf(row) + if (Number.isFinite(t) && now - t <= shareWindowMs) { + if (!modelDaily.has(c)) modelDaily.set(c, { tokens: 0 }) + modelDaily.get(c).tokens += tk + } + } + + for (const acc of accounts.values()) { + acc.rows.sort((a, b) => Date.parse(a.t) - Date.parse(b.t)) + acc.times = acc.rows.map((r) => Date.parse(r.t)) + acc.cum = new Array(acc.rows.length) + let sum = 0 + for (let i = 0; i < acc.rows.length; i++) { + sum += tokensOf(acc.rows[i]) + acc.cum[i] = sum + } + acc.total = sum + } + + const bestDisplay = (canon) => { + const m = displayCount.get(canon) + if (!m) return canon + let best = canon, bestN = -1 + for (const [raw, n] of m) if (n > bestN) { best = raw; bestN = n } + return best + } + + // 前缀和在 [t0, t1) 区间内的增量,以及该区间内按模型的 token 数。 + const sliceStats = (acc, t0, t1) => { + const lo = lowerBound(acc.times, t0) + const hi = lowerBound(acc.times, t1) + const tokens = (hi > 0 ? acc.cum[hi - 1] : 0) - (lo > 0 ? acc.cum[lo - 1] : 0) + const byModel = new Map() + let calls = 0 + for (let i = lo; i < hi; i++) { + const r = acc.rows[i] + const c = canonModel(r.model || r.served || "?") + byModel.set(c, (byModel.get(c) || 0) + tokensOf(r)) + calls++ + } + return { tokens, byModel, calls } + } + + return { accounts, modelDaily, bestDisplay, sliceStats } +} + +function lowerBound(arr, x) { + let lo = 0, hi = arr.length + while (lo < hi) { + const mid = (lo + hi) >> 1 + if (arr[mid] < x) lo = mid + 1 + else hi = mid + } + return lo +} + +// 从历史读数里求“每 1% 额度约合多少 token”。 +// 优先用当前这一轮:首点(应为 100 附近)到末点的 token 增量 ÷ 掉掉的百分比。 +// 首点不是满额时,退到该轮内各相邻点区间比值的中位数。 +export function tokensPerPercent(points, acc, sliceStats) { + if (!Array.isArray(points) || points.length < 2 || !acc) return null + // 按轮次分组。历史里有的点没有 start 字段,所以除了 start 变化, + // 还要在“剩余百分比突然回升”(重置)处切一刀。 + const sorted = points + .filter((p) => p && p.at) + .slice() + .sort((a, b) => Date.parse(a.at) - Date.parse(b.at)) + const groups = [] + let cur = null + let curStart = null + for (const p of sorted) { + const st = p.start ? Date.parse(p.start) : null + const prev = cur && cur.length ? cur[cur.length - 1] : null + const reset = prev && Number(p.left) > Number(prev.left) + 2 + const newStart = st != null && curStart != null && st !== curStart + if (!cur || reset || newStart) { + cur = [] + groups.push(cur) + curStart = st + } else if (st != null) { + curStart = st + } + cur.push(p) + } + if (!groups.length) return null + // 每一轮就是一次独立测量:这一轮掉了多少百分比、同期记录到多少 token、多少条请求。 + const rounds = [] + for (const arr of groups) { + if (arr.length < 2) continue + const first = arr[0] + const last = arr[arr.length - 1] + const drop = Number(first.left) - Number(last.left) + const t0 = Date.parse(first.at) + const t1 = Date.parse(last.at) + if (!(drop >= 3) || !(t1 > t0)) continue + const s = sliceStats(acc, t0, t1) + if (!(s.tokens > 0)) continue + rounds.push({ + start: t0, + end: t1, + drop, + tokens: s.tokens, + calls: s.calls, + cpp: s.calls > 0 ? s.calls / drop : 0, + ratio: s.tokens / drop, + byModel: s.byModel, + }) + } + if (!rounds.length) return null + + // 每一轮都是一次测量。记录很少的轮次(每条请求对应的百分比过大)不参与, + // 用剩下这些完整轮次的中位数作为这个窗口的「每 1% 多少 token」。 + const cpps = rounds.map((r) => r.cpp).filter((x) => x > 0).sort((a, b) => a - b) + const medCpp = cpps.length ? cpps[Math.floor(cpps.length / 2)] : 0 + const usable = rounds.filter((r) => r.calls >= 5 && (medCpp === 0 || r.cpp >= medCpp * 0.2)) + const pool = usable.length ? usable : rounds + const ratios = pool.map((r) => r.ratio).sort((a, b) => a - b) + const med = ratios[Math.floor(ratios.length / 2)] + const byModel = new Map() + for (const r of pool) for (const [m, v] of r.byModel) byModel.set(m, (byModel.get(m) || 0) + v) + const p20 = ratios[Math.floor(ratios.length * 0.2)] + const p80 = ratios[Math.floor(ratios.length * 0.8)] + const dispersion = med > 0 ? (p80 - p20) / med : 99 + const last = rounds[rounds.length - 1] + + return { + tpp: med, + // 语言无关的取值,页面自己翻译:median 用多轮中位数,single 只有一轮,sparse 记录不足。 + method: usable.length > 1 ? "median" : usable.length === 1 ? "single" : "sparse", + start: pool[0].start, + end: pool[pool.length - 1].end, + drop: pool[pool.length - 1].drop, + byModel, + totalTokens: pool.reduce((s, r) => s + r.tokens, 0), + points: sorted.length, + rounds: rounds.length, + dispersion, + medianCallsPerPercent: medCpp, + lowConfidence: usable.length === 0, + latest: { drop: last.drop, tokens: last.tokens, calls: last.calls, cpp: last.cpp, ratio: last.ratio }, + } +} + +// 判断一个窗口属于哪一类: +// token 令牌型窗口(名字带 tokens) +// aggregate 汇总窗口(Total credits、总积分),它等于下面各分包的合计 +// credit 积分类窗口(Credits、Extra credits、各种积分包、试用包) +// rate 时间型速率窗口(5 hours、7 days、Month、Weekly、每日、本轮) +// 时间型窗口是嵌套的:5 小时限制的是瞬时速度,7 天 / Month 才是总的额度上限, +// 所以剩余 token 以周期最长的那个窗口为准。 +export function classifyWindow(name) { + const n = String(name || "") + if (/tokens?\s*(\(|()?\s*est/i.test(n) || /tokens?\s*$/i.test(n)) return "token" + if (/total|总|合计|全部/i.test(n)) return "aggregate" + if (/积分|credit|bonus|包|签到|福利|赠送|余额|领取|trial|试用/i.test(n)) return "credit" + if (/^\s*(\d+\s*(hours?|days?|weeks?|months?|minutes?)|weekly|monthly|daily|month|day|hour|每日|本轮)/i.test(n)) return "rate" + return "credit" +} + +// 窗口对应的周期长度(小时),用来判断哪个是总的额度上限。 +export function periodHours(name) { + const n = String(name || "").trim().toLowerCase() + const m = /^\s*(\d+(?:\.\d+)?)\s*(minute|hour|day|week|month)/.exec(n) + if (m) { + const v = Number(m[1]) + return m[2] === "minute" ? v / 60 : m[2] === "hour" ? v : m[2] === "day" ? v * 24 : m[2] === "week" ? v * 168 : v * 720 + } + if (/month|月/.test(n)) return 720 + if (/week|周/.test(n)) return 168 + if (/day|天|每日/.test(n)) return 24 + if (/hour|小时|本轮/.test(n)) return 1 + return 0 +} + +// 主入口:把网关给当前额度、历史读数、逐条用量合成按模型的剩余 token 报表。 +export function buildReport({ quotaRecords, history, usage, now = Date.now() }) { + const idx = usage + const models = new Map() // canon -> {tokens, pools: Map, display} + const modelPoolDetail = new Map() // canon -> [{pool, tokens, share, ...}] + const pools = [] // 每个有效池一行,便于展开 + const blockedAccounts = [] // 因为某个窗口已用完而不计入的账号 + const skipped = { noHistory: 0, noUsage: 0, noPercent: 0, unsupportedUnit: 0, blockedWindows: 0 } + + // 同一账号的多个窗口要先合在一起看:时间型嵌套取最紧,汇总窗口只算它自己。 + const accounts = new Map() + for (const rec of quotaRecords || []) { + const key = `${rec.provider || ""}|${rec.user || ""}` + if (!accounts.has(key)) accounts.set(key, { provider: rec.provider, user: rec.user || "", recs: [] }) + accounts.get(key).recs.push(rec) + } + + for (const [key, group] of accounts) { + const acc = idx.accounts.get(key) || findAccountLoose(idx.accounts, group.provider, group.user) + const hist = findHistory(history, group.provider, group.user) || {} + const wins = [] + for (const rec of group.recs) { + for (const w of rec.windows || []) { + if (typeof w.used !== "number") { skipped.noPercent++; continue } + // 单位是「次」「问题」这类非 token 额度的窗口,不参与 token 估算 + if (w.unit && !/credit|积分|token/i.test(String(w.unit))) { skipped.unsupportedUnit++; continue } + const remaining = typeof w.remaining === "number" ? w.remaining : Math.max(0, 100 - w.used) + const pts = hist[w.name] + const est = pts && acc ? tokensPerPercent(pts, acc, idx.sliceStats) : null + if (!pts) skipped.noHistory++ + else if (!est) skipped.noUsage++ + wins.push({ + name: w.name, + remaining, + used: w.used, + resetsAt: w.resetsAt || null, + tpp: est ? est.tpp : null, + method: est ? est.method : null, + points: est ? est.points : 0, + rounds: est ? est.rounds : 0, + dispersion: est ? est.dispersion : 0, + medianCallsPerPercent: est ? est.medianCallsPerPercent : 0, + latest: est ? est.latest : null, + lowConfidence: est ? !!est.lowConfidence : false, + byModel: est ? est.byModel : null, + remainTokens: est ? Math.max(0, remaining) * est.tpp : null, + kind: classifyWindow(w.name), + periodH: periodHours(w.name), + }) + } + } + if (!wins.length) continue + + const rate = wins.filter((x) => x.kind === "rate") + const aggregate = wins.filter((x) => x.kind === "aggregate") + const credit = wins.filter((x) => x.kind === "credit") + const token = wins.filter((x) => x.kind === "token") + + // 组合成「池」:时间型一组取最紧;有汇总窗口就只算汇总;其余各算各的。 + const plan = [] + if (rate.length) plan.push({ label: rate.map((x) => x.name).join(" · "), wins: rate, mode: "longest", kind: "rate" }) + if (aggregate.length) plan.push({ label: aggregate.map((x) => x.name).join(" · "), wins: aggregate, mode: "single", kind: "aggregate" }) + else for (const c of credit) plan.push({ label: c.name, wins: [c], mode: "single", kind: "credit" }) + for (const t of token) plan.push({ label: t.name, wins: [t], mode: "single", kind: "token" }) + + for (const p of plan) { + let binding + let blockedWin = null + if (p.mode === "longest") { + // 周期最长的窗口是总的额度上限;5 小时这类只限制瞬时速度,不单独当成总剩余 + binding = p.wins.reduce((a, b) => { + const pa = a.periodH || 0 + const pb = b.periodH || 0 + if (pb !== pa) return pb > pa ? b : a + return Number(b.remaining) < Number(a.remaining) ? b : a + }) + if (binding.remaining <= 1) blockedWin = binding + } else { + binding = p.wins[0] + const hit = p.wins.find((x) => x.remaining <= 1) + if (hit) blockedWin = hit + } + const shown = binding + const latest = binding?.latest || null + // 最新一轮记录很少、远低于历史轮次时,标成记录不足 + const lowConfidence = !!binding && (binding.lowConfidence || + (!!latest && binding.medianCallsPerPercent > 0 && latest.cpp > 0 && + latest.cpp < binding.medianCallsPerPercent * 0.2)) + const shortExhausted = p.mode === "longest" + ? p.wins.filter((x) => x !== binding && x.remaining <= 1).map((x) => x.name) + : [] + const poolKey = group.user ? `${group.provider}/${group.user}·${p.label}` : `${group.provider}·${p.label}` + const row = { + pool: poolKey, + provider: group.provider, + user: group.user, + window: p.label, + used: shown.used, + remaining: blockedWin ? 0 : shown.remaining, + resetsAt: shown.resetsAt, + tpp: binding ? binding.tpp : null, + method: binding ? binding.method : null, + points: binding ? binding.points : 0, + rounds: binding ? binding.rounds : 0, + roundDrop: latest ? latest.drop : null, + roundTokens: latest ? latest.tokens : null, + roundCalls: latest ? latest.calls : null, + dispersion: binding ? binding.dispersion : 0, + lowConfidence, + shortExhausted, + tokens: 0, + blocked: !!blockedWin, + blockedBy: blockedWin ? blockedWin.name : "", + models: [], + } + if (blockedWin) { + skipped.blockedWindows++ + if (!blockedAccounts.find((a) => a.account === key)) { + blockedAccounts.push({ account: key, window: blockedWin.name }) + } + pools.push(row) + continue + } + const tokens = !binding + ? 0 + : p.mode === "longest" + ? binding.remainTokens + : p.wins.reduce((s, x) => s + Math.max(0, x.remainTokens || 0), 0) + if (!(tokens > 0)) { pools.push(row); continue } + row.tokens = tokens + + // 摊到模型:用该池里最紧那个窗口的模型占比 + const byModel = (binding && binding.byModel) || new Map() + let denom = 0 + for (const v of byModel.values()) denom += v + if (denom > 0) { + for (const [canon, v] of byModel) { + const share = v / denom + if (share <= 0) continue + const part = tokens * share + addModel(models, canon, part, poolKey, idx.bestDisplay(canon)) + row.models.push({ id: canon, name: idx.bestDisplay(canon), share, tokens: part }) + pushDetail(modelPoolDetail, canon, { + pool: poolKey, provider: group.provider, user: group.user, window: p.label, + remaining: binding.remaining, resetsAt: binding.resetsAt, poolTokens: tokens, tokens: part, share, + }) + } + } else { + addModel(models, "", tokens, poolKey, "") + row.models.push({ id: "", name: "", share: 1, tokens }) + pushDetail(modelPoolDetail, "", { + pool: poolKey, provider: group.provider, user: group.user, window: p.label, + remaining: binding ? binding.remaining : 0, resetsAt: shown.resetsAt, poolTokens: tokens, tokens, share: 1, + }) + } + pools.push(row) + } + } + + // 各模型的近期日均消耗,用来折算“还能用多久” + const out = [] + for (const [canon, m] of models) { + const daily = idx.modelDaily.get(canon)?.tokens || 0 + const perDay = daily / 7 + const detail = (modelPoolDetail.get(canon) || []).sort((a, b) => b.tokens - a.tokens) + out.push({ + id: canon, + name: m.display, + tokens: m.tokens, + pools: detail, + dailyTokens: perDay, + days: perDay > 0 ? m.tokens / perDay : null, + }) + } + out.sort((a, b) => b.tokens - a.tokens) + + const totalTokens = out.reduce((s, m) => s + m.tokens, 0) + return { generatedAt: now, totalTokens, models: out, pools, blockedAccounts, skipped } +} + + +function pushDetail(map, canon, entry) { + if (!map.has(canon)) map.set(canon, []) + map.get(canon).push(entry) +} + +function addModel(models, canon, tokens, poolKey, display) { + if (!models.has(canon)) models.set(canon, { tokens: 0, pools: new Map(), display }) + const m = models.get(canon) + m.tokens += tokens + m.pools.set(poolKey, (m.pools.get(poolKey) || 0) + tokens) +} + +function findHistory(history, provider, user) { + const exact = history[`${provider}|${user}`] + if (exact) return exact + const target = `${provider}|${String(user || "").toLowerCase()}` + for (const [k, v] of Object.entries(history)) { + if (k.toLowerCase() === target) return v + } + // 别名差异:同供应商下,用户串互相包含 + const u = String(user || "").toLowerCase() + if (u) { + for (const [k, v] of Object.entries(history)) { + const [p, name] = k.split("|") + if (p !== provider) continue + const n = String(name || "").toLowerCase() + if (n && (u.includes(n) || n.includes(u))) return v + } + } + return null +} + +function findAccountLoose(accounts, provider, user) { + const u = String(user || "").toLowerCase() + for (const [k, v] of accounts) { + const [p, a] = k.split("|") + if (p !== provider) continue + const n = String(a || "").toLowerCase() + if (n && u && (n === u || u.includes(n) || n.includes(u))) return v + } + return null +} diff --git a/packages/page-model-quota/lib/server.mjs b/packages/page-model-quota/lib/server.mjs new file mode 100644 index 0000000..1073992 --- /dev/null +++ b/packages/page-model-quota/lib/server.mjs @@ -0,0 +1,389 @@ +// 页面服务:给窗口里的“模型剩余额度”页提供 /api/report,并托管 ui/。 +// +// 数据全部来自本机 magpie 的配置目录: +// usage.jsonl 逐条请求的 token +// quota-history.json 每个账号每个窗口的剩余百分比读数 +// quotas.json 当前额度快照(网关不可用时的兜底) +// 当前额度优先问网关 GET /v1/magpie/quotas?kept=1,那里带 remaining 与 holds。 + +import { createServer } from "node:http" +import { createHash, randomBytes, timingSafeEqual } from "node:crypto" +import { readFile } from "node:fs/promises" +import { existsSync } from "node:fs" +import { readFileSync, openSync, readSync, closeSync, statSync } from "node:fs" +import { join, extname, isAbsolute } from "node:path" +import { fileURLToPath } from "node:url" +import os from "node:os" +import { buildReport, indexUsage } from "./report.mjs" + +const here = fileURLToPath(new URL(".", import.meta.url)) +const UI_ROOT = join(here, "..", "ui") +const THIS_FILE = fileURLToPath(import.meta.url) + +const MIME = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".svg": "image/svg+xml", + ".json": "application/json; charset=utf-8", +} + +// magpie 的配置目录:便携安装时宿主以配置目录为 cwd 启动服务,所以先看 cwd; +// 其次 XDG_CONFIG_HOME,最后 ~/.config/magpie。MAGPIE_CONFIG_DIR 只作显式覆盖。 +let CONFIG_OVERRIDE = "" +export function configDir() { + if (CONFIG_OVERRIDE) return CONFIG_OVERRIDE + if (process.env.MAGPIE_CONFIG_DIR) return process.env.MAGPIE_CONFIG_DIR + try { + const cwd = process.cwd() + for (const f of ["usage.jsonl", "plugins.json", "providers.json"]) { + if (existsSync(join(cwd, f))) return cwd + } + } catch {} + const xdg = process.env.XDG_CONFIG_HOME + if (xdg && isAbsolute(xdg)) return join(xdg, "magpie") + return join(os.homedir(), ".config", "magpie") +} + +const gatewayBase = () => { + let a = process.env.MAGPIE_ADDR || process.env.MAGPIE_GATEWAY || "127.0.0.1:3425" + if (!/^https?:\/\//i.test(a)) a = "http://" + a + try { + return new URL(a).origin + } catch { + return "http://127.0.0.1:3425" + } +} +const GATEWAY = gatewayBase + +// ---- 数据装载 --------------------------------------------------------------- + +function readJsonSafe(file, fallback) { + try { + return JSON.parse(readFileSync(file, "utf8")) + } catch { + return fallback + } +} + +// 一次读完整份 usage.jsonl,并把字节偏移记下来,之后只读追加的部分。 +function openUsage(file) { + const state = { file, offset: 0, rows: [], shrank: false } + reloadUsage(state) + return state +} + +function reloadUsage(state) { + state.rows = [] + state.offset = 0 + if (!existsSync(state.file)) return + const size = statSync(state.file).size + const fd = openSync(state.file, "r") + try { + const buf = Buffer.alloc(size) + readSync(fd, buf, 0, size, 0) + state.offset = size + for (const line of buf.toString("utf8").split("\n")) { + if (!line.trim()) continue + try { state.rows.push(JSON.parse(line)) } catch { /* 尾行未写完时跳过 */ } + } + } finally { + closeSync(fd) + } +} + +function appendUsage(state) { + if (!existsSync(state.file)) return + const size = statSync(state.file).size + if (size < state.offset) { reloadUsage(state); return } + if (size === state.offset) return + const fd = openSync(state.file, "r") + try { + const len = size - state.offset + const buf = Buffer.alloc(len) + readSync(fd, buf, 0, len, state.offset) + const text = buf.toString("utf8") + const lastNl = text.lastIndexOf("\n") + // 只吸收已经完整成行的部分,剩下的半行下次再读 + const usable = lastNl >= 0 ? text.slice(0, lastNl) : "" + if (usable) { + for (const line of usable.split("\n")) { + if (!line.trim()) continue + try { state.rows.push(JSON.parse(line)) } catch { /* 理论上不会发生 */ } + } + state.offset += Buffer.byteLength(usable, "utf8") + 1 + } + } finally { + closeSync(fd) + } +} + +async function gatewayQuotas() { + const res = await fetch(`${GATEWAY()}/v1/magpie/quotas?kept=1`, { signal: AbortSignal.timeout(8000) }) + if (!res.ok) throw new Error("gateway quota endpoint HTTP " + res.status) + const body = await res.json() + return body.data ?? [] +} + +// quotas.json 兜底:它只有 used,没有 remaining / holds,但足够算百分比。 +function fileQuotas() { + const raw = readJsonSafe(join(configDir(), "quotas.json"), {}) + const out = [] + for (const rec of Object.values(raw)) { + const q = rec?.quota + if (!q || !Array.isArray(q.windows)) continue + out.push({ + provider: q.provider, + name: q.name, + plan: q.plan, + user: q.user, + windows: q.windows.map((w) => ({ + ...w, + remaining: typeof w.remaining === "number" ? w.remaining : Math.max(0, 100 - Number(w.used || 0)), + })), + }) + } + return out +} + +// ---- 报告缓存 --------------------------------------------------------------- + +export function createEngine() { + const dir = configDir() + const usage = openUsage(join(dir, "usage.jsonl")) + let cache = null + let building = null + let lastBuild = 0 + const MAX_AGE = 30 * 1000 + + async function build(force) { + if (!force && cache && Date.now() - lastBuild < MAX_AGE) return cache + if (building) return building + building = (async () => { + appendUsage(usage) + let quotaRecords + let source = "gateway" + let sourceError = "" + try { + quotaRecords = await gatewayQuotas() + } catch (e) { + quotaRecords = fileQuotas() + source = "file" + sourceError = String(e?.message || e) + } + const history = readJsonSafe(join(dir, "quota-history.json"), {}) + const idx = indexUsage(usage.rows, { now: Date.now() }) + const report = buildReport({ quotaRecords, history, usage: idx, now: Date.now() }) + report.source = source + report.sourceError = sourceError + report.usageRows = usage.rows.length + cache = report + lastBuild = Date.now() + return report + })().finally(() => { building = null }) + return building + } + + return { build, usage } +} + +// ---- HTTP ------------------------------------------------------------------- + +const DEFAULT_PORT = 3496 +const PKG = (() => { + try { return JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")) } catch { return {} } +})() +const BUILD_ID = createHash("sha1").update(readFileSync(THIS_FILE)).update(String(PKG.version || "")).digest("hex").slice(0, 10) + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) + +// port: 页面服务的端口,未给则用 DEFAULT_PORT。configDir: magpie 的配置目录。 +export async function startServer({ port, configDir: given } = {}) { + // magpie 在 input.directory 里给出配置目录,便携安装时比 cwd 探测更可靠。 + CONFIG_OVERRIDE = given && existsSync(join(given, "usage.jsonl")) ? given : "" + const engine = createEngine() + // 页面口令:每次启动重新生成,注入到本实例返回的 HTML,不落盘。 + const KEY = randomBytes(24).toString("base64url") + let actualPort = 0 + let OWN = new Set() + let HOSTS = new Set() + + const own = (p) => { + actualPort = p + OWN = new Set([`http://127.0.0.1:${p}`, `http://localhost:${p}`]) + HOSTS = new Set([`127.0.0.1:${p}`, `localhost:${p}`]) + } + + // Host 只认本进程实际监听端口上的 127.0.0.1 和 localhost,挡掉 DNS 重新绑定。 + const hostAllowed = (req) => HOSTS.has(String(req.headers.host || "").toLowerCase()) + // magpie 的插件页面在 sandbox="allow-scripts" 的框架里,导航后仍是 opaque origin, + // 请求带的 Origin 就是字面量 "null"。允许它,但 API 一律要页面口令;其它来源拒绝。 + const originAllowed = (req) => { + const o = req.headers.origin + return o === undefined || o === "null" || OWN.has(o) + } + const corsHeaders = (req) => { + const o = req.headers.origin + const h = { vary: "Origin" } + if (o === "null") h["access-control-allow-origin"] = "null" + else if (o && OWN.has(o)) h["access-control-allow-origin"] = o + return h + } + const send = (res, status, body, type = "application/json; charset=utf-8", withCors = true) => { + const data = typeof body === "string" || body instanceof Uint8Array ? body : JSON.stringify(body) + res.writeHead(status, { + "content-type": type, + "cache-control": "no-store", + ...(withCors ? corsHeaders(res.req) : {}), + "x-content-type-options": "nosniff", + }) + res.end(data) + } + const keyOK = (req) => { + const got = Buffer.from(String(req.headers["x-magpie-quota-key"] || "")) + const want = Buffer.from(KEY) + return got.length === want.length && timingSafeEqual(got, want) + } + + const server = createServer(async (req, res) => { + const url = new URL(req.url || "/", "http://127.0.0.1:" + (actualPort || DEFAULT_PORT)) + const pathname = url.pathname + if (process.env.MAGPIE_QUOTA_DEBUG && pathname.startsWith("/api/")) { + console.log(`[model-quota] ${req.method} ${pathname} host=${req.headers.host || "-"} origin=${req.headers.origin || "-"} key=${req.headers["x-magpie-quota-key"] ? "yes" : "no"}`) + } + if (!hostAllowed(req)) return send(res, 403, { error: "invalid host" }, undefined, false) + if (!originAllowed(req)) return send(res, 403, { error: "cross-origin reads are not allowed" }) + if (req.method === "OPTIONS") { + res.writeHead(204, { + ...corsHeaders(req), + "access-control-allow-methods": "GET,POST,OPTIONS", + "access-control-allow-headers": "content-type, x-magpie-quota-key", + "access-control-max-age": "86400", + }) + return res.end() + } + try { + if (pathname === "/api/ping") { + return send(res, 200, { ok: true, service: "magpie-model-quota", build: BUILD_ID, port: actualPort }) + } + if (pathname.startsWith("/api/")) { + if (!keyOK(req)) return send(res, 401, { error: "unauthorized: send the x-magpie-quota-key header" }) + if (pathname === "/api/report") { + const report = await engine.build(req.method === "POST") + return send(res, 200, report) + } + return send(res, 404, { error: "not found" }) + } + + // 静态资源 + const rel = pathname === "/" ? "index.html" : pathname.replace(/^\//, "") + const file = join(UI_ROOT, rel) + if (!file.startsWith(UI_ROOT)) return send(res, 403, { error: "forbidden" }, undefined, false) + const data = await readFile(file).catch(() => null) + if (!data) return send(res, 404, "not found", "text/plain; charset=utf-8", false) + const type = MIME[extname(file).toLowerCase()] || "application/octet-stream" + if (rel === "index.html") { + // 只把注入了口令的 HTML 交给“导航”;跨源 fetch 拿不到它,也就拿不到口令。 + const mode = String(req.headers["sec-fetch-mode"] || "") + if (mode && mode !== "navigate") return send(res, 403, { error: "cross-origin page read not allowed" }, undefined, false) + const html = data.toString("utf8").replace("", `\n`) + return send(res, 200, html, type, false) + } + return send(res, 200, data, type, false) + } catch (err) { + if (res.headersSent) { try { res.end() } catch {} return } + return send(res, 500, { error: String(err?.message || err) }) + } + }) + + // 端口:调用方给的值 → 环境变量 → 默认 3496。页面从同一份 options 读,保证一致。 + const rawWant = port ?? process.env.MAGPIE_MODEL_QUOTA_PORT + let target = DEFAULT_PORT + if (rawWant !== undefined && rawWant !== null && rawWant !== "" && Number.isFinite(Number(rawWant))) { + const n = Number(rawWant) + if (Number.isInteger(n) && n >= 0 && n <= 65535) target = n + } + + const probe = async (port) => { + try { + const r = await fetch(`http://127.0.0.1:${port}/api/ping`, { signal: AbortSignal.timeout(800) }) + if (!r.ok) return null + const j = await r.json() + return j && j.service === "magpie-model-quota" ? j : null + } catch { + return null + } + } + + const bindOnce = (p) => new Promise((resolve, reject) => { + const cleanup = () => { server.removeListener("listening", onOk); server.removeListener("error", onErr) } + const onOk = () => { cleanup(); own(server.address().port); resolve(true) } + const onErr = (e) => { + cleanup() + // 端口被占/无权限 → 交给上层重试;其它错误直接失败 + if (e.code !== "EADDRINUSE" && e.code !== "EACCES") reject(e) + else resolve(false) + } + server.once("listening", onOk) + server.once("error", onErr) + server.listen(p, "127.0.0.1") + }) + + // 旧实例(上一个版本或上一个宿主)还占着端口时,先复用它,保证 magpie 能在 + // 它自己的 20 秒加载窗口内成功;同时后台等它退出,再由新实例接管同一个端口。 + const takeover = (p) => { + ;(async () => { + for (;;) { + await sleep(1000) + try { + if (await bindOnce(p)) { + console.log(`[model-quota] took over ${p} with build ${BUILD_ID}`) + return + } + } catch (e) { + console.log(`[model-quota] takeover failed: ${e.code || e.message}`) + return + } + } + })() + } + const reused = (p) => ({ port: p, listening: false, reused: true, server, close: async () => { if (server.listening) server.close() } }) + + const deadline = Date.now() + 20000 + let foreignSince = 0 + for (;;) { + if (await bindOnce(target)) break + const st = await probe(target) + if (st) { + if (st.build === BUILD_ID) { + // 濒死实例也能应答一次;1.5 秒后仍活着才复用 + await sleep(1500) + const again = await probe(target) + if (again && again.build === BUILD_ID) { + own(target) + console.log(`[model-quota] ${target} already served by the same build, reusing it`) + takeover(target) + return reused(target) + } + continue + } + own(target) + console.log(`[model-quota] ${target} is served by build ${st.build}; reusing it until it exits`) + takeover(target) + return reused(target) + } + // 端口上没有我们的服务:可能是别的程序,短暂重试后直接报错 + if (!foreignSince) foreignSince = Date.now() + if (Date.now() - foreignSince > 4000) { + throw new Error(`port ${target} is in use by another program — free it or set the plugin's port option`) + } + if (Date.now() >= deadline) { + throw new Error(`port ${target} is not available — free it or set the plugin's port option`) + } + await sleep(150) + } + + console.log(`[model-quota] listening on http://127.0.0.1:${actualPort}`) + return { port: actualPort, listening: true, reused: false, server, close: async () => { if (server.listening) server.close() } } +} + diff --git a/packages/page-model-quota/package.json b/packages/page-model-quota/package.json new file mode 100644 index 0000000..1beb73e --- /dev/null +++ b/packages/page-model-quota/package.json @@ -0,0 +1,69 @@ +{ + "name": "@magpie-community/page-model-quota", + "version": "0.1.0", + "description": "把所有账号、所有供应商的额度窗口换算成 token,按模型合并估算还剩多少。A page in Magpie's window that estimates how many tokens each model has left, merged across every account and provider, from the local usage history.", + "type": "module", + "main": "./index.mjs", + "files": [ + "index.mjs", + "serve.mjs", + "lib", + "page", + "ui", + "assets", + "LICENSE", + "README.md" + ], + "scripts": { + "start": "node serve.mjs", + "test": "node --test test/*.test.mjs" + }, + "engines": { + "magpie": ">=0.1.1340" + }, + "keywords": [ + "magpie", + "magpie-page", + "magpie-plugin", + "quota", + "usage", + "tokens", + "models" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/page-model-quota" + }, + "homepage": "https://github.com/magpie-community/plugins/tree/main/packages/page-model-quota", + "bugs": { + "url": "https://github.com/magpie-community/plugins/issues" + }, + "magpie": { + "name": "Model Quota", + "summary": { + "en": "How many tokens each model has left, merged across every account and provider: each quota window is turned into tokens from your own usage history and split by the model's share in it.", + "zh": "每个模型在所有账号、所有供应商的池子里还剩多少 token:用你自己的用量历史把每个额度窗口换算成 token,再按模型在窗口里的占比摊开。" + }, + "page": { + "title": "Model Quota", + "titles": { + "en": "Model Quota", + "zh": "模型剩余额度", + "zh-TW": "模型剩餘額度" + }, + "file": "page/index.html", + "icon": "page/icon.svg", + "service": { + "port": 3496, + "option": "port" + } + }, + "options": { + "port": 3496 + }, + "permissions": [], + "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTQiIGZpbGw9IiMwZjE3MmEiLz48ZyBmaWxsPSJub25lIiBzdHJva2U9IiMzOGJkZjgiIHN0cm9rZS13aWR0aD0iNCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIj48cGF0aCBkPSJNMTQgMjJoMzZNMTQgMzJoMzZNMTQgNDJoMjIiLz48L2c+PC9zdmc+" + } +} diff --git a/packages/page-model-quota/page/boot.js b/packages/page-model-quota/page/boot.js new file mode 100644 index 0000000..f37340b --- /dev/null +++ b/packages/page-model-quota/page/boot.js @@ -0,0 +1,121 @@ +// 带路页:把 magpie 的框架导航到本插件的页面服务。 +// 页面 CSP 是 connect-src 'none',只能直接跳转,不能先探测。 +(async () => { + const DEFAULT_PORT = 3496; + const words = { + en: { + title: "Model Quota", + connecting: "Connecting to the local quota service...", + stopped: (port) => `The local quota service is not running (127.0.0.1:${port}).`, + remote: (port) => `The service listens on 127.0.0.1:${port} on the machine running magpie. Open the page there, or forward that port.`, + retry: "Retry", + }, + zh: { + title: "模型剩余额度", + connecting: "正在连接本地额度服务…", + stopped: (port) => `本地额度服务没有在运行(127.0.0.1:${port})。`, + remote: (port) => `服务只在运行 magpie 的那台机器上监听 127.0.0.1:${port},请在本机打开或做端口转发。`, + retry: "重试", + }, + }; + + let port = DEFAULT_PORT; + let theme = "light"; + let lang = "en"; + let tokens = null; + let service = ""; + + function followLanguage(value) { + lang = String(value || "").toLowerCase().startsWith("zh") ? "zh" : "en"; + const text = words[lang]; + document.documentElement.lang = lang === "zh" ? "zh-CN" : "en"; + document.title = text.title; + document.getElementById("title").textContent = text.title; + document.getElementById("said").textContent = text.connecting; + document.getElementById("retry").textContent = text.retry; + } + + try { + const current = await window.magpie?.ready; + if (current) { + theme = current.dark ? "dark" : "light"; + lang = String(current.lang || lang).toLowerCase().startsWith("zh") ? "zh" : "en"; + tokens = current.tokens || null; + } + } catch { + // 没有桥接时页面照样能用。 + } + + try { + const options = await window.magpie?.options?.get?.(); + const value = Number(options?.port); + if (Number.isInteger(value) && value > 0 && value < 65536) port = value; + } catch { + // 用声明的默认值。 + } + + try { + const value = window.magpie?.service; + if (typeof value === "string" && /^https?:\/\//.test(value)) service = value; + } catch { + // 桌面窗口直接导航到回环地址。 + } + + followLanguage(lang); + window.magpie?.onTheme?.((next) => { + if (!next) return; + if (typeof next.dark === "boolean") theme = next.dark ? "dark" : "light"; + if (typeof next.lang === "string") { + const before = lang; + followLanguage(next.lang); + // 框架马上要被替换,只更新等待文字。 + if (before !== lang) { + const retry = document.getElementById("retry"); + if (retry && !retry.hidden) retry.textContent = words[lang].retry; + } + } + }); + + const query = new URLSearchParams(); + query.set("theme", theme); + query.set("lang", lang); + // 每次打开都换一个地址,浏览器不会拿缓存里的旧文档(旧口令)来用。 + query.set("_", String(Date.now())); + if (tokens && typeof tokens === "object") { + try { + const slim = {}; + for (const [key, value] of Object.entries(tokens)) { + const text = String(value ?? "").trim(); + if (text) slim[key] = text; + } + if (Object.keys(slim).length) { + query.set("tokens", btoa(unescape(encodeURIComponent(JSON.stringify(slim))))); + } + } catch { + // 主题色带不过去就用页面自己的。 + } + } + + const retry = document.getElementById("retry"); + retry.hidden = false; + retry.addEventListener("click", () => location.reload()); + + if (service) { + location.replace(service + "?" + query.toString()); + return; + } + + const host = String(location.hostname || "").toLowerCase().replace(/^\[|\]$/g, ""); + const local = !host || host === "localhost" || host.endsWith(".localhost") || host === "::1" || /^127\./.test(host); + if (!local) { + document.getElementById("said").textContent = words[lang].remote(port); + return; + } + + // 服务没起来时,跳转过去只会看到空白:五秒后把原因写回这一页。 + const timer = setTimeout(() => { + if (document.getElementById("said")) document.getElementById("said").textContent = words[lang].stopped(port); + }, 5000); + location.replace("http://127.0.0.1:" + port + "/?" + query.toString()); + void timer; +})(); diff --git a/packages/page-model-quota/page/icon.svg b/packages/page-model-quota/page/icon.svg new file mode 100644 index 0000000..b6e6325 --- /dev/null +++ b/packages/page-model-quota/page/icon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/packages/page-model-quota/page/index.html b/packages/page-model-quota/page/index.html new file mode 100644 index 0000000..c734981 --- /dev/null +++ b/packages/page-model-quota/page/index.html @@ -0,0 +1,38 @@ + + + + + + Model Quota + + + +
+ Model Quota +
Connecting to the local quota service...
+ +
+ + + + diff --git a/packages/page-model-quota/serve.mjs b/packages/page-model-quota/serve.mjs new file mode 100644 index 0000000..5bf109e --- /dev/null +++ b/packages/page-model-quota/serve.mjs @@ -0,0 +1,11 @@ +// 手动起服务用:node serve.mjs [--port 3496] +import { startServer } from "./lib/server.mjs"; + +const arg = (name, fallback) => { + const i = process.argv.indexOf(`--${name}`); + return i > 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback; +}; + +const value = Number(arg("port", process.env.MAGPIE_MODEL_QUOTA_PORT || 3496)); +const info = await startServer({ port: Number.isInteger(value) && value > 0 ? value : 3496 }); +console.log(`[model-quota] listening on http://127.0.0.1:${info.port}`); diff --git a/packages/page-model-quota/test/i18n.test.mjs b/packages/page-model-quota/test/i18n.test.mjs new file mode 100644 index 0000000..ef759b1 --- /dev/null +++ b/packages/page-model-quota/test/i18n.test.mjs @@ -0,0 +1,45 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +const dir = join(import.meta.dirname, ".."); +const read = (file) => readFileSync(join(dir, file), "utf8"); + +// 报表里只放语言无关的值,词由页面按语言给出。中文出现在报表里, +// 英文页面就会显示中文。 +test("the report carries no prose for the page to print", () => { + const source = read("lib/report.mjs"); + const code = source + .split("\n") + .filter((line) => !/^\s*(\/\/|\*)/.test(line)) + .join("\n"); + // 双引号字符串和模板字符串都要查:任何一种带上中文,英文页面就会显示中文。 + const literals = [ + ...[...code.matchAll(/"([^"\\\n]*[\u4e00-\u9fff][^"\\\n]*)"/g)].map((m) => m[1]), + ...[...code.matchAll(/`([^`\\\n]*[\u4e00-\u9fff][^`\\\n]*)`/g)].map((m) => m[1]), + ]; + // 只有识别窗口名字用的正则里允许中文,字符串字面量一个都不该有。 + assert.deepEqual(literals, []); +}); + +test("an unassigned model and an account with no user have no words in them", () => { + const source = read("lib/report.mjs"); + assert.match(source, /addModel\(models, "", tokens, poolKey, ""\)/); + assert.doesNotMatch(source, /未分模型/); + assert.doesNotMatch(source, /无账号/); + assert.match(source, /group\.user \? `\$\{group\.provider\}\/\$\{group\.user\}·\$\{p\.label\}` : `\$\{group\.provider\}·\$\{p\.label\}`/); +}); + +test("the low-confidence word brings its own brackets", () => { + const app = read("ui/app.js"); + assert.match(app, /historical: " \(from past rounds\)"/); + assert.match(app, /historical: "(按历史轮次估)"/); + assert.match(app, /fmtTokens\(pool\.tokens\) \+ t\.historical/); + assert.doesNotMatch(app, /"(" \+ t\.historical/); +}); + +test("the page declares its own language", () => { + const app = read("ui/app.js"); + assert.match(app, /document\.documentElement\.lang = lang === "zh" \? "zh-CN" : "en"/); +}); diff --git a/packages/page-model-quota/test/page.test.mjs b/packages/page-model-quota/test/page.test.mjs new file mode 100644 index 0000000..98252ef --- /dev/null +++ b/packages/page-model-quota/test/page.test.mjs @@ -0,0 +1,47 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; + +const dir = join(import.meta.dirname, ".."); +const pageDir = join(dir, "page"); +const read = (base, file) => readFileSync(join(base, file), "utf8"); +const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + +test("the launcher reads nothing of magpie and reaches no network", () => { + assert.deepEqual(pkg.magpie.permissions ?? [], []); + const reads = new Set(); + for (const file of readdirSync(pageDir).filter((f) => f.endsWith(".js"))) { + const source = read(pageDir, file); + for (const match of source.matchAll(/magpie\.read\(\s*"([^"]+)"/g)) reads.add(match[1]); + // 页面的 CSP 是 connect-src 'none',magpie 也会拒绝这些调用。 + assert.doesNotMatch(source, /\bfetch\(|XMLHttpRequest|WebSocket|sendBeacon|EventSource|importScripts/); + } + assert.deepEqual([...reads], []); +}); + +test("the launcher navigates instead of probing", () => { + const boot = read(pageDir, "boot.js"); + assert.match(boot, /window\.magpie\?\.service/); + assert.match(boot, /location\.replace/); + assert.doesNotMatch(boot, /\bfetch\(/); +}); + +test("plugin metadata speaks Chinese and English", () => { + assert.equal(pkg.magpie.name, "Model Quota"); + assert.equal(pkg.magpie.page.titles.zh, "模型剩余额度"); + assert.equal(pkg.magpie.page.titles.en, "Model Quota"); + assert.match(pkg.magpie.summary.zh, /额度窗口/); + assert.match(pkg.magpie.summary.en, /quota window/); + assert.match(pkg.description, /A page in Magpie's window/); + const readme = read(dir, "README.md"); + assert.match(readme, /magpie plugin add @magpie-community\/page-model-quota/); + assert.match(readme, /## 中文说明/); +}); + +test("the declared port is the one the page falls back to", () => { + const boot = read(pageDir, "boot.js"); + const declared = pkg.magpie.page.service.port; + assert.equal(pkg.magpie.options.port, declared); + assert.match(boot, new RegExp(`const DEFAULT_PORT = ${declared}`)); +}); diff --git a/packages/page-model-quota/test/quota.test.mjs b/packages/page-model-quota/test/quota.test.mjs new file mode 100644 index 0000000..3a94f1f --- /dev/null +++ b/packages/page-model-quota/test/quota.test.mjs @@ -0,0 +1,159 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import http from "node:http"; + +import { canonModel, cleanModelName, classifyWindow, periodHours, tokensOf } from "../lib/report.mjs"; +import { startServer } from "../lib/server.mjs"; + +// 测试不去问真实的网关:指向一个没人监听的端口,额度就取自 quotas.json。 +process.env.MAGPIE_ADDR = "127.0.0.1:1"; + +test("model names merge across context suffixes", () => { + assert.equal(cleanModelName("grok-4.7@500k"), "grok-4.7"); + assert.equal(cleanModelName("grok-4.7@256k"), "grok-4.7"); + assert.equal(canonModel("grok-4.7@500k"), canonModel("grok-4.7@256k")); + assert.equal(canonModel("GLM-5.3-Flash"), canonModel("glm-5.3-flash")); +}); + +test("a window is classified by its name", () => { + assert.equal(classifyWindow("5 hours"), "rate"); + assert.equal(classifyWindow("Weekly"), "rate"); + assert.equal(classifyWindow("Total credits"), "aggregate"); + assert.equal(classifyWindow("Extra credits"), "credit"); + assert.equal(classifyWindow("deepseek-v4.1-flash tokens (est.)"), "token"); +}); + +test("a window's period decides which one is the allowance", () => { + assert.equal(periodHours("5 hours"), 5); + assert.equal(periodHours("7 days"), 168); + assert.equal(periodHours("Month"), 720); + assert.ok(periodHours("Month") > periodHours("7 days")); +}); + +test("tokens count every field", () => { + assert.equal(tokensOf({ in: 10, out: 5, cache_read: 3, cache_write: 2, reasoning: 1 }), 21); +}); + +// 最小的配置目录:一个账号、一个 5 小时窗口、一轮读数、同期用量。 +function fixture() { + const dir = mkdtempSync(join(tmpdir(), "model-quota-")); + const hour = 3600 * 1000; + const base = Date.parse("2026-11-10T00:00:00Z"); + const at = (h) => new Date(base + h * hour).toISOString(); + + const usage = []; + for (let i = 0; i < 40; i++) { + usage.push({ + t: at(0.5 + i * 0.1), + provider: "acme", + providerAccount: "a@example.com", + model: "acme-large@500k", + in: 1000, + out: 1000, + cache_read: 0, + cache_write: 0, + reasoning: 0, + }); + } + writeFileSync(join(dir, "usage.jsonl"), usage.map((row) => JSON.stringify(row)).join("\n") + "\n"); + writeFileSync( + join(dir, "quota-history.json"), + JSON.stringify({ + "acme|a@example.com": { + "5 hours": [ + { at: at(0), left: 100, start: at(0) }, + { at: at(4), left: 90, start: at(0) }, + ], + }, + }), + ); + writeFileSync( + join(dir, "quotas.json"), + JSON.stringify({ + "acme|a@example.com": { + quota: { + provider: "acme", + name: "Acme", + plan: "Pro", + user: "a@example.com", + windows: [{ name: "5 hours", used: 20, remaining: 80, resetsAt: at(5) }], + }, + }, + }), + ); + return dir; +} + +const get = (port, path, headers = {}) => + new Promise((resolve, reject) => { + const req = http.request({ host: "127.0.0.1", port, path, method: "GET", headers }, (res) => { + let body = ""; + res.on("data", (chunk) => (body += chunk)); + res.on("end", () => resolve({ status: res.statusCode, body, headers: res.headers })); + }); + req.on("error", reject); + req.end(); + }); + +test("the service guards its report and splits tokens by model", async () => { + const dir = fixture(); + const info = await startServer({ port: 0, configDir: dir }); + try { + const page = await get(info.port, "/", { host: `127.0.0.1:${info.port}`, "sec-fetch-mode": "navigate" }); + assert.equal(page.status, 200); + const key = /name="magpie-quota-key" content="([^"]+)"/.exec(page.body)?.[1]; + assert.ok(key, "the page carries its key"); + + // 跨源抓页面拿不到口令。 + const grabbed = await get(info.port, "/", { + host: `127.0.0.1:${info.port}`, + "sec-fetch-mode": "cors", + origin: "null", + }); + assert.equal(grabbed.status, 403); + + // 没有口令读不到报表。 + const denied = await get(info.port, "/api/report", { host: `127.0.0.1:${info.port}`, origin: "null" }); + assert.equal(denied.status, 401); + + // 沙盒框架的 Origin: null 带着口令可以读。 + const allowed = await get(info.port, "/api/report", { + host: `127.0.0.1:${info.port}`, + origin: "null", + "x-magpie-quota-key": key, + }); + assert.equal(allowed.status, 200); + assert.equal(allowed.headers["access-control-allow-origin"], "null"); + + const report = JSON.parse(allowed.body); + assert.equal(report.pools.length, 1); + assert.equal(report.pools[0].remaining, 80); + assert.equal(report.models.length, 1); + // 显示名去掉上下文后缀,同一个模型的不同容量归到一起。 + assert.equal(report.models[0].name, "acme-large"); + assert.ok(report.models[0].tokens > 0); + } finally { + await info.close(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("another host name or origin is refused", async () => { + const dir = fixture(); + const info = await startServer({ port: 0, configDir: dir }); + try { + const wrongHost = await get(info.port, "/api/report", { host: `attacker.localhost:${info.port}` }); + assert.equal(wrongHost.status, 403); + const otherOrigin = await get(info.port, "/api/report", { + host: `127.0.0.1:${info.port}`, + origin: "http://localhost:9999", + }); + assert.equal(otherOrigin.status, 403); + } finally { + await info.close(); + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/page-model-quota/ui/app.js b/packages/page-model-quota/ui/app.js new file mode 100644 index 0000000..d15309d --- /dev/null +++ b/packages/page-model-quota/ui/app.js @@ -0,0 +1,359 @@ +// 页面逻辑:读 api/report,渲染按模型汇总的剩余 token。 +const query = new URLSearchParams(location.search); +const theme = query.get("theme"); +if (theme === "dark" || theme === "light") document.documentElement.dataset.theme = theme; + +const KEY = document.querySelector('meta[name="magpie-quota-key"]')?.content || ""; +const expanded = new Set(); + +const words = { + en: { + heading: "Model quota", + sub: "Every quota window of every account and provider, turned into tokens and merged by model", + refresh: "Refresh", + refreshing: "Refreshing…", + connecting: "Connecting to the service…", + total: "Tokens left", + totalNote: (n) => `${n} models`, + models: "Models", + modelsNote: "with a quota window to estimate from", + pools: "Quota windows", + poolsNote: "counted once each", + model: "Model", + tokens: "Tokens left", + share: "Share", + daily: "Daily use", + lasts: "Lasts", + poolCount: "Windows", + windows: "Quota windows", + window: "Window", + remaining: "Left", + tpp: "Per 1%", + poolTokens: "Tokens left", + roundDrop: "Used this round", + roundCalls: "Records", + reset: "Resets", + detailWindow: "Quota window", + detailPart: "To this model", + detailShare: "Its share", + detailPool: "Window left", + unassigned: "(no model split)", + emptyModels: "No quota window can be estimated yet. Let magpie record some usage, or wait until a window has a few readings.", + emptyPools: "No quota window can be estimated yet.", + exhausted: (w) => `Exhausted (${w})`, + historical: " (from past rounds)", + hoursUnit: "h", + daysUnit: "d", + over: "> 1000 d", + updated: (t) => `Updated ${t}`, + failed: (m) => `Failed to load: ${m}`, + note: + "Tokens are input + output + cache reads + cache writes + reasoning. A window's tokens per 1% come from its own history: the tokens an account spent over a drop in its remaining percentage. Tokens left = remaining percentage × that, split by each model's share inside the window.", + noteSkipped: (parts) => ` Not counted: ${parts.join("; ")}.`, + noteFile: " Current quota came from the local snapshot; the gateway did not answer.", + noteSource: "Source: magpie's usage.jsonl and quota-history.json; current quota from the gateway's /v1/magpie/quotas.", + blocked: (n) => `${n} windows are exhausted, so their accounts are left out`, + lowConfidence: (n) => `${n} windows have few records and are estimated from past rounds`, + noHistory: (n) => `${n} windows have no readings yet`, + noUsage: (n) => `${n} windows have no usage to line up with`, + }, + zh: { + heading: "模型剩余额度", + sub: "把所有账号、所有供应商的额度窗口换算成 token,按模型合并", + refresh: "刷新", + refreshing: "刷新中…", + connecting: "正在连接服务…", + total: "合计剩余", + totalNote: (n) => `覆盖 ${n} 个模型`, + models: "覆盖模型", + modelsNote: "有可估算额度窗口的模型", + pools: "覆盖额度池", + poolsNote: "每个窗口只计一次", + model: "模型", + tokens: "剩余 token", + share: "占比", + daily: "日均消耗", + lasts: "预计可用", + poolCount: "池数", + windows: "额度窗口", + window: "窗口", + remaining: "剩余", + tpp: "每 1% 约合", + poolTokens: "剩余 token", + roundDrop: "本轮已用", + roundCalls: "本轮记录", + reset: "重置", + detailWindow: "额度窗口", + detailPart: "摊到本模型", + detailShare: "本模型占比", + detailPool: "窗口剩余", + unassigned: "(未分模型)", + emptyModels: "还没有可估算的额度窗口。先让 magpie 记录一些用量,或等额度读数攒够几个点。", + emptyPools: "没有可估算的额度窗口。", + exhausted: (w) => `已用完(${w})`, + historical: "(按历史轮次估)", + hoursUnit: "小时", + daysUnit: "天", + over: "> 1000 天", + updated: (t) => `更新于 ${t}`, + failed: (m) => `加载失败:${m}`, + note: + "口径:token = 输入 + 输出 + 缓存读 + 缓存写 + 推理。每个窗口的“每 1% 值多少 token”由它自己的历史推得:账号在剩余百分比下降期间消耗的 token 除以掉掉的百分比。剩余 token = 剩余百分比 × 该值,再按窗口内各模型的占比摊开。", + noteSkipped: (parts) => ` 未计入:${parts.join(";")}。`, + noteFile: " 当前额度取自本地快照,网关没有应答。", + noteSource: "数据源:magpie 的 usage.jsonl 与 quota-history.json;当前额度来自网关的 /v1/magpie/quotas。", + blocked: (n) => `${n} 个窗口已用完,所在账号不计入`, + lowConfidence: (n) => `${n} 个窗口记录不足,按历史轮次估算`, + noHistory: (n) => `${n} 个窗口还没有读数`, + noUsage: (n) => `${n} 个窗口没有可对齐的用量记录`, + }, +}; + +const lang = String(query.get("lang") || navigator.language || "en").toLowerCase().startsWith("zh") ? "zh" : "en"; +const t = words[lang]; +const locale = lang === "zh" ? "zh-CN" : "en-US"; + +const $ = (id) => document.getElementById(id); + +function fmtTokens(n) { + if (!Number.isFinite(n)) return "—"; + if (lang === "zh") { + if (n >= 1e8) return (n / 1e8).toFixed(2) + " 亿"; + if (n >= 1e4) return (n / 1e4).toFixed(1) + " 万"; + return Math.round(n).toLocaleString(locale); + } + if (n >= 1e9) return (n / 1e9).toFixed(2) + "B"; + if (n >= 1e6) return (n / 1e6).toFixed(1) + "M"; + if (n >= 1e4) return (n / 1e3).toFixed(1) + "K"; + return Math.round(n).toLocaleString(locale); +} + +function fmtDays(d) { + if (d == null || !Number.isFinite(d)) return "—"; + if (d < 1) return (d * 24).toFixed(1) + " " + t.hoursUnit; + if (d < 1000) return d.toFixed(1) + " " + t.daysUnit; + return t.over; +} + +function fmtTime(ts) { + if (!ts) return ""; + return new Date(ts).toLocaleString(locale, { hour12: false }); +} + +function el(tag, cls, text) { + const node = document.createElement(tag); + if (cls) node.className = cls; + if (text != null) node.textContent = text; + return node; +} + +function labels() { + $("heading").textContent = t.heading; + $("subheading").textContent = t.sub; + $("refresh").textContent = t.refresh; + $("label-total").textContent = t.total; + $("label-models").textContent = t.models; + $("note-models").textContent = t.modelsNote; + $("label-pools").textContent = t.pools; + $("pool-note").textContent = t.poolsNote; + $("th-model").textContent = t.model; + $("th-tokens").textContent = t.tokens; + $("th-share").textContent = t.share; + $("th-daily").textContent = t.daily; + $("th-days").textContent = t.lasts; + $("th-pools").textContent = t.poolCount; + $("pool-title").textContent = t.windows; + $("th-window").textContent = t.window; + $("th-remaining").textContent = t.remaining; + $("th-tpp").textContent = t.tpp; + $("th-pool-tokens").textContent = t.poolTokens; + $("th-round-drop").textContent = t.roundDrop; + $("th-round-calls").textContent = t.roundCalls; + $("th-reset").textContent = t.reset; + document.title = t.heading; + document.documentElement.lang = lang === "zh" ? "zh-CN" : "en"; +} + +function render(report) { + $("total").textContent = fmtTokens(report.totalTokens); + $("total-note").textContent = t.totalNote(report.models.length); + $("modelCount").textContent = String(report.models.length); + $("poolCount").textContent = String(report.pools.length); + $("stamp").textContent = t.updated(new Date(report.generatedAt).toLocaleTimeString(locale, { hour12: false })); + + const tbody = $("rows"); + tbody.innerHTML = ""; + const total = report.totalTokens || 1; + + const empty = $("empty"); + empty.hidden = report.models.length > 0; + if (!report.models.length) empty.textContent = t.emptyModels; + + for (const model of report.models) { + const row = el("tr", "model-row"); + row.dataset.id = model.id; + + const cell = el("td", "col-model"); + const name = el("div", "model-name"); + name.appendChild(el("span", "dot")); + name.appendChild(el("span", "nm", model.name || model.id || t.unassigned)); + cell.appendChild(name); + const bar = el("div", "bar"); + const fill = el("i"); + fill.style.width = Math.max(1, Math.min(100, (model.tokens / total) * 100)) + "%"; + bar.appendChild(fill); + cell.appendChild(bar); + row.appendChild(cell); + + row.appendChild(el("td", "num", fmtTokens(model.tokens))); + row.appendChild(el("td", "num", ((model.tokens / total) * 100).toFixed(1) + "%")); + row.appendChild(el("td", "num", model.dailyTokens > 0 ? fmtTokens(model.dailyTokens) : "—")); + const days = el("td", "num", fmtDays(model.days)); + if (model.days != null && model.days < 1) days.classList.add("warn"); + row.appendChild(days); + row.appendChild(el("td", "num", String((model.pools || []).length))); + + row.addEventListener("click", () => { + if (expanded.has(model.id)) expanded.delete(model.id); + else expanded.add(model.id); + render(report); + }); + tbody.appendChild(row); + + if (!expanded.has(model.id)) continue; + + const detailRow = el("tr", "detail-row"); + const detailCell = el("td"); + detailCell.colSpan = 6; + const box = el("div", "detail"); + const table = el("table"); + const head = el("thead"); + const headRow = el("tr"); + headRow.appendChild(el("th", null, t.detailWindow)); + headRow.appendChild(el("th", "num", t.detailPart)); + headRow.appendChild(el("th", "num", t.detailShare)); + headRow.appendChild(el("th", "num", t.detailPool)); + head.appendChild(headRow); + table.appendChild(head); + const body = el("tbody"); + for (const pool of model.pools || []) { + const detail = el("tr"); + detail.appendChild(el("td", null, pool.pool)); + detail.appendChild(el("td", "num", fmtTokens(pool.tokens))); + detail.appendChild(el("td", "num", pool.share != null ? (pool.share * 100).toFixed(1) + "%" : "—")); + detail.appendChild(el("td", "num", fmtTokens(pool.poolTokens))); + body.appendChild(detail); + } + table.appendChild(body); + box.appendChild(table); + detailCell.appendChild(box); + detailRow.appendChild(detailCell); + tbody.appendChild(detailRow); + } + + const poolBody = $("poolRows"); + poolBody.innerHTML = ""; + const pools = (report.pools || []).slice().sort((a, b) => b.tokens - a.tokens); + const poolEmpty = $("poolEmpty"); + poolEmpty.hidden = pools.length > 0; + if (!pools.length) poolEmpty.textContent = t.emptyPools; + + for (const pool of pools) { + const row = el("tr"); + row.appendChild(el("td", "col-model", pool.pool)); + row.appendChild(el("td", "num", Number(pool.remaining).toFixed(1) + "%")); + row.appendChild(el("td", "num", pool.tpp ? fmtTokens(pool.tpp) : "—")); + const tokens = el("td", "num"); + if (pool.blocked) tokens.textContent = t.exhausted(pool.blockedBy || ""); + else if (pool.lowConfidence) tokens.textContent = fmtTokens(pool.tokens) + t.historical; + else tokens.textContent = fmtTokens(pool.tokens); + if (pool.blocked) tokens.classList.add("warn"); + row.appendChild(tokens); + row.appendChild(el("td", "num", pool.roundDrop != null ? pool.roundDrop.toFixed(0) + "%" : "—")); + row.appendChild(el("td", "num", pool.roundCalls != null ? String(pool.roundCalls) : "—")); + row.appendChild(el("td", "num", pool.resetsAt ? fmtTime(pool.resetsAt) : "—")); + poolBody.appendChild(row); + } + + const skipped = report.skipped || {}; + const blocked = (report.pools || []).filter((p) => p.blocked).length; + const lowConfidence = (report.pools || []).filter((p) => p.lowConfidence).length; + const parts = []; + if (blocked) parts.push(t.blocked(blocked)); + if (lowConfidence) parts.push(t.lowConfidence(lowConfidence)); + if (skipped.noHistory) parts.push(t.noHistory(skipped.noHistory)); + if (skipped.noUsage) parts.push(t.noUsage(skipped.noUsage)); + + const note = $("note"); + note.textContent = + t.note + (parts.length ? t.noteSkipped(parts) : "") + (report.source === "file" ? t.noteFile : ""); + note.appendChild(document.createElement("br")); + note.appendChild(el("span", null, t.noteSource)); +} + +async function load(force, attempt = 0) { + const button = $("refresh"); + button.disabled = true; + button.textContent = t.refreshing; + try { + const suffix = force ? "?force=1" : ""; + const init = { method: force ? "POST" : "GET", headers: { "x-magpie-quota-key": KEY } }; + // 直接访问时两种写法等价;经 magpie 的 service 代理、页面挂在子路径下时, + // 只有相对路径会带上代理前缀,所以先用相对路径,404 再退回根路径。 + let res; + try { + res = await fetch("api/report" + suffix, init); + if (res.status === 404) res = await fetch("/api/report" + suffix, init); + } catch { + res = await fetch("/api/report" + suffix, init); + } + if (!res.ok) { + const body = await res.json().catch(() => ({})); + const error = new Error(body.error || "HTTP " + res.status); + error.http = true; + error.status = res.status; + throw error; + } + render(await res.json()); + try { + sessionStorage.removeItem("mq-reload"); + } catch { + // 没有 sessionStorage 也不影响。 + } + } catch (error) { + // 宿主重启后旧页面手里的口令会失效:换一个地址重新载入,拿新口令。 + if (error.http && error.status === 401) { + try { + if (!sessionStorage.getItem("mq-reload")) { + sessionStorage.setItem("mq-reload", "1"); + const next = new URL(location.href); + next.searchParams.set("_r", String(Date.now())); + location.replace(next.href); + return; + } + } catch { + // 同上。 + } + } + // 只有网络错误才重试;HTTP 错误直接显示,避免一直停在“正在连接”。 + if (!error.http && attempt < 20) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + if (attempt === 0) $("stamp").textContent = t.connecting; + return load(force, attempt + 1); + } + $("stamp").textContent = t.failed(String(error.message || error)); + } finally { + button.disabled = false; + button.textContent = t.refresh; + } +} + +labels(); +$("refresh").addEventListener("click", () => load(true)); +load(false); +setInterval(() => load(false), 60000); +// 切回这个页签时立刻拉一次,避免看到切走之前的旧表。 +window.addEventListener("focus", () => load(false)); +document.addEventListener("visibilitychange", () => { + if (!document.hidden) load(false); +}); diff --git a/packages/page-model-quota/ui/index.html b/packages/page-model-quota/ui/index.html new file mode 100644 index 0000000..3b2659e --- /dev/null +++ b/packages/page-model-quota/ui/index.html @@ -0,0 +1,82 @@ + + + + + +Model Quota + + + +
+
+
+

Model Quota

+

+
+
+ + +
+
+ +
+
+
+
—
+
+
+
+
+
—
+
+
+
+
+
—
+
+
+
+ +
+ + + + + + + + + + + + +
+ +
+ +

+
+ + + + + + + + + + + + + +
+ +
+ +
+

+
+
+ + + diff --git a/packages/page-model-quota/ui/style.css b/packages/page-model-quota/ui/style.css new file mode 100644 index 0000000..36497e5 --- /dev/null +++ b/packages/page-model-quota/ui/style.css @@ -0,0 +1,101 @@ +:root { + color-scheme: light dark; + --bg: #f6f7f9; + --fg: #17202a; + --muted: #667085; + --line: #e3e6eb; + --card: #ffffff; + --accent: #0e7490; + --accent-soft: #e0f2fe; + --track: #eef1f5; + --danger: #b42318; +} +[data-theme="dark"] { + --bg: #14181d; + --fg: #e6e9ee; + --muted: #98a2b3; + --line: #262d36; + --card: #1b2129; + --accent: #38bdf8; + --accent-soft: #12303f; + --track: #232a33; + --danger: #f97066; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #14181d; + --fg: #e6e9ee; + --muted: #98a2b3; + --line: #262d36; + --card: #1b2129; + --accent: #38bdf8; + --accent-soft: #12303f; + --track: #232a33; + --danger: #f97066; + } +} + +* { box-sizing: border-box; } +html, body { margin: 0; } +body { + background: var(--bg); + color: var(--fg); + font: 13px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei UI", "PingFang SC", system-ui, sans-serif; + -webkit-font-smoothing: antialiased; +} +.wrap { max-width: 1020px; margin: 0 auto; padding: 22px 20px 40px; } + +.top { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 18px; } +.title h1 { margin: 0; font-size: 19px; font-weight: 650; letter-spacing: .2px; } +.title .sub { margin: 4px 0 0; color: var(--muted); font-size: 12.5px; } +.actions { display: flex; align-items: center; gap: 10px; flex: none; } +.stamp { color: var(--muted); font-size: 12px; white-space: nowrap; } +button { + font: inherit; color: var(--fg); background: var(--card); + border: 1px solid var(--line); border-radius: 8px; padding: 6px 14px; cursor: pointer; + transition: border-color .15s, background .15s; +} +button:hover { border-color: var(--accent); } +button:active { transform: translateY(1px); } +button:disabled { opacity: .55; cursor: default; } + +.cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 18px; } +.card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; } +.card-label { color: var(--muted); font-size: 12px; } +.card-value { font-size: 22px; font-weight: 650; margin: 4px 0 2px; font-variant-numeric: tabular-nums; } +.card-note { color: var(--muted); font-size: 11.5px; } + +.table-wrap { background: var(--card); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; } +.grid { width: 100%; border-collapse: collapse; } +.grid th { + text-align: left; font-weight: 550; color: var(--muted); font-size: 12px; + padding: 11px 14px; border-bottom: 1px solid var(--line); white-space: nowrap; +} +.grid th.num, .grid td.num { text-align: right; } +.grid td { padding: 10px 14px; border-bottom: 1px solid var(--line); vertical-align: middle; } +.grid tbody tr.model-row { cursor: pointer; } +.grid tbody tr.model-row:hover { background: color-mix(in srgb, var(--accent-soft) 45%, transparent); } +.grid tbody tr:last-child td { border-bottom: none; } +.col-model { min-width: 220px; } +td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } +.model-name { display: flex; align-items: center; gap: 8px; } +.model-name .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex: none; } +.model-name .nm { font-weight: 550; } +.bar { height: 5px; border-radius: 3px; background: var(--track); margin-top: 6px; overflow: hidden; max-width: 260px; } +.bar > i { display: block; height: 100%; background: var(--accent); border-radius: 3px; } +.days.warn { color: var(--danger); } + +tr.detail-row > td { background: color-mix(in srgb, var(--accent-soft) 32%, transparent); padding: 0 14px 12px; } +.detail { padding: 8px 0 2px; } +.detail table { width: 100%; border-collapse: collapse; font-size: 12px; } +.detail th { text-align: left; color: var(--muted); font-weight: 500; padding: 4px 8px; } +.detail th.num, .detail td.num { text-align: right; } +.detail td { padding: 4px 8px; border-top: 1px dashed var(--line); font-variant-numeric: tabular-nums; } + +.empty { padding: 40px 20px; text-align: center; color: var(--muted); } +.section-title { font-size: 14px; font-weight: 600; margin: 22px 0 8px; letter-spacing: .2px; } +.foot { margin-top: 14px; color: var(--muted); font-size: 12px; } +.foot p { margin: 4px 0; } +.foot b { color: var(--fg); font-weight: 550; } +.spin { animation: spin 1s linear infinite; display: inline-block; } +@keyframes spin { to { transform: rotate(360deg); } } diff --git a/registry.json b/registry.json index d48021f..98a8558 100644 --- a/registry.json +++ b/registry.json @@ -281,9 +281,8 @@ "summary": { "en": "A quota card wall with expiry tiers, daily/per-provider charts, 24h cache-hit and token curves, optional remote attribution and account detail. Runs its own zero-dependency local service reading this machine's Magpie usage data; optional remote attribution queries the configured remote magpie.", "zh": "额度到期卡片墙 + 每日与 provider 用量图表 + 24 小时缓存命中与 token 曲线,可选远端归因与账号明细。自带零依赖本机服务,读本机 Magpie 用量数据;远端归因会查询所配置的远端 magpie。" } }, { "package": "magpie-muse-auth", "name": "Muse (Meta)", "icon": "https://raw.githubusercontent.com/sonvivu/magpie-muse-auth/main/icon.svg", "providers": ["muse"], "summary": { "en": "Muse (Meta) subscription for Magpie and OpenCode: device-code sign-in, minted API key, Wonder and Spark models with reasoning efforts. The -contributor models use Meta's Contributor lane (data may be used for training). Unofficial.", "zh": "使用 Muse (Meta) 订阅:设备码登录,自动换取 API 密钥,提供 Wonder 和 Spark 模型及推理强度设置;以 -contributor 结尾的模型走 Meta 的 Contributor 通道(数据可能用于训练)。(非官方)" } }, - { "package": "magpie-model-quota", "kind": "page", "name": "Model Quota", - "icon": "https://raw.githubusercontent.com/1sh1ro/magpie-model-quota/main/assets/icon.svg", - "summary": { "en": "Estimate how many tokens each model has left, merged across every account and provider. Runs entirely on magpie's local usage history; no telemetry or network requests.", "zh": "把所有账号、所有供应商的额度换算成 token,按模型合并估算还剩多少。完全基于 magpie 本地用量历史,不联网。" } }, + { "package": "@magpie-community/page-model-quota", "name": "Model Quota", "kind": "page", "community": true, + "summary": { "en": "How many tokens each model has left, merged across every account and provider: each quota window is turned into tokens from your own usage history and split by the model's share in it.", "zh": "每个模型在所有账号、所有供应商的池子里还剩多少 token:用你自己的用量历史把每个额度窗口换算成 token,再按模型在窗口里的占比摊开。" } }, { "package": "@magpie-community/page-harnessweight", "name": "HarnessWeight", "kind": "page", "community": true, "summary": { "en": "Compare agent harnesses behind your gateway by input tokens, cache, failures, latency and estimated tool-definition size. Its local service reads this machine's usage ledger; a read-only hook samples tool sizes and tracks in-flight requests.", "zh": "按 Agent 对比网关后面的输入 token、缓存、失败率、延迟与工具定义体积估算。本机服务读取用量记录,只读 hook 采样工具大小并追踪进行中的请求。" } } ]