diff --git a/README.md b/README.md index e8f22a2..6f2c6a9 100644 --- a/README.md +++ b/README.md @@ -191,6 +191,7 @@ These add a page to magpie's window, in the app and in `magpie web`, under Plugi | [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 | | [agent-console](packages/agent-console) | Drive the Agent CLIs on this computer (Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh) with a timeline, Git changes, files and a terminal, by [qingnian108](https://github.com/qingnian108). Has a host part: a gate and a daemon on 127.0.0.1, started when the page opens | none (its daemon runs the Agent CLIs you pick, in the projects you open) | +| [page-harnessweight](packages/page-harnessweight) | Compare the agent harnesses behind the gateway: tokens, cache, failures, latency and estimated tool-definition size. Has a local service and a read-only gateway hook, by [webkubor](https://github.com/webkubor) | none (the service reads the local usage ledger and the local gateway's agent names and icon keys; the hook records tool names and numerical usage metadata locally) | ```sh magpie plugin add @magpie-community/page- @@ -216,6 +217,7 @@ Like middleware, these run on the requests agents send, but in magpie's Bun host | [OpenViking](https://github.com/volcengine/OpenViking/tree/main/examples/magpie-memory-plugin) | OpenViking context recall and opt-in completed-conversation capture using existing OpenViking configuration; published as `@openviking/magpie-plugin` and maintained in the OpenViking repository | | [@vshulcz/magpie-deja](https://github.com/vshulcz/deja-vu/tree/main/extensions/magpie) | [deja-vu](https://github.com/vshulcz/deja-vu) local cross-agent session memory: recalls project-scoped (`ctx.cwd`) history from the transcripts Claude Code, Codex, Hermes, Gemini CLI, OpenCode, Cursor and DSH write on disk, scrubs secret patterns, and attaches the recalled excerpt to the request sent to your model provider; when recalled history helped, the model is asked to end its reply with a one-line `déjà vu: … — reusing it.` note | | [notify](packages/notify) | A push to ntfy, Bark, Gotify, Server酱, Feishu, DingTalk, WeCom, Telegram or a webhook when an agent's turn is done or fails, after it ran `minMinutes` or longer, and when a subscription account needs signing in again | +| [page-harnessweight](packages/page-harnessweight) | Tracks in-flight request counts in memory and records tool-definition sizes and usage metadata after responses; never modifies requests | Use the same plugin management commands as middleware: diff --git a/packages/page-harnessweight/.gitignore b/packages/page-harnessweight/.gitignore new file mode 100644 index 0000000..98fa027 --- /dev/null +++ b/packages/page-harnessweight/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +*.log +data/ diff --git a/packages/page-harnessweight/LICENSE b/packages/page-harnessweight/LICENSE new file mode 100644 index 0000000..af1ca36 --- /dev/null +++ b/packages/page-harnessweight/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 webkubor + +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-harnessweight/README.md b/packages/page-harnessweight/README.md new file mode 100644 index 0000000..3151a92 --- /dev/null +++ b/packages/page-harnessweight/README.md @@ -0,0 +1,39 @@ +# HarnessWeight + +A magpie page for comparing the agents behind your gateway: requests, input and output tokens, cache reads, failures, latency and estimated tool-definition size. The dashboard groups requests by agent, not model. A read-only gateway hook records tool counts and JSON sizes after each response and observes in-flight request counts in memory. + +[Project, screenshots and demo](https://github.com/webkubor/harnessweight) + +## Install + +```sh +magpie plugin add @magpie-community/page-harnessweight +``` + +Open **HarnessWeight** in magpie. Usage history is read from magpie's existing local ledger; tool-size samples accumulate after installation. The service listens on loopback, port **3496** by default. Change the `port` plugin option if that port is in use. + +## Reading the dashboard + +- **Input** includes fresh input, cache reads and cache writes. Cache rates and input tokens are usage measurements, not a currency amount; pricing depends on the model and provider. +- **Tool-definition tokens** are an estimate: the serialized JSON byte count divided by 3.5. They are not measured with the model's tokenizer. Tool definitions may be cached; their size is not a direct bill. +- **In flight** is derived from hook start and response callbacks. Missing callbacks may leave counts visible until expiry (15 minutes). It does not reflect activity outside the gateway. +- **Session duration** is the span between the first and last recorded request for a session in the chosen period, including idle time. Sessions longer than six hours are excluded from duration aggregates; a missing session ID cannot be measured. +- Protocols are inferred from recorded endpoints for the selected period. They are not a list of the agent's current configuration. + +## Data and security + +The sandboxed page asks for no bridge reads; it navigates to the plugin's local service. The service reads magpie's local usage ledger and queries its local gateway for agent display names and icon keys. The hook writes request metadata, tool names, counts and sizes locally. It does not store prompts, tool arguments or credentials and does not modify the request. + +The local service validates Host and Origin and requires a per-process random token on data APIs. No telemetry is sent by this plugin. + +Configuration options include `port`, `usageLog`, `dataDir`, `gatewayUrl` and `agents`; see the [project documentation](https://github.com/webkubor/harnessweight) for details. + +## Development + +```sh +bun test +``` + +Agent icons are from the community page-agent-office icon collection and LobeHub; see [app/icons/NOTICE](app/icons/NOTICE). Brand marks belong to their respective owners. + +MIT © webkubor diff --git a/packages/page-harnessweight/app/app.js b/packages/page-harnessweight/app/app.js new file mode 100644 index 0000000..4a3dbdc --- /dev/null +++ b/packages/page-harnessweight/app/app.js @@ -0,0 +1,495 @@ +// HarnessWeight — the interface. Served by the plugin's own service, so the +// data is a same-origin fetch away. + +import { explainFor, COLS, CARD_SORTS } from "./explain.js" +import { pageLanguage, languageTags, translate } from "./i18n.mjs" + +const $ = (id) => document.getElementById(id) +const qs = new URLSearchParams(location.search) +// magpie's window language arrives as ?lang= (page/boot.js); opened directly, +// the browser's own language decides +const LANG = pageLanguage(qs.get("lang") || navigator.language || "") +const LOCALE = languageTags[LANG] || "en" +const T = (key, params) => translate(LANG, key, params) +document.documentElement.lang = LOCALE +document.title = T("app.title") +for (const el of document.querySelectorAll("[data-t]")) el.textContent = T(el.dataset.t) +for (const el of document.querySelectorAll("[aria-label-t]")) el.setAttribute("aria-label", T(el.getAttribute("aria-label-t"))) +// sandboxed in magpie's frame the origin is opaque and storage throws +const store = { + get(k) { try { return localStorage.getItem(k) } catch { return null } }, + set(k, v) { try { localStorage.setItem(k, v) } catch {} }, +} + +const state = { + period: store.get("al.period") || "7d", + clients: store.get("al.clients") === "1", + sort: { key: "prompt", dir: -1 }, + cardSort: "prompt", + toolSort: "avgBytes", + activeAgents: new Map(), + activityKnown: false, + data: null, + openAgent: null, +} + +// the service writes a per-start token into this page's HTML +const TOKEN = document.querySelector('meta[name="harnessweight-token"]')?.content || "" +let reloaded = false +const sessionStorageSafe = () => reloaded || location.hash === "#r" +function markReloaded() { reloaded = true; location.hash = "r" } + +// ---------- formatting ---------- +const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]) +function short(n) { + if (n == null || !Number.isFinite(n)) return "—" + const a = Math.abs(n) + if (a >= 1e9) return `${(n / 1e9).toFixed(2)}B` + if (a >= 1e6) return `${(n / 1e6).toFixed(1)}M` + if (a >= 1e3) return `${(n / 1e3).toFixed(1)}K` + return String(Math.round(n)) +} +const int = (n) => (n == null ? "—" : Math.round(n).toLocaleString(LOCALE)) +const pct = (x) => (x == null || !Number.isFinite(x) ? "—" : `${(x * 100).toFixed(1)}%`) +function secs(ms) { + if (!ms) return "—" + return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s` +} +function dur(ms) { + if (ms == null || !Number.isFinite(ms)) return "—" + const m = ms / 60000 + if (m < 1) return `${Math.round(ms / 1000)}${esc(T("dur.second"))}` + if (m < 60) return `${m.toFixed(0)}${esc(T("dur.minute"))}` + const h = m / 60 + if (h < 24) return `${h.toFixed(1)}${esc(T("dur.hour"))}` + return `${(h / 24).toFixed(1)}${esc(T("dur.day"))}` +} +function when(at) { + if (!at) return "—" + return new Date(at).toLocaleString(LOCALE, { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }) +} + +// ---------- agent mark: magpie's own icon, else the initial ---------- +const PALETTE = ["#17A9A2", "#F26B1D", "#6D5DFC", "#2B8AE2", "#C2410C", "#0E7C77", "#8B5CF6", "#64748B"] +function hue(s) { let h = 0; for (const c of String(s)) h = (h * 31 + c.charCodeAt(0)) >>> 0; return PALETTE[h % PALETTE.length] } +function mark(a, size = 20) { + const initial = esc(String(a.name || a.agent || "?").trim().charAt(0).toUpperCase()) + const letter = `${initial}` + if (!a.icon) return letter + return `` +} +const label = (a) => esc(a.name || a.agent) + +// ---------- explanations ---------- +// A small "?" that shows what a number means on hover or keyboard focus. The +// text lives in explain.js; this only renders the marker. +// A label with a small "?" next to it that opens the explanation on hover or +// keyboard focus. The label itself stays plain text; only the marker is a +// button, so a label never gets squeezed by the marker. +function tip(key, label) { + const e = explainFor(key, LANG) + if (!e.title || e.title.startsWith("explain.")) return label ?? "" + return `${label ?? ""}` +} + +// Render notes outside scroll containers so table and drawer overflow never clip them. +let activeTip = null +function closeTip() { + if (!activeTip) return + activeTip.trigger.setAttribute('aria-expanded', 'false') + activeTip.bubble.remove() + activeTip = null +} +function wireTips(root) { + for (const t of root.querySelectorAll('.tip:not([data-wired])')) { + t.dataset.wired = '1' + const open = () => { + if (activeTip?.trigger === t) return + closeTip() + const bubble = document.createElement('div') + bubble.className = 'floating-tip' + bubble.setAttribute('aria-hidden', 'true') // trigger already contains the full accessible label + bubble.innerHTML = t.querySelector('.tip-body').innerHTML + document.body.append(bubble) + const r = t.getBoundingClientRect(), b = bubble.getBoundingClientRect() + const left = Math.max(8, Math.min(window.innerWidth - b.width - 8, r.left + r.width / 2 - b.width / 2)) + const top = r.top >= b.height + 10 ? r.top - b.height - 8 : Math.min(window.innerHeight - b.height - 8, r.bottom + 8) + bubble.style.left = `${left}px` + bubble.style.top = `${Math.max(8, top)}px` + t.setAttribute('aria-expanded', 'true') + activeTip = {trigger:t, bubble} + } + const close = () => { if (activeTip?.trigger === t) closeTip() } + t.addEventListener('mouseenter', open) + t.addEventListener('mouseleave', close) + t.addEventListener('focus', open) + t.addEventListener('blur', close) + t.addEventListener('click', e => { e.stopPropagation(); open() }) + t.addEventListener('keydown', e => { + e.stopPropagation() + if (e.key === 'Escape') { close(); t.blur() } + if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); activeTip?.trigger === t ? close() : open() } + }) + } +} +document.addEventListener('scroll', closeTip, true) +window.addEventListener('resize', closeTip) +document.addEventListener('pointerdown', e => { if (!e.target.closest('.tip')) closeTip() }) + +// Only request-start / response-finish hook observations drive activity. +// Completed-request timestamps must never masquerade as in-flight calls. +function isLive(a) { + return state.activityKnown && (state.activeAgents.get(a.agent) || 0) > 0 +} +function activityBadge(agent) { + const count = state.activeAgents.get(agent) || 0 + return `${tip("live", esc(T("activity.callsInFlight", { n: count })))}` +} +async function refreshActivity() { + if (document.hidden) return + try { + const res = await fetch(`/api/activity?k=${encodeURIComponent(TOKEN)}`, {cache:'no-store', signal:AbortSignal.timeout(4000)}) + if (!res.ok) throw new Error(`HTTP ${res.status}`) + const data = await res.json() + state.activeAgents = new Map(data.agents.map(a => [a.agent, a.count])) + state.activityKnown = data.available === true + if (!state.activityKnown) state.activeAgents.clear() + } catch { + state.activityKnown = false + state.activeAgents.clear() + } + $('activityInfo').textContent = state.activityKnown + ? T("activity.liveHint") + : T("activity.unavailableHint") + for (const card of document.querySelectorAll('.card[data-agent]')) { + const active = state.activityKnown && (state.activeAgents.get(card.dataset.agent) || 0) > 0 + card.classList.toggle('live', active) + const head = card.querySelector('.card-head') + const old = head.querySelector('.live-badge') + const count = state.activeAgents.get(card.dataset.agent) || 0 + if (old && old.dataset.count === String(count)) continue + old?.remove() + if (active) { + head.insertAdjacentHTML('beforeend', activityBadge(card.dataset.agent)) + const badge = head.querySelector('.live-badge') + badge.dataset.count = String(count) + wireTips(badge) + } + } +} + +// ---------- sparkline ---------- +function spark(series, key, cls = "") { + if (!series || series.length < 2) return "" + const w = 240, h = cls ? 80 : 34, pad = 2 + const vals = series.map((d) => d[key]) + const max = Math.max(...vals, 1) + const pts = vals.map((v, i) => [pad + (i * (w - pad * 2)) / (vals.length - 1), h - pad - (v / max) * (h - pad * 2)]) + const line = pts.map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(" ") + const area = `${line} L${pts.at(-1)[0].toFixed(1)} ${h} L${pts[0][0].toFixed(1)} ${h} Z` + return `` +} + +// ---------- paint ---------- +function paint() { + const d = state.data + $("state").hidden = true + if (!d.agents.length) { + for (const id of ["insights", "kpis", "cards", "tools"]) $(id).innerHTML = "" + $("table").innerHTML = "" + showState(T("state.noAgents")) + return + } + paintStatus(d) + paintInsights(d) + paintKpis(d) + paintCardSort() + paintCards(d) + paintTable(d) + paintTools(d) + wireTips(document) + const s = d.sources || {} + $("sources").textContent = T("sources.summary", { usageRows: int(s.usageRows), toolRows: int(s.toolRows), time: new Date(d.generatedAt).toLocaleTimeString(LOCALE) }) + if (state.openAgent) openDetail(state.openAgent, false) +} + +function ago(t) { + if (!t) return T("time.none") + const s = Math.max(0, (Date.now() - t) / 1000) + if (s < 60) return T("time.secondsAgo", { n: Math.round(s) }) + if (s < 3600) return T("time.minutesAgo", { n: Math.round(s / 60) }) + if (s < 86400) return T("time.hoursAgo", { n: Math.round(s / 3600) }) + return T("time.daysAgo", { n: Math.round(s / 86400) }) +} +function paintStatus(d) { + const fresh = d.lastTool && Date.now() - d.lastTool < 15 * 60e3 + const el = $("status") + el.className = "status " + (fresh ? "live" : d.lastTool ? "idle" : "wait") + el.textContent = fresh ? T("status.collecting", { usage: ago(d.lastUsage), tool: ago(d.lastTool) }) + : d.lastTool ? T("status.stale", { tool: ago(d.lastTool) }) + : T("status.waiting") +} + +function paintInsights(d) { + $("insights").innerHTML = d.insights + .map((i) => `
${esc(i.text)}
`) + .join("") +} + +function paintKpis(d) { + const t = d.totals + const items = [ + [T("kpi.inputTokens"), short(t.prompt), T("kpi.requests", { count: int(t.calls) }), "prompt"], + [T("kpi.cacheRate"), pct(t.cacheRate), T("kpi.fullPriceOf", { value: short(t.fullPrice) }), "cacheRate"], + [T("kpi.outputTokens"), short(t.out), T("kpi.avgPerCall", { value: short(t.calls ? t.out / t.calls : 0) }), "out"], + [T("kpi.failed"), int(t.failed), pct(t.calls ? t.failed / t.calls : 0), "errorRate"], + [T("kpi.agents"), int(d.agents.length), d.hiddenClients ? T("kpi.hiddenClients", { count: int(d.hiddenClients) }) : T("kpi.clients"), null], + ] + if (t.credits > 0) items.splice(4, 0, [T("kpi.credits"), t.credits.toFixed(2), T("kpi.creditsNote")]) + $("kpis").innerHTML = items + .map(([k, v, s, tipKey]) => `
${tipKey ? tip(tipKey, k) : k}
${v}
${esc(s)}
`) + .join("") +} + +function paintCards(d) { + const max = Math.max(...d.agents.map((a) => a.prompt), 1) + const sorted = [...d.agents].sort((x, y) => cardVal(y, state.cardSort) - cardVal(x, state.cardSort)) + $("cards").innerHTML = sorted + .map((a, i) => { + const w = (a.prompt / max) * 100 + const fullW = a.prompt ? (a.fullPrice / a.prompt) * w : 0 + const top1 = a.prompt === max && d.agents.length > 1 + const live = isLive(a) + const proto = a.protocols?.[0]?.name + return `
+
${mark(a, 22)}${label(a)}${live ? activityBadge(a.agent) : ""}${top1 ? `${esc(T("card.topSpender"))}` : ""}
+
${short(a.prompt)}${esc(T("card.inputTokens"))}
+
+
+
${pct(a.cacheRate)}${tip("cacheRate", esc(T("col.cacheRate")))}
+
${short(a.avgPrompt)}${tip("avgPrompt", esc(T("col.avgPrompt")))}
+
${pct(a.errorRate)}${tip("errorRate", esc(T("col.errorRate")))}
+
+ ${proto ? `
${esc(proto)}${a.session?.median ? `${dur(a.session.median)}` : ""}
` : ""} + ${spark(a.series, "prompt")} +
` + }) + .join("") +} + +const val = (a, k) => { + if (k === "toolTokens") return a.tools?.avgTokens ?? -1 + if (k === "agent") return a.name || a.agent + if (k === "protocol") return a.protocols?.[0]?.name || "" + if (k === "session") return a.session?.median ?? -1 + return a[k] +} + +const cardVal = (a, k) => (k === "toolTokens" ? a.tools?.avgTokens ?? -1 : a[k] ?? -1) + +function paintCardSort() { + const box = $("cardSort") + if (!box) return + box.innerHTML = CARD_SORTS.map(([k, nameKey]) => + ``).join("") +} + +function paintTable(d) { + const { key, dir } = state.sort + const rows = [...d.agents].sort((x, y) => { + const a = val(x, key), b = val(y, key) + return typeof a === "string" ? a.localeCompare(b) * dir : ((a ?? 0) - (b ?? 0)) * dir + }) + const topAgent = d.agents[0]?.agent + const head = COLS.map(([k, nameKey, n, tipKey]) => { const name = esc(T(nameKey)); return `${tipKey ? tip(tipKey, name) : name}` }).join("") + const body = rows + .map((a) => ` + ${mark(a, 18)}${label(a)}${a.agent === topAgent && d.agents.length > 1 ? `` : ""} + ${int(a.calls)} + ${short(a.prompt)} + ${short(a.avgPrompt)} + ${pct(a.cacheRate)} + ${short(a.fullPrice)} + ${short(a.out)} + ${pct(a.errorRate)} + ${secs(a.p50ttft)} + ${secs(a.p50ms)} + ${a.tools ? short(a.tools.avgTokens) : "—"} + ${a.protocols?.length ? esc(a.protocols[0].name) : "—"} + ${a.session?.median ? dur(a.session.median) : "—"} + `) + .join("") + $("table").innerHTML = `${head}${body}` +} + +function paintTools(d) { + const withTools = d.agents.filter((a) => a.tools) + if (!withTools.length) { + $("toolsHint").textContent = T("tools.hint") + $("tools").innerHTML = `
${esc(T("tools.empty"))}
` + return + } + const sorted = [...withTools].sort((a, b) => (b.tools[state.toolSort] ?? 0) - (a.tools[state.toolSort] ?? 0)) + const max = sorted[0].tools.avgBytes || 1 + $("toolsHint").innerHTML = `${esc(T("tools.sampling", { since: when(d.toolsSince), samples: int(d.toolSamples) }))} + ${[["avgBytes", T("tools.sortBytes")], ["avgTokens", T("tools.sortTokens")], ["avgCount", T("tools.sortCount")], ["shareOfPrompt", T("tools.sortShare")]] + .map(([k, n]) => ``).join("")}` + $("tools").innerHTML = `
${sorted + .map((a, i) => `
+
${mark(a, 18)}${label(a)}
+
+
${esc(a.tools.shareOfPrompt != null ? T("tools.perAgentShare", { count: Math.round(a.tools.avgCount), tokens: short(a.tools.avgTokens), share: pct(a.tools.shareOfPrompt) }) : T("tools.perAgent", { count: Math.round(a.tools.avgCount), tokens: short(a.tools.avgTokens) }))}
+
`) + .join("")}
` +} + +// ---------- detail drawer ---------- +function distribution(items, total) { + if (!items?.length) return `

${esc(T("detail.noRecords"))}

` + return items.map(m => `
${esc(m.label || m.name)}${esc(T("detail.countPct", { count: int(m.count), pct: pct(total ? m.count / total : 0) }))}
`).join("") +} + +function openDetail(agent, focus = true) { + const a = state.data?.agents.find(x => x.agent === agent) + if (!a) return closeDetail() + const previousDetails = !focus ? [...$("detail").querySelectorAll('details')].map(d => d.open) : [] + const previousQuery = !focus ? $("detail").querySelector('.tool-search input')?.value || '' : '' + state.openAgent = agent + const modelCount = a.models.reduce((n,m) => n + m.count, 0) + const protoNames = {anthropic:'Anthropic Messages', responses:'OpenAI Responses', chat:'OpenAI Chat Completions', gemini:'Google Gemini', other:T('detail.otherProtocol')} + const protocolCount = a.protocols.reduce((n,p) => n + p.count, 0) + const toolNames = a.tools?.names || [] + const cache = Math.max(0, Math.min(100, a.cacheRate * 100)) + const failure = a.calls ? a.failed / a.calls : 0 + $("detail").innerHTML = `
+

${mark(a,32)}${label(a)}

${when(a.first)} — ${when(a.last)} · ${esc(T('detail.selectedPeriod'))}

+
${esc(T('detail.summaryRequests', { calls: int(a.calls) }))}

${esc(T('detail.summaryBody', { avg: short(a.avgPrompt), cache: pct(a.cacheRate), failed: int(a.failed), cancelled: int(a.cancelled) }))}

${esc(T('detail.summaryNote'))}
+

${esc(T('detail.inputTitle'))} ${tip('prompt')}

+
${esc(T('detail.totalInput'))}${short(a.prompt)}
${esc(T('detail.avgInput'))}${short(a.avgPrompt)}
${esc(T('detail.generatedOutput'))}${short(a.out)}
+ ${a.prompt ? `
+
● ${esc(T('detail.cacheReads'))} ${short(a.cacheRead)} · ${pct(a.cacheRate)}● ${esc(T('detail.nonCacheReads'))} ${short(a.fullPrice)}
` : `

${esc(T('detail.noInput'))}

`} +

${esc(T('detail.cacheNote'))}

+
${esc(T('detail.inputBreakdown'))}
${esc(T('detail.freshInput'))}
${short(a.in)}
${esc(T('detail.cacheWrite'))}
${short(a.cacheWrite)}
${a.credits > 0 ? `
${esc(T('detail.credits'))}
${a.credits.toFixed(2)} credits
` : ''}
+
+

${esc(T('detail.latencyTitle'))}

${esc(T('detail.ttft'))} ${tip('p50ttft')}${secs(a.p50ttft)}
${esc(T('detail.fullResponse'))} ${tip('p50ms')}${secs(a.p50ms)}
${esc(T('detail.failureRate'))} ${tip('errorRate')}${pct(failure)}

${esc(T('detail.latencyNote'))}

+

${esc(T('detail.toolsTitle'))} ${tip('toolTokens')}

${a.tools ? `
${esc(T('detail.toolsPerRequest'))}${esc(T('detail.toolsPerRequestValue', { count: Math.round(a.tools.avgCount) }))}
${esc(T('detail.toolSize'))}≈${short(a.tools.avgTokens)}
${esc(T('detail.validSamples'))}${esc(T('detail.validSamplesValue', { count: int(a.tools.samples) }))}

${esc(T('detail.toolsNote'))}

${esc(T('detail.toolsCaveat', { samples: int(a.tools.samples), calls: int(a.calls) }))}

${esc(T('detail.toolInventory'))}
${toolNames.map(t=>`${esc(t.name)}`).join('')}

${esc(T('detail.toolInventoryNote'))}

` : `

${esc(T('detail.toolsEmpty'))}

`}
+

${esc(T('detail.modelsTitle'))}

${esc(T('detail.modelsNote', { count: a.models.length }))}

${distribution(a.models,a.calls)}${modelCount < a.calls ? `

${esc(T('detail.remaining', { count: int(a.calls-modelCount) }))}

` : ''}
+

${esc(T('detail.protocolsTitle'))} ${tip('protocol')}

${esc(T('detail.protocolsNote'))}

${distribution(a.protocols.map(p=>({...p,label:protoNames[p.name] || p.name})),a.calls)}${protocolCount < a.calls ? `

${esc(T('detail.remaining', { count: int(a.calls-protocolCount) }))}

` : ''}
+

${esc(T('detail.sessionTitle'))} ${tip('sessionMedian')}

${a.session?.measured ? `
${esc(T('detail.medianSpan'))}${dur(a.session.median)}
${esc(T('detail.p90Span'))}${dur(a.session.p90)}
${esc(T('detail.measuredSessions'))}${int(a.session.measured)}

${esc(T('detail.sessionNote', { open: int(a.session.open || 0) }))}

` : `
${esc(T('detail.sessionUnavailable'))}

${esc(T('detail.sessionEmpty'))}

`}
+

${esc(T('detail.trendTitle'))}

${spark(a.series,'prompt','big') || `

${esc(T('detail.trendEmpty'))}

`}

${esc(T('detail.trendNote'))}

+
` + wireTips($("detail")) + $("detail").querySelector('.tool-search input')?.addEventListener('input', e => { + const term = e.target.value.trim().toLowerCase() + for (const item of $("detail").querySelectorAll('[data-tool-name]')) item.hidden = !item.dataset.toolName.includes(term) + }) + if (!focus) { + $("detail").querySelectorAll('details').forEach((d,i) => { d.open = !!previousDetails[i] }) + const input = $("detail").querySelector('.tool-search input') + if (input) { input.value = previousQuery; input.dispatchEvent(new Event('input')) } + } + const dr = $("drawer") + dr.classList.add("open") + dr.setAttribute("aria-hidden", "false") + $("scrim").hidden = false + if (focus) { dr.scrollTop = 0; dr.focus() } +} +function closeDetail() { + state.openAgent = null + $("drawer").classList.remove("open") + $("drawer").setAttribute("aria-hidden", "true") + $("scrim").hidden = true +} + +// ---------- loading ---------- +function showState(text, err = false) { + $("state").hidden = false + $("state").className = err ? "state err" : "state" + $("state").textContent = text +} + +async function load() { + if (!state.data) $("cards").innerHTML = '
' + try { + const p = new URLSearchParams({ period: state.period, tz: String(new Date().getTimezoneOffset()) }) + if (state.clients) p.set("clients", "1") + p.set("lang", LANG) + p.set("k", TOKEN) + const res = await fetch(`/api/summary?${p}`, { cache: "no-store" }) + if (res.status === 403 && !sessionStorageSafe("al.reloaded")) { markReloaded(); return location.reload() } + if (!res.ok) throw new Error(`HTTP ${res.status}`) + state.data = await res.json() + paint() + } catch (e) { + showState(T("state.loadError", { message: e.message }), true) + } +} + +// ---------- events ---------- +function selectPeriod() { + for (const b of $("periods").children) b.setAttribute("aria-selected", String(b.dataset.period === state.period)) +} +$("periods").addEventListener("click", (e) => { + const b = e.target.closest("button[data-period]") + if (!b || b.dataset.period === state.period) return + state.period = b.dataset.period + store.set("al.period", state.period) + selectPeriod() + load() +}) +$("clients").checked = state.clients +$("clients").addEventListener("change", (e) => { + state.clients = e.target.checked + store.set("al.clients", state.clients ? "1" : "0") + load() +}) +const pick = (e) => e.target.closest("[data-agent]")?.dataset.agent +$("cards").addEventListener("click", (e) => { const a = pick(e); if (a) openDetail(a) }) +$("cardSort").addEventListener("click", (e) => { + const b = e.target.closest("button[data-sort]") + if (!b || b.dataset.sort === state.cardSort) return + state.cardSort = b.dataset.sort + paintCardSort() + paintCards(state.data) + wireTips($("cards")) +}) +$("toolsHint").addEventListener("click", (e) => { + const b = e.target.closest("button[data-tsort]") + if (!b) return + state.toolSort = b.dataset.tsort + paintTools(state.data) +}) +$("table").addEventListener("click", (e) => { + const th = e.target.closest("th[data-key]") + if (th) { + const k = th.dataset.key + state.sort = { key: k, dir: state.sort.key === k ? -state.sort.dir : k === "agent" ? 1 : -1 } + paintTable(state.data) + wireTips($("table")) + return + } + const a = pick(e) + if (a) openDetail(a) +}) +for (const id of ["cards", "table"]) { + $(id).addEventListener("keydown", (e) => { + if (e.key !== "Enter" && e.key !== " ") return + const th = e.target.closest("th[data-key]") + if (th) { e.preventDefault(); return th.click() } + const a = pick(e) + if (a) { e.preventDefault(); openDetail(a) } + }) +} +$("close").addEventListener("click", closeDetail) +$("scrim").addEventListener("click", closeDetail) +document.addEventListener("keydown", (e) => { if (e.key === "Escape" && state.openAgent) closeDetail() }) + +selectPeriod() +await load() +await refreshActivity() +setInterval(load, 60_000) +async function pollActivity() { + await refreshActivity() + setTimeout(pollActivity, 2000) +} +setTimeout(pollActivity, 2000) diff --git a/packages/page-harnessweight/app/explain.js b/packages/page-harnessweight/app/explain.js new file mode 100644 index 0000000..4aaefc5 --- /dev/null +++ b/packages/page-harnessweight/app/explain.js @@ -0,0 +1,50 @@ +// What every number on this page means, in one place. Each entry becomes a +// small "?" that shows the explanation on hover or focus — so a reader who +// does not know the term can find out without leaving the page. +// +// The explanations name what is measured, where the number comes from, and +// what makes it misleading. Anything that is an estimate says so. +// +// The wording itself lives in i18n.mjs, beside the rest of the interface +// text; this file only says which explanation exists and where it goes. + +import { translate } from "./i18n.mjs" + +// The explanation for one metric, in the page's language. +export function explainFor(key, lang) { + return { + title: translate(lang, `explain.${key}.title`), + body: translate(lang, `explain.${key}.body`), + } +} + +// The order the table uses, with the tooltip key for each column. +// [key, label key, is numeric, tooltip key] +export const COLS = [ + ["agent", "col.agent", false, null], + ["calls", "col.calls", true, "calls"], + ["prompt", "col.prompt", true, "prompt"], + ["avgPrompt", "col.avgPrompt", true, "avgPrompt"], + ["cacheRate", "col.cacheRate", true, "cacheRate"], + ["fullPrice", "col.fullPrice", true, "fullPrice"], + ["out", "col.out", true, "out"], + ["errorRate", "col.errorRate", true, "errorRate"], + ["p50ttft", "col.p50ttft", true, "p50ttft"], + ["p50ms", "col.p50ms", true, "p50ms"], + ["toolTokens", "col.toolTokens", true, "toolTokens"], + ["protocol", "col.protocol", false, "protocol"], + ["session", "col.session", true, "sessionMedian"], +] + +// The card order: what the cards can be sorted by. +// [key, label key, tooltip key] +export const CARD_SORTS = [ + ["prompt", "sort.prompt", "prompt"], + ["avgPrompt", "col.avgPrompt", "avgPrompt"], + ["cacheRate", "col.cacheRate", "cacheRate"], + ["fullPrice", "col.fullPrice", "fullPrice"], + ["errorRate", "col.errorRate", "errorRate"], + ["p50ms", "col.p50ms", "p50ms"], + ["p50ttft", "col.p50ttft", "p50ttft"], + ["toolTokens", "sort.toolTokens", "toolTokens"], +] diff --git a/packages/page-harnessweight/app/i18n.mjs b/packages/page-harnessweight/app/i18n.mjs new file mode 100644 index 0000000..65013e2 --- /dev/null +++ b/packages/page-harnessweight/app/i18n.mjs @@ -0,0 +1,456 @@ +// HarnessWeight's interface text, in one place. +// +// The Chinese is the source of truth for the copy; every other language is a +// table beside it. The page asks for a key, never for a language-specific +// string, so a missing translation falls back to English instead of leaking +// Chinese into an English UI. +// +// This module is shared: the browser loads it as a module (app.js imports it) +// and the service imports the same file to write the insights sentences, so +// both sides speak the same language and there is only one copy of the copy. +// +// No Node and no browser APIs here on purpose — it must load in both. + +export const languageTags = { en: "en", zh: "zh-CN", "zh-TW": "zh-TW", ja: "ja-JP" } + +// magpie hands the page a language tag ("zh-CN", "en-US", "ja-JP", …). +// Anything we have no table for reads English. +export function languageFor(value = "") { + const tag = String(value).toLowerCase().replaceAll("_", "-") + if (/^zh-(tw|hk|mo|hant)\b/.test(tag)) return "zh-TW" + if (/^zh(?:-|$)/.test(tag)) return "zh" + if (/^ja(?:-|$)/.test(tag)) return "ja" + return "en" +} + +const en = { + // ---- app shell ---- + "app.title": "HarnessWeight · agent harness token weight", + "status.loading": "Loading…", + "header.sub": "Behind one gateway: how many tokens each agent harness reads, how many hit the cache, how many calls fail, and how heavy the tool definitions it resends every turn are.", + "aria.periods": "Period", + "period.today": "Today", + "period.7d": "7 days", + "period.30d": "30 days", + "clients.toggle": "Include scripts and internal requests", + "aria.insights": "Insights", + "aria.overview": "Overview", + "aria.cardSort": "Sort cards", + "aria.close": "Close", + "footer.localOnly": "Data is read locally and never uploaded.", + + // ---- sections ---- + "cards.title": "Where your tokens go", + "cards.hint": "Each card is an agent. Bar length is total input tokens; the darker segment combines fresh input and cache writes. Pricing depends on the provider.", + "activity.connecting": "Connecting to live request status…", + "table.title": "Compare metrics", + "table.hint": "Click a column header to sort, or a row for details.", + "tools.title": "Tool definition weight", + "tools.hint": "Agents resend their tool list with every request, and that counts towards input tokens too.", + + // ---- formatting ---- + "dur.second": "s", + "dur.minute": "m", + "dur.hour": "h", + "dur.day": "d", + "unit.times": "times", + "unit.items": "items", + + // ---- status and sources ---- + "time.none": "not yet", + "time.secondsAgo": "{n}s ago", + "time.minutesAgo": "{n}m ago", + "time.hoursAgo": "{n}h ago", + "time.daysAgo": "{n}d ago", + "status.collecting": "Collecting · last request {usage} · last tool sample {tool}", + "status.stale": "No new sample in 15 minutes · last one {tool} (use an agent and it resumes)", + "status.waiting": "Hook installed, waiting for the first request through the gateway", + "sources.summary": "{usageRows} usage rows · {toolRows} tool samples · updated at {time}", + "state.noAgents": "No agent requests were recorded in this period. Send a request from any agent through the gateway, then refresh.", + "state.loadError": "Could not read the data: {message}. Make sure the magpie gateway is running, then refresh.", + + // ---- activity ---- + "activity.callsInFlight": "{n} in flight", + "activity.liveHint": "An animated border means the gateway observed an in-flight request for this agent.", + "activity.unavailableHint": "Live request status is unavailable. An unlit border does not mean the agent is idle.", + + // ---- overview tiles ---- + "kpi.inputTokens": "Input tokens", + "kpi.cacheRate": "Cache hit rate", + "kpi.outputTokens": "Output tokens", + "kpi.failed": "Failed", + "kpi.agents": "Agents", + "kpi.credits": "credits", + "kpi.requests": "{count} requests", + "kpi.fullPriceOf": "{value} at full price", + "kpi.avgPerCall": "{value} average per call", + "kpi.hiddenClients": "{count} script/internal requests not counted", + "kpi.clients": "Clients behind the gateway", + "kpi.creditsNote": "Usage credits recorded by magpie", + + // ---- cards ---- + "card.topSpender": "Top spender", + "card.inputTokens": "input tokens", + "card.stackLegend": "Light: cache reads; dark: billed at full price", + "card.detailsAria": "{name} details", + "card.sessionMedianTitle": "Median session span", + "table.topSpenderTitle": "Top spender", + + // ---- tools block ---- + "tools.empty": "No samples yet. The gateway hook records which tools each agent sends and how large they are (names and sizes only, never contents). Use an agent for a while, then refresh.", + "tools.sampling": "Sampling since {since}, across {samples} requests. Token counts are estimated at about 3.5 bytes per token, the same for every agent.", + "tools.sortBytes": "By bytes", + "tools.sortTokens": "By tokens", + "tools.sortCount": "By count", + "tools.sortShare": "Share of input", + "tools.perAgent": "{count} · ≈{tokens} tokens", + "tools.perAgentShare": "{count} · ≈{tokens} tokens · {share} of input", + + // ---- detail drawer ---- + "detail.noRecords": "No records to show in this period.", + "detail.countPct": "{count} · {pct}", + "detail.selectedPeriod": "selected period", + "detail.summaryRequests": "In this period it sent {calls} requests to the model.", + "detail.summaryBody": "An average of {avg} tokens read per request; {cache} of the input came from cache. {failed} failed and {cancelled} were cancelled.", + "detail.summaryNote": "These are observed usage records. Different tasks, models, and usage frequency make this unsuitable as an agent capability ranking.", + "detail.inputTitle": "① Where do the input tokens go?", + "detail.totalInput": "Total input", + "detail.avgInput": "Average per request", + "detail.generatedOutput": "Generated output", + "detail.inputBreakdown": "Input breakdown", + "detail.freshInput": "Fresh input", + "detail.cacheWrite": "Cache writes", + "detail.credits": "Gateway credits", + "detail.latencyTitle": "② How long does it take, and how often does it fail?", + "detail.ttft": "Time to first token", + "detail.fullResponse": "Full response", + "detail.failureRate": "Failure rate", + "detail.latencyNote": "Times are medians (p50): half of the valid records are faster. First-token and full-response samples are counted separately and may differ, so subtracting them does not give the generation time. A failure does not necessarily cost anything.", + "detail.toolsTitle": "③ How heavy are the tool definitions?", + "detail.toolsPerRequest": "Tools per request", + "detail.toolsPerRequestValue": "{count}", + "detail.toolSize": "Definition size (estimated tokens)", + "detail.validSamples": "Valid samples", + "detail.validSamplesValue": "{count}", + "detail.toolsNote": "Tool definitions are the model’s instruction manuals: names, parameter schemas, and descriptions. Long manuals eat context, so fewer tools are not necessarily lighter.", + "detail.toolsCaveat": "Estimated from JSON bytes ÷ 3.5, not from the model’s tokenizer. {samples} tool samples and {calls} usage records are not matched request by request, so no coverage rate can be derived from them. Tool definitions may hit the cache, so they are not billed at full price on every turn.", + "detail.toolInventory": "Frequent tool names (up to 40)", + "detail.toolFilter": "Filter tool names", + "detail.toolSearchPlaceholder": "Search names", + "detail.toolInventoryNote": "Shows up to the 40 names seen most often in the samples; each sample records at most 60 names. This is not a full inventory, not the current configuration, and not a count of tool calls.", + "detail.toolsEmpty": "No tool definitions collected yet. As this agent sends new requests through the gateway, data will appear here.", + "detail.modelsTitle": "④ Which models were used?", + "detail.modelsNote": "Ordered by request count; percentages use this agent’s total requests as the denominator. Showing the top {count}.", + "detail.remaining": "{count} other records.", + "detail.protocolsTitle": "⑤ Which protocols were used?", + "detail.protocolsNote": "A protocol is the message format between the request and the model service. These are the main protocols in the selected period, inferred from the endpoints in the logs and possibly including protocols the gateway converted; this is not the current configuration.", + "detail.sessionTitle": "⑥ How long does a session last?", + "detail.medianSpan": "Median span", + "detail.p90Span": "90% of sessions below", + "detail.measuredSessions": "Measured sessions", + "detail.sessionNote": "Measured as the span between a session’s first and last request, including thinking and idle time, so it is not continuous work time. The current window may cut a session short; {open} sessions longer than six hours are left out of the measurement.", + "detail.sessionUnavailable": "Session span cannot be computed", + "detail.sessionEmpty": "No session records to measure in this period. Request counts and response times are still available; this does not mean the agent did no work.", + "detail.otherProtocol": "Other / unknown", + "detail.cacheReads": "Cache reads", + "detail.nonCacheReads": "Non-cache reads", + "detail.noInput": "No input tokens in this period, so the composition cannot be computed.", + "detail.cacheNote": "Cache reads usually get a discount. Non-cache reads include fresh input and cache writes, and providers price them differently; token counts are not money.", + "detail.trendTitle": "Daily input tokens", + "detail.trendEmpty": "Not enough data to draw a trend yet.", + "detail.trendNote": "The trend reflects how much it was used, not how well the work went.", + + // ---- table and card columns ---- + "col.agent": "Agent", + "col.calls": "Requests", + "col.prompt": "Input tokens", + "col.avgPrompt": "Input per request", + "col.cacheRate": "Cache hit rate", + "col.fullPrice": "At full price", + "col.out": "Output", + "col.errorRate": "Failure rate", + "col.p50ttft": "First token p50", + "col.p50ms": "Response p50", + "col.toolTokens": "Tool tokens / request", + "col.protocol": "Protocol", + "col.session": "Session span", + "sort.prompt": "Input tokens", + "sort.toolTokens": "Tool weight", + + // ---- explanations ---- + "explain.prompt.title": "Input tokens", + "explain.prompt.body": "Every token read by the model in this period: fresh input, cache reads, and cache writes. Whatever context the model reads each turn lands here, and this is usually the largest part of the bill.", + "explain.avgPrompt.title": "Input per request", + "explain.avgPrompt.body": "Tokens read by the model per request on average. The total is multiplied by how often you called it; spread over the requests, this shows which harness is heavier per call.", + "explain.cacheRate.title": "Cache hit rate", + "explain.cacheRate.body": "The share of input tokens read from the prompt cache. Cache reads and writes may be priced differently by each provider. A low rate does not by itself imply a weaker model.", + "explain.fullPrice.title": "At full price", + "explain.fullPrice.body": "Fresh input plus cache-write tokens, excluding cache reads. This counts tokens, not money; cache-write prices also differ per model and provider.", + "explain.out.title": "Output tokens", + "explain.out.body": "Tokens the model generated. Input and output are usually priced differently and output can cost more; check your provider’s actual bill.", + "explain.errorRate.title": "Failure rate", + "explain.errorRate.body": "Share of requests that failed; deliberate cancellations are counted separately. Whether a failure burns tokens or money depends on when it happened and what the provider returned.", + "explain.calls.title": "Requests", + "explain.calls.body": "Requests through the gateway. Note that this only covers the harnesses you use; scripts and internal requests are hidden by default.", + "explain.p50ttft.title": "First token p50", + "explain.p50ttft.body": "Half of the requests were faster than this. The time to the first token decides how long you wait before anything appears, so it matters more to the feel than the total.", + "explain.p50ms.title": "Response p50", + "explain.p50ms.body": "Half of the requests were faster than this, measured from entering the gateway to the complete response, including reasoning and generation.", + "explain.toolTokens.title": "Tool tokens / request", + "explain.toolTokens.body": "Estimated from the JSON size of the tool names, parameter schemas, and descriptions sampled at the gateway: bytes ÷ 3.5. This is not an exact tokenizer count; it may hit the cache and it is not the cost.", + "explain.toolShare.title": "Share of input", + "explain.toolShare.body": "Tool definitions as a share of the tokens this harness reads. A 25% share means roughly one in every four input tokens describes a tool, unrelated to the conversation itself.", + "explain.toolCount.title": "Tool count", + "explain.toolCount.body": "How many tool definitions ride along with each request. Count is not cost: a few long descriptions can outweigh a dozen short ones. Compare their sizes.", + "explain.sessionMedian.title": "Session span", + "explain.sessionMedian.body": "The median span between a session’s first and last request within the selected window. It includes idle time and is not continuous work time. Sessions longer than six hours are currently left out.", + "explain.sessionP90.title": "Session span p90", + "explain.sessionP90.body": "90% of sessions were shorter than this. A few very long sessions (a desktop app left open) drag the average up, so this percentile is more trustworthy than the mean.", + "explain.sessionCount.title": "Sessions", + "explain.sessionCount.body": "The number of distinct sessions seen in this period. Session IDs are maintained by each harness, so some of them do not have the concept at all.", + "explain.protocol.title": "Protocol", + "explain.protocol.body": "The protocol mix in the selected period, inferred from the endpoints in the usage log. It may include the upstream protocol after the gateway converted it, so do not read it as the current client configuration.", + "explain.live.title": "In flight", + "explain.live.body": "Requests whose start was recorded by the gateway hook without a matching finish callback, refreshed about every two seconds. A missing finish callback is kept for up to 15 minutes. This is an observed request state, not the state of an agent’s background process.", + "explain.fullPriceShare.title": "Full-price share", + "explain.fullPriceShare.body": "The share of the tokens this harness reads that are billed at full price. The higher this share, the more expensive the same usage is.", + "explain.credits.title": "credits", + "explain.credits.body": "Usage credits recorded by magpie, which depend on how your provider prices things. This is not a token count.", +} + +const zh = { + // ---- app shell ---- + "app.title": "HarnessWeight · agent harness 的 token 重量", + "status.loading": "正在读取…", + "header.sub": "同一个网关后面,每个 agent harness 读了多少 token、命中多少缓存、失败多少次、每轮重发多重的工具定义。", + "aria.periods": "统计周期", + "period.today": "今天", + "period.7d": "7 天", + "period.30d": "30 天", + "clients.toggle": "含脚本和内部请求", + "aria.insights": "结论", + "aria.overview": "总览", + "aria.cardSort": "卡片排序", + "aria.close": "关闭", + "footer.localOnly": "数据只在本机读取,不上传。", + + // ---- sections ---- + "cards.title": "谁在花你的 token", + "cards.hint": "每张卡是一个 Agent。条的长度是输入 token 总量,深色部分合计新鲜输入与缓存写入;价格由供应商决定。", + "activity.connecting": "正在连接实时调用状态…", + "table.title": "逐项对比", + "table.hint": "点表头排序,点一行看详情。", + "tools.title": "工具定义重量", + "tools.hint": "Agent 每次请求都会把自己的工具清单重发一遍,这部分也按 token 计费。", + + // ---- formatting ---- + "dur.second": "秒", + "dur.minute": "分", + "dur.hour": "小时", + "dur.day": "天", + "unit.times": "次", + "unit.items": "个", + + // ---- status and sources ---- + "time.none": "还没有", + "time.secondsAgo": "{n} 秒前", + "time.minutesAgo": "{n} 分钟前", + "time.hoursAgo": "{n} 小时前", + "time.daysAgo": "{n} 天前", + "status.collecting": "采集中 · 最近一次请求 {usage} · 工具采样 {tool}", + "status.stale": "15 分钟内没有新采样 · 上次 {tool}(用一下 Agent 就会恢复)", + "status.waiting": "hook 已装好,等第一条请求经过网关", + "sources.summary": "用量记录 {usageRows} 条 · 工具采样 {toolRows} 条 · 更新于 {time}", + "state.noAgents": "这段时间网关没有记录到 Agent 的请求。用任意 Agent 走一次网关,再回来刷新。", + "state.loadError": "读不到数据:{message}。确认 magpie 网关在运行,再刷新。", + + // ---- activity ---- + "activity.callsInFlight": "{n} 个调用中", + "activity.liveHint": "流光边框表示网关观察到该 Agent 有调用进行中。", + "activity.unavailableHint": "实时调用状态暂不可用;没有流光不代表 Agent 空闲。", + + // ---- overview tiles ---- + "kpi.inputTokens": "输入 token", + "kpi.cacheRate": "缓存命中", + "kpi.outputTokens": "输出 token", + "kpi.failed": "失败", + "kpi.agents": "Agent", + "kpi.credits": "credits", + "kpi.requests": "{count} 次请求", + "kpi.fullPriceOf": "按原价算的 {value}", + "kpi.avgPerCall": "平均 {value}/次", + "kpi.hiddenClients": "另有 {count} 次脚本/内部请求未计", + "kpi.clients": "网关后面的客户端", + "kpi.creditsNote": "magpie 记账的按量额度", + + // ---- cards ---- + "card.topSpender": "花得最多", + "card.inputTokens": "输入 token", + "card.stackLegend": "浅色:缓存读取;深色:按原价", + "card.detailsAria": "{name} 详情", + "card.sessionMedianTitle": "单次会话时长中位数", + "table.topSpenderTitle": "花得最多", + + // ---- tools block ---- + "tools.empty": "还没有采样。网关 hook 会从下一次请求开始记录每个 Agent 带了哪些工具、有多大(只记名字和大小,不记内容)。用一会儿 Agent 后刷新即可。", + "tools.sampling": "从 {since} 开始采样,共 {samples} 次请求。token 数按每 token 约 3.5 字节估算,各 Agent 口径一致。", + "tools.sortBytes": "按字节", + "tools.sortTokens": "按 token", + "tools.sortCount": "按个数", + "tools.sortShare": "占输入比", + "tools.perAgent": "{count} 个 · ≈{tokens} token", + "tools.perAgentShare": "{count} 个 · ≈{tokens} token · 占 {share}", + + // ---- detail drawer ---- + "detail.noRecords": "当前范围没有可展示的记录。", + "detail.countPct": "{count} 次 · {pct}", + "detail.selectedPeriod": "当前筛选范围", + "detail.summaryRequests": "这段时间,它向模型发起了 {calls} 次请求。", + "detail.summaryBody": "每次平均读入 {avg} token;输入中 {cache} 来自缓存。记录到 {failed} 次失败和 {cancelled} 次主动取消。", + "detail.summaryNote": "这里比较的是实际使用记录;任务、模型和使用频率不同,不能直接当作 Agent 能力排名。", + "detail.inputTitle": "① 输入都用在哪里?", + "detail.totalInput": "累计输入", + "detail.avgInput": "每次平均", + "detail.generatedOutput": "生成的输出", + "detail.inputBreakdown": "查看输入明细", + "detail.freshInput": "新鲜输入", + "detail.cacheWrite": "缓存写入", + "detail.credits": "网关记录的额度", + "detail.latencyTitle": "② 等待多久,出错多少?", + "detail.ttft": "首字等待", + "detail.fullResponse": "完整响应", + "detail.failureRate": "失败率", + "detail.latencyNote": "时间采用中位数(p50):有一半的有效记录更快。首字与完整响应各自统计,样本可能不同,不能相减当作生成耗时。失败不等于一定产生费用。", + "detail.toolsTitle": "③ 工具说明有多重?", + "detail.toolsPerRequest": "每次携带工具", + "detail.toolsPerRequestValue": "{count} 个", + "detail.toolSize": "说明体积(估算 token)", + "detail.validSamples": "有效采样", + "detail.validSamplesValue": "{count} 次", + "detail.toolsNote": "工具定义是发给模型的“工具使用说明书”,包含名称、参数格式和描述。长说明书也会占上下文,工具数量少不一定更轻。", + "detail.toolsCaveat": "以 JSON 字节数 ÷ 3.5 估算,非模型 tokenizer 的实测值。工具采样 {samples} 条,用量记录 {calls} 条;两者未逐请求关联,不能据此计算覆盖率。工具说明可能命中缓存,不代表每轮都按原价收费。", + "detail.toolInventory": "查看高频工具名称(最多 40 项)", + "detail.toolFilter": "筛选工具名", + "detail.toolSearchPlaceholder": "输入名称关键词", + "detail.toolInventoryNote": "这里最多显示采样中出现频率最高的 40 个名称;每次采样也最多记录 60 个名称。这不是完整列表、当前启用列表或工具调用次数。", + "detail.toolsEmpty": "尚未采集到工具定义。让该 Agent 通过网关发送新请求后,这里会逐步出现数据。", + "detail.modelsTitle": "④ 用过哪些模型?", + "detail.modelsNote": "按请求次数排列,百分比以该 Agent 全部请求为分母。只显示前 {count} 项。", + "detail.remaining": "其余 / 未列出的记录:{count} 次。", + "detail.protocolsTitle": "⑤ 请求经过哪些协议?", + "detail.protocolsNote": "协议是请求与模型服务之间使用的消息格式。下面显示所选时间范围内的主要协议,按日志中记录的端点推断,可能包含网关转换后的协议;不是当前配置清单。", + "detail.sessionTitle": "⑥ 一次会话持续多久?", + "detail.medianSpan": "中位时长", + "detail.p90Span": "90% 会话短于", + "detail.measuredSessions": "可测会话", + "detail.sessionNote": "按同一会话首末请求的跨度计算,包含思考与闲置,不是连续工作时间。当前统计窗口可能截断会话;{open} 个超过 6 小时的会话未参与时长统计。", + "detail.sessionUnavailable": "暂时无法计算会话时长", + "detail.sessionEmpty": "当前范围没有可用于时长统计的会话记录。请求次数和响应耗时仍可正常查看;这不代表 Agent 没有工作。", + "detail.otherProtocol": "其他 / 未识别", + "detail.cacheReads": "缓存读取", + "detail.nonCacheReads": "非缓存读取", + "detail.noInput": "当前范围没有输入 token 记录,无法计算构成。", + "detail.cacheNote": "缓存读取通常享有折扣。非缓存读取含新鲜输入与缓存写入,各供应商定价不同;token 数不是金额。", + "detail.trendTitle": "每天的输入用量", + "detail.trendEmpty": "数据不足,暂不绘制趋势。", + "detail.trendNote": "趋势反映使用规模,不是任务完成质量。", + + // ---- table and card columns ---- + "col.agent": "Agent", + "col.calls": "请求", + "col.prompt": "输入 token", + "col.avgPrompt": "每次读", + "col.cacheRate": "缓存命中", + "col.fullPrice": "按原价", + "col.out": "输出", + "col.errorRate": "失败率", + "col.p50ttft": "首字 p50", + "col.p50ms": "耗时 p50", + "col.toolTokens": "工具 token/次", + "col.protocol": "协议", + "col.session": "会话时长", + "sort.prompt": "读入 token", + "sort.toolTokens": "工具重量", + + // ---- explanations ---- + "explain.prompt.title": "输入 token", + "explain.prompt.body": "这段时间读进模型的所有 token:新鲜输入 + 缓存读取 + 缓存写入。模型每轮读到的上下文都算在这里,是账单里最大的一块。", + "explain.avgPrompt.title": "每次读", + "explain.avgPrompt.body": "平均每次请求读进模型的 token。总额会被「用了多少次」放大,摊到每次请求才能看出哪个 harness 单次更重。", + "explain.cacheRate.title": "缓存命中", + "explain.cacheRate.body": "读进来的 token 里,有多少是从 prompt cache 取的。命中的部分按折扣价算,没命中的按原价。命中率低不等于模型差,通常是前缀不稳定(比如工具定义变了)。", + "explain.fullPrice.title": "按原价", + "explain.fullPrice.body": "新鲜输入与缓存写入的 token 合计,不含缓存读取。这里统计的是数量,不是金额;不同模型、供应商的缓存写入价格也可能不同。", + "explain.out.title": "输出 token", + "explain.out.body": "模型生成回来的 token。输入和输出通常采用不同单价,输出单价也可能更高;请以实际供应商账单为准。", + "explain.errorRate.title": "失败率", + "explain.errorRate.body": "出错请求占比;主动取消单独统计。失败是否消耗 token 或收费,取决于失败发生的阶段和供应商回执。", + "explain.calls.title": "请求", + "explain.calls.body": "经过网关的请求数。注意这里只算你用的 harness,脚本和内部请求默认隐藏。", + "explain.p50ttft.title": "首字 p50", + "explain.p50ttft.body": "一半的请求比这个快。首字时间决定你等多久能看到第一个字,比总耗时更影响体感。", + "explain.p50ms.title": "耗时 p50", + "explain.p50ms.body": "一半的请求比这个快,指请求从进网关到拿到完整回复的总时长(含思考和生成)。", + "explain.toolTokens.title": "工具 token/次", + "explain.toolTokens.body": "在网关采样工具名、参数 schema 和描述的 JSON 体积,以字节数 ÷ 3.5 估算 token。不是精确 tokenizer 计数;可能命中缓存,也不等于实际费用。", + "explain.toolShare.title": "占输入比", + "explain.toolShare.body": "工具定义占这个 harness 自己读进的 token 的比例。25% 意味着模型读 4 个 token 就有 1 个是工具定义,跟对话内容无关。", + "explain.toolCount.title": "工具个数", + "explain.toolCount.body": "每次请求带了多少个工具定义。注意:个数不等于成本。有的工具描述特别长,少数几个就能顶掉一打短工具。要裁就按字节裁。", + "explain.sessionMedian.title": "单次会话时长", + "explain.sessionMedian.body": "所选窗口内,同一 session 首末请求的跨度中位数,包含闲置,不是持续工作时间。超过 6 小时的会话目前不参与时长统计。", + "explain.sessionP90.title": "长会话 p90", + "explain.sessionP90.body": "九成的会话比这个短。少数超长会话(桌面端挂着不关)会拉高平均值,所以这个数比平均更可靠。", + "explain.sessionCount.title": "会话数", + "explain.sessionCount.body": "这段时间内出现过的不同会话数量。会话 id 由 harness 自己维护,所以有的 harness 没有这个概念。", + "explain.protocol.title": "接入协议", + "explain.protocol.body": "根据用量日志端点统计所选范围内的协议分布,可能包含网关转换后的上游协议。不能当作当前客户端配置。", + "explain.live.title": "正在使用", + "explain.live.body": "网关 hook 已记录请求开始、尚未收到对应结束回调的数量,每约 2 秒刷新。丢失结束回调的记录最多保留 15 分钟;这是观测状态,不是 Agent 的后台进程状态。", + "explain.fullPriceShare.title": "按原价占比", + "explain.fullPriceShare.body": "按原价计费的 token 占它读进的总 token 的比例。这个比例越高,同样的用量越贵。", + "explain.credits.title": "credits", + "explain.credits.body": "magpie 记账的按量额度,取决于你走的 provider 怎么定价,不是 token 数本身。", +} + +export const TEXT = { en, zh } + +// The language the page actually renders in: a recognised language with no +// table yet (zh-TW, ja) renders English, and says so in . +export function pageLanguage(value = "") { + const lang = languageFor(value) + return TEXT[lang] ? lang : "en" +} + +// The insights sentences live here too: the service writes them, so they must +// come out of the same table as the rest of the page. +const insights = { + en: { + prompt: "{hi} reads an average of {avg} tokens per request, {ratio}x {lo}.", + cache: "{hi} has the highest cache hit rate ({hiRate}); {lo} the lowest ({loRate}). Actual pricing depends on the provider and model.", + volume: "{name} accounts for {share} of the input tokens in this period, the largest source of spend.", + errors: "{name} has a failure rate of {rate}; failed requests may still consume tokens.", + tools: "{hi} resends about {tokens} tokens of tool definitions per request ({count} tools), {ratio}x {lo} (about {loTokens} tokens, {loCount} tools).", + }, + zh: { + prompt: "{hi} 每次请求平均读 {avg} token,是 {lo} 的 {ratio} 倍。", + cache: "缓存命中最高的是 {hi}({hiRate}),最低的是 {lo}({loRate})。实际计费取决于供应商和模型。", + volume: "{name} 占了这段时间 {share} 的输入 token,是最大的开销来源。", + errors: "{name} 的失败率是 {rate};失败请求也可能消耗 token。", + tools: "{hi} 每次请求重发的工具定义约 {tokens} token({count} 个),是 {lo}(约 {loTokens} token,{loCount} 个)的 {ratio} 倍。", + }, +} + +// {name} placeholders are filled in; a missing one leaves the placeholder +// visible rather than printing "undefined". +export function translate(language, key, parameters = {}) { + const lang = languageFor(language) + const template = TEXT[lang]?.[key] ?? TEXT.en[key] ?? key + return template.replace(/\{(\w+)\}/g, (match, name) => parameters[name] ?? match) +} + +export function insight(language, kind, parameters = {}) { + const lang = languageFor(language) + const template = insights[lang]?.[kind] ?? insights.en[kind] ?? kind + return template.replace(/\{(\w+)\}/g, (match, name) => parameters[name] ?? match) +} diff --git a/packages/page-harnessweight/app/icons/NOTICE b/packages/page-harnessweight/app/icons/NOTICE new file mode 100644 index 0000000..dccc83a --- /dev/null +++ b/packages/page-harnessweight/app/icons/NOTICE @@ -0,0 +1,6 @@ +These agent icons are the same files magpie shows for each agent. They were +copied from the community plugin @magpie-community/page-agent-office +(packages/agent-office/page/icons, MIT), whose SVG brand marks come from +@lobehub/icons (https://github.com/lobehub/lobe-icons, MIT, Copyright (c) 2023 +LobeHub). Each mark remains the trademark of its owner; it is shown only to +name the agent it belongs to. diff --git a/packages/page-harnessweight/app/icons/aionui.svg b/packages/page-harnessweight/app/icons/aionui.svg new file mode 100644 index 0000000..4f83bfd --- /dev/null +++ b/packages/page-harnessweight/app/icons/aionui.svg @@ -0,0 +1 @@ +AionUi diff --git a/packages/page-harnessweight/app/icons/air.svg b/packages/page-harnessweight/app/icons/air.svg new file mode 100644 index 0000000..540f06b --- /dev/null +++ b/packages/page-harnessweight/app/icons/air.svg @@ -0,0 +1,4 @@ + + + + diff --git a/packages/page-harnessweight/app/icons/alma.png b/packages/page-harnessweight/app/icons/alma.png new file mode 100644 index 0000000..69f9eb3 Binary files /dev/null and b/packages/page-harnessweight/app/icons/alma.png differ diff --git a/packages/page-harnessweight/app/icons/antigravity-color.svg b/packages/page-harnessweight/app/icons/antigravity-color.svg new file mode 100644 index 0000000..3ed10ab --- /dev/null +++ b/packages/page-harnessweight/app/icons/antigravity-color.svg @@ -0,0 +1 @@ +Antigravity \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/aside.svg b/packages/page-harnessweight/app/icons/aside.svg new file mode 100644 index 0000000..5654270 --- /dev/null +++ b/packages/page-harnessweight/app/icons/aside.svg @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/page-harnessweight/app/icons/astrbot.svg b/packages/page-harnessweight/app/icons/astrbot.svg new file mode 100644 index 0000000..b898aab --- /dev/null +++ b/packages/page-harnessweight/app/icons/astrbot.svg @@ -0,0 +1 @@ +AstrBot diff --git a/packages/page-harnessweight/app/icons/atomcode.png b/packages/page-harnessweight/app/icons/atomcode.png new file mode 100644 index 0000000..169b41c Binary files /dev/null and b/packages/page-harnessweight/app/icons/atomcode.png differ diff --git a/packages/page-harnessweight/app/icons/cindy.png b/packages/page-harnessweight/app/icons/cindy.png new file mode 100644 index 0000000..31acb9a Binary files /dev/null and b/packages/page-harnessweight/app/icons/cindy.png differ diff --git a/packages/page-harnessweight/app/icons/claude-color.svg b/packages/page-harnessweight/app/icons/claude-color.svg new file mode 100644 index 0000000..62dc0db --- /dev/null +++ b/packages/page-harnessweight/app/icons/claude-color.svg @@ -0,0 +1 @@ +Claude \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/claudecode-color.svg b/packages/page-harnessweight/app/icons/claudecode-color.svg new file mode 100644 index 0000000..ed1293c --- /dev/null +++ b/packages/page-harnessweight/app/icons/claudecode-color.svg @@ -0,0 +1 @@ +Claude Code \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/cline.svg b/packages/page-harnessweight/app/icons/cline.svg new file mode 100644 index 0000000..f754ea9 --- /dev/null +++ b/packages/page-harnessweight/app/icons/cline.svg @@ -0,0 +1 @@ +Cline \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/codebuddy-color.svg b/packages/page-harnessweight/app/icons/codebuddy-color.svg new file mode 100644 index 0000000..ec353e2 --- /dev/null +++ b/packages/page-harnessweight/app/icons/codebuddy-color.svg @@ -0,0 +1 @@ +CodeBuddy \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/codex-color.svg b/packages/page-harnessweight/app/icons/codex-color.svg new file mode 100644 index 0000000..c77ccfd --- /dev/null +++ b/packages/page-harnessweight/app/icons/codex-color.svg @@ -0,0 +1 @@ +Codex \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/commandcode.svg b/packages/page-harnessweight/app/icons/commandcode.svg new file mode 100644 index 0000000..697f183 --- /dev/null +++ b/packages/page-harnessweight/app/icons/commandcode.svg @@ -0,0 +1 @@ +Command Code diff --git a/packages/page-harnessweight/app/icons/crush.png b/packages/page-harnessweight/app/icons/crush.png new file mode 100644 index 0000000..bb7d339 Binary files /dev/null and b/packages/page-harnessweight/app/icons/crush.png differ diff --git a/packages/page-harnessweight/app/icons/cursor.svg b/packages/page-harnessweight/app/icons/cursor.svg new file mode 100644 index 0000000..a5b2ee3 --- /dev/null +++ b/packages/page-harnessweight/app/icons/cursor.svg @@ -0,0 +1 @@ +Cursor \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/deepseek-color.svg b/packages/page-harnessweight/app/icons/deepseek-color.svg new file mode 100644 index 0000000..3fc2302 --- /dev/null +++ b/packages/page-harnessweight/app/icons/deepseek-color.svg @@ -0,0 +1 @@ +DeepSeek \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/devin.svg b/packages/page-harnessweight/app/icons/devin.svg new file mode 100644 index 0000000..c5f9a18 --- /dev/null +++ b/packages/page-harnessweight/app/icons/devin.svg @@ -0,0 +1 @@ +Devin \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/empryo-color.svg b/packages/page-harnessweight/app/icons/empryo-color.svg new file mode 100644 index 0000000..035a7a1 --- /dev/null +++ b/packages/page-harnessweight/app/icons/empryo-color.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/factory.svg b/packages/page-harnessweight/app/icons/factory.svg new file mode 100644 index 0000000..86ab9ef --- /dev/null +++ b/packages/page-harnessweight/app/icons/factory.svg @@ -0,0 +1 @@ +Factory diff --git a/packages/page-harnessweight/app/icons/geminicli-color.svg b/packages/page-harnessweight/app/icons/geminicli-color.svg new file mode 100644 index 0000000..e15f1f7 --- /dev/null +++ b/packages/page-harnessweight/app/icons/geminicli-color.svg @@ -0,0 +1 @@ +Gemini CLI \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/githubcopilot.svg b/packages/page-harnessweight/app/icons/githubcopilot.svg new file mode 100644 index 0000000..3cbf22a --- /dev/null +++ b/packages/page-harnessweight/app/icons/githubcopilot.svg @@ -0,0 +1 @@ +GithubCopilot \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/goose.svg b/packages/page-harnessweight/app/icons/goose.svg new file mode 100644 index 0000000..1082090 --- /dev/null +++ b/packages/page-harnessweight/app/icons/goose.svg @@ -0,0 +1 @@ +Goose \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/grok.svg b/packages/page-harnessweight/app/icons/grok.svg new file mode 100644 index 0000000..efb1a61 --- /dev/null +++ b/packages/page-harnessweight/app/icons/grok.svg @@ -0,0 +1 @@ +Grok \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/hanako.png b/packages/page-harnessweight/app/icons/hanako.png new file mode 100644 index 0000000..3321ae4 Binary files /dev/null and b/packages/page-harnessweight/app/icons/hanako.png differ diff --git a/packages/page-harnessweight/app/icons/hermes.svg b/packages/page-harnessweight/app/icons/hermes.svg new file mode 100644 index 0000000..4b7ff9d --- /dev/null +++ b/packages/page-harnessweight/app/icons/hermes.svg @@ -0,0 +1 @@ +Hermes Agent diff --git a/packages/page-harnessweight/app/icons/jcode.svg b/packages/page-harnessweight/app/icons/jcode.svg new file mode 100644 index 0000000..5dea061 --- /dev/null +++ b/packages/page-harnessweight/app/icons/jcode.svg @@ -0,0 +1 @@ +jcode diff --git a/packages/page-harnessweight/app/icons/kilocode.svg b/packages/page-harnessweight/app/icons/kilocode.svg new file mode 100644 index 0000000..ff05262 --- /dev/null +++ b/packages/page-harnessweight/app/icons/kilocode.svg @@ -0,0 +1 @@ +Kilo Code \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/kimi.svg b/packages/page-harnessweight/app/icons/kimi.svg new file mode 100644 index 0000000..1915850 --- /dev/null +++ b/packages/page-harnessweight/app/icons/kimi.svg @@ -0,0 +1 @@ +Kimi \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/kiro-color.svg b/packages/page-harnessweight/app/icons/kiro-color.svg new file mode 100644 index 0000000..0c651b9 --- /dev/null +++ b/packages/page-harnessweight/app/icons/kiro-color.svg @@ -0,0 +1 @@ +Kiro \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/lody.png b/packages/page-harnessweight/app/icons/lody.png new file mode 100644 index 0000000..512bffb Binary files /dev/null and b/packages/page-harnessweight/app/icons/lody.png differ diff --git a/packages/page-harnessweight/app/icons/meta-color.svg b/packages/page-harnessweight/app/icons/meta-color.svg new file mode 100644 index 0000000..4604edd --- /dev/null +++ b/packages/page-harnessweight/app/icons/meta-color.svg @@ -0,0 +1 @@ +Meta diff --git a/packages/page-harnessweight/app/icons/mimocode.svg b/packages/page-harnessweight/app/icons/mimocode.svg new file mode 100644 index 0000000..d5ae60c --- /dev/null +++ b/packages/page-harnessweight/app/icons/mimocode.svg @@ -0,0 +1,11 @@ + + MiMo Code + + + + + + + + + diff --git a/packages/page-harnessweight/app/icons/minimax-color.svg b/packages/page-harnessweight/app/icons/minimax-color.svg new file mode 100644 index 0000000..beb7adb --- /dev/null +++ b/packages/page-harnessweight/app/icons/minimax-color.svg @@ -0,0 +1 @@ +Minimax \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/mistermorph-color.svg b/packages/page-harnessweight/app/icons/mistermorph-color.svg new file mode 100644 index 0000000..28b42a4 --- /dev/null +++ b/packages/page-harnessweight/app/icons/mistermorph-color.svg @@ -0,0 +1 @@ + diff --git a/packages/page-harnessweight/app/icons/mothx.png b/packages/page-harnessweight/app/icons/mothx.png new file mode 100644 index 0000000..3477149 Binary files /dev/null and b/packages/page-harnessweight/app/icons/mothx.png differ diff --git a/packages/page-harnessweight/app/icons/omp.svg b/packages/page-harnessweight/app/icons/omp.svg new file mode 100644 index 0000000..eb4d17e --- /dev/null +++ b/packages/page-harnessweight/app/icons/omp.svg @@ -0,0 +1 @@ +omp \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/openchamber.svg b/packages/page-harnessweight/app/icons/openchamber.svg new file mode 100644 index 0000000..2471fc7 --- /dev/null +++ b/packages/page-harnessweight/app/icons/openchamber.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/packages/page-harnessweight/app/icons/opencode.svg b/packages/page-harnessweight/app/icons/opencode.svg new file mode 100644 index 0000000..9c4cb89 --- /dev/null +++ b/packages/page-harnessweight/app/icons/opencode.svg @@ -0,0 +1 @@ +opencode \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/penguin-color.svg b/packages/page-harnessweight/app/icons/penguin-color.svg new file mode 100644 index 0000000..0d48619 --- /dev/null +++ b/packages/page-harnessweight/app/icons/penguin-color.svg @@ -0,0 +1 @@ + diff --git a/packages/page-harnessweight/app/icons/pi.svg b/packages/page-harnessweight/app/icons/pi.svg new file mode 100644 index 0000000..5122fb5 --- /dev/null +++ b/packages/page-harnessweight/app/icons/pi.svg @@ -0,0 +1 @@ +Pi \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/qoder.svg b/packages/page-harnessweight/app/icons/qoder.svg new file mode 100644 index 0000000..0ef248b --- /dev/null +++ b/packages/page-harnessweight/app/icons/qoder.svg @@ -0,0 +1 @@ +Qoder \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/qwen-color.svg b/packages/page-harnessweight/app/icons/qwen-color.svg new file mode 100644 index 0000000..f2d0ada --- /dev/null +++ b/packages/page-harnessweight/app/icons/qwen-color.svg @@ -0,0 +1 @@ +Qwen \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/raycast.svg b/packages/page-harnessweight/app/icons/raycast.svg new file mode 100644 index 0000000..ce23cfb --- /dev/null +++ b/packages/page-harnessweight/app/icons/raycast.svg @@ -0,0 +1 @@ +Raycast \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/reasonix-color.svg b/packages/page-harnessweight/app/icons/reasonix-color.svg new file mode 100644 index 0000000..1eae941 --- /dev/null +++ b/packages/page-harnessweight/app/icons/reasonix-color.svg @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/page-harnessweight/app/icons/snow.png b/packages/page-harnessweight/app/icons/snow.png new file mode 100644 index 0000000..02dfd5b Binary files /dev/null and b/packages/page-harnessweight/app/icons/snow.png differ diff --git a/packages/page-harnessweight/app/icons/stepfun-color.svg b/packages/page-harnessweight/app/icons/stepfun-color.svg new file mode 100644 index 0000000..920e8a6 --- /dev/null +++ b/packages/page-harnessweight/app/icons/stepfun-color.svg @@ -0,0 +1 @@ +Stepfun \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/t3code.svg b/packages/page-harnessweight/app/icons/t3code.svg new file mode 100644 index 0000000..2ed6850 --- /dev/null +++ b/packages/page-harnessweight/app/icons/t3code.svg @@ -0,0 +1,4 @@ + + + + diff --git a/packages/page-harnessweight/app/icons/trae.svg b/packages/page-harnessweight/app/icons/trae.svg new file mode 100644 index 0000000..8f42e96 --- /dev/null +++ b/packages/page-harnessweight/app/icons/trae.svg @@ -0,0 +1 @@ +TRAE \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/workbuddy-color.svg b/packages/page-harnessweight/app/icons/workbuddy-color.svg new file mode 100644 index 0000000..faf7e5d --- /dev/null +++ b/packages/page-harnessweight/app/icons/workbuddy-color.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/xai.svg b/packages/page-harnessweight/app/icons/xai.svg new file mode 100644 index 0000000..536e713 --- /dev/null +++ b/packages/page-harnessweight/app/icons/xai.svg @@ -0,0 +1 @@ +Grok \ No newline at end of file diff --git a/packages/page-harnessweight/app/icons/zcode.png b/packages/page-harnessweight/app/icons/zcode.png new file mode 100644 index 0000000..377db60 Binary files /dev/null and b/packages/page-harnessweight/app/icons/zcode.png differ diff --git a/packages/page-harnessweight/app/icons/zed.svg b/packages/page-harnessweight/app/icons/zed.svg new file mode 100644 index 0000000..c286d0f --- /dev/null +++ b/packages/page-harnessweight/app/icons/zed.svg @@ -0,0 +1 @@ +Zed diff --git a/packages/page-harnessweight/app/icons/zoo-code.png b/packages/page-harnessweight/app/icons/zoo-code.png new file mode 100644 index 0000000..e671597 Binary files /dev/null and b/packages/page-harnessweight/app/icons/zoo-code.png differ diff --git a/packages/page-harnessweight/app/index.html b/packages/page-harnessweight/app/index.html new file mode 100644 index 0000000..2716c83 --- /dev/null +++ b/packages/page-harnessweight/app/index.html @@ -0,0 +1,80 @@ + + + + + +HarnessWeight · agent harness token weight + + + + + + +
+
+ +
+

HarnessWeight

+

正在读取…

+

同一个网关后面,每个 agent harness 读了多少 token、命中多少缓存、失败多少次、每轮重发多重的工具定义。

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

谁在花你的 token

+

每张卡是一个 Agent。条的长度是这段时间读进模型的总 token,深色部分是按原价算的(没命中缓存)。

+
+

正在连接实时调用状态…

+
+
+
+ +
+
+

逐项对比

+

点表头排序,点一行看详情。

+
+
+
+ +
+
+

工具定义重量

+

Agent 每次请求都会把自己的工具清单重发一遍,这部分也按 token 计费。

+
+
+
+ + +
+ + + + + + + diff --git a/packages/page-harnessweight/app/logo-dark.svg b/packages/page-harnessweight/app/logo-dark.svg new file mode 100644 index 0000000..0f626bb --- /dev/null +++ b/packages/page-harnessweight/app/logo-dark.svg @@ -0,0 +1,17 @@ + +HarnessWeight + + + + + + + + + + + + + + + diff --git a/packages/page-harnessweight/app/logo.svg b/packages/page-harnessweight/app/logo.svg new file mode 100644 index 0000000..142cf03 --- /dev/null +++ b/packages/page-harnessweight/app/logo.svg @@ -0,0 +1,17 @@ + +HarnessWeight + + + + + + + + + + + + + + + diff --git a/packages/page-harnessweight/app/style.css b/packages/page-harnessweight/app/style.css new file mode 100644 index 0000000..09e06ab --- /dev/null +++ b/packages/page-harnessweight/app/style.css @@ -0,0 +1,310 @@ +/* HarnessWeight — brand v2: teal #17A9A2, orange #F26B1D, warm yellow #FFB547, graphite #2B2F36. + Orange marks "the most expensive one" only; it is never decoration. */ +:root { + --bg: #F6F7F8; --panel: #FFFFFF; --panel-2: #F1F3F5; --fg: #1B1E23; --muted: #646B76; --line: #E4E7EB; + --teal: #17A9A2; --teal-2: #5EE0D2; --teal-ink: #0E7C77; --teal-soft: #E3F6F4; + --orange: #F26B1D; --orange-2: #FFA23A; --orange-soft: #FFF0E5; --yellow: #FFB547; + --ink: #2B2F36; --bar: #E6E9ED; --danger: #C2410C; + --radius: 14px; --shadow: 0 1px 2px rgba(16,24,40,.04), 0 4px 16px rgba(16,24,40,.05); + --tip-bg: #1B1E23; --tip-fg: #F2F4F7; --teal-glow: rgba(23,169,162,.30); --chip-bg: #F1F3F5; + --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; + color-scheme: light; +} +:root[data-theme="dark"] { + --bg: #0D1117; --panel: #151B23; --panel-2: #1B222C; --fg: #E6EAF0; --muted: #8B94A3; --line: #252D38; + --teal: #2CC5BC; --teal-ink: #5EE0D2; --teal-soft: #0F2A2A; --orange-soft: #2E1C10; + --ink: #3A414D; --bar: #232B36; --danger: #FF8A4C; + --tip-bg: #E9EDF2; --tip-fg: #1B1E23; --teal-glow: rgba(44,197,188,.34); --chip-bg: #1B222C; + --shadow: none; color-scheme: dark; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #0D1117; --panel: #151B23; --panel-2: #1B222C; --fg: #E6EAF0; --muted: #8B94A3; --line: #252D38; + --teal: #2CC5BC; --teal-ink: #5EE0D2; --teal-soft: #0F2A2A; --orange-soft: #2E1C10; + --ink: #3A414D; --bar: #232B36; --danger: #FF8A4C; --shadow: none; color-scheme: dark; + --tip-bg: #E9EDF2; --tip-fg: #1B1E23; --teal-glow: rgba(44,197,188,.34); --chip-bg: #1B222C; + } +} +.logo.on-dark { display: none; } +:root[data-theme="dark"] .logo.on-dark { display: block; } :root[data-theme="dark"] .logo.on-light { display: none; } +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .logo.on-dark { display: block; } :root:not([data-theme="light"]) .logo.on-light { display: none; } } + +* { box-sizing: border-box; } +body { margin: 0; background: var(--bg); color: var(--fg); + font: 14px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; + -webkit-font-smoothing: antialiased; } +.num, td.n, th.n { font-variant-numeric: tabular-nums; } + +.top, main, .foot { max-width: 1120px; margin: 0 auto; padding-left: 24px; padding-right: 24px; } +.top { display: flex; flex-wrap: wrap; gap: 16px; align-items: center; justify-content: space-between; padding-top: 28px; padding-bottom: 20px; } +.brand { display: flex; gap: 12px; align-items: center; } +.logo { display: block; } +h1 { margin: 0; font-size: 22px; font-weight: 680; letter-spacing: -.01em; } +.sub { margin: 2px 0 0; color: var(--muted); font-size: 13px; } +.controls { display: flex; gap: 14px; align-items: center; flex-wrap: wrap; } +.seg { display: inline-flex; padding: 3px; gap: 2px; background: var(--panel-2); border: 1px solid var(--line); border-radius: 10px; } +.seg button { border: 0; background: transparent; color: var(--muted); font: inherit; font-size: 13px; padding: 5px 13px; border-radius: 7px; cursor: pointer; } +.seg button:hover { color: var(--fg); } +.seg button[aria-selected="true"] { background: var(--panel); color: var(--fg); box-shadow: var(--shadow); font-weight: 600; } +.seg button:focus-visible, .toggle input:focus-visible, button:focus-visible, tr:focus-visible, .card:focus-visible { outline: 2px solid var(--teal); outline-offset: 2px; } +.toggle { color: var(--muted); font-size: 13px; display: inline-flex; gap: 6px; align-items: center; cursor: pointer; } +.toggle input { accent-color: var(--teal); } + +.insights { display: grid; gap: 8px; margin-bottom: 18px; } +.insight { display: flex; gap: 10px; align-items: flex-start; padding: 11px 14px; border-radius: 12px; background: var(--teal-soft); color: var(--fg); font-size: 13.5px; } +.insight::before { content: ""; flex: none; width: 6px; height: 6px; margin-top: 8px; border-radius: 50%; background: var(--teal); } +.insight.hot { background: var(--orange-soft); } .insight.hot::before { background: var(--orange); } + +.kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 26px; } +.kpi { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px; box-shadow: var(--shadow); } +.kpi .k { color: var(--muted); font-size: 12px; } +.kpi .v { font-size: 24px; font-weight: 680; letter-spacing: -.01em; margin-top: 2px; } +.kpi .s { color: var(--muted); font-size: 12px; margin-top: 2px; } + +.block { margin-bottom: 30px; } +.block-head { margin-bottom: 12px; } +h2 { margin: 0; font-size: 16px; font-weight: 650; } +.hint { margin: 3px 0 0; color: var(--muted); font-size: 12.5px; } + +.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 16px; box-shadow: var(--shadow); cursor: pointer; transition: border-color .15s, transform .15s; } +.card:hover { border-color: color-mix(in srgb, var(--teal) 45%, var(--line)); transform: translateY(-1px); } +.card:active { transform: translateY(0) scale(.995); } +.card.top1 { border-color: color-mix(in srgb, var(--orange) 55%, var(--line)); } +.card-head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; } +.card-name { font-weight: 650; font-size: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.tag { font-size: 11px; padding: 1px 8px; border-radius: 999px; background: var(--orange); color: #fff; font-weight: 600; white-space: nowrap; } +.card-big { margin-top: 10px; font-size: 26px; font-weight: 700; letter-spacing: -.01em; } +.card-big small { font-size: 12px; font-weight: 500; color: var(--muted); margin-left: 4px; } +.stack { margin-top: 8px; height: 8px; border-radius: 4px; background: var(--bar); overflow: hidden; display: flex; } +.stack .cached { background: linear-gradient(90deg, var(--teal-2), var(--teal)); } +.stack .full { background: var(--ink); } +.card.top1 .stack .full { background: linear-gradient(90deg, var(--orange-2), var(--orange)); } +.card-meta { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; margin-top: 12px; } +.card-meta > div { font-size: 12px; color: var(--muted); min-width: 0; display: flex; flex-direction: column; align-items: flex-start; gap: 1px; } +.card-meta b { color: var(--fg); font-size: 13.5px; font-weight: 600; } +/* the label under the number wraps as a word, never one character per line */ +/* labels may be longer than the column (English); wrap, never spill into the next one */ +.card-meta .tipwrap { display: inline; white-space: normal; max-width: 100%; line-height: 1.35; } +.card-meta .tipwrap .tip { margin-left: 3px; vertical-align: 1px; } +.spark { display: block; width: 100%; height: 34px; margin-top: 10px; } +.spark path.l { fill: none; stroke: var(--teal); stroke-width: 1.6; } +.spark path.a { fill: color-mix(in srgb, var(--teal) 14%, transparent); } + +.table-wrap { overflow-x: auto; background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); } +table { width: 100%; border-collapse: collapse; font-size: 12.5px; } +table th, table td { padding: 9px 9px; } +table th .tip { margin-left: 2px; } +table td.n, table th.n { padding-left: 7px; padding-right: 7px; } +table .proto-cell { max-width: 92px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +th { text-align: left; font-weight: 600; color: var(--muted); font-size: 12px; padding: 11px 12px; border-bottom: 1px solid var(--line); white-space: nowrap; cursor: pointer; user-select: none; } +th:hover { color: var(--fg); } +th[aria-sort] { color: var(--fg); } +th[aria-sort="descending"]::after { content: " ↓"; } th[aria-sort="ascending"]::after { content: " ↑"; } +th.n, td.n { text-align: right; } +td { padding: 11px 12px; border-bottom: 1px solid var(--line); white-space: nowrap; } +tbody tr { cursor: pointer; } +tbody tr:hover td { background: var(--panel-2); } +tbody tr:last-child td { border-bottom: 0; } +td.agent { font-weight: 600; } +.bad { color: var(--danger); font-weight: 600; } +.dot { display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 8px; background: var(--teal); vertical-align: 0; } +.dot.hot { background: var(--orange); } + +.tool-row { display: grid; grid-template-columns: 190px 1fr 190px; gap: 12px; align-items: center; padding: 9px 0; border-bottom: 1px solid var(--line); } +.tool-row:last-child { border-bottom: 0; } +.tool-track { height: 10px; background: var(--bar); border-radius: 5px; overflow: hidden; } +.tool-fill { height: 100%; background: linear-gradient(90deg, var(--teal-2), var(--teal)); border-radius: 5px; } +.tool-fill.hot { background: linear-gradient(90deg, var(--orange-2), var(--orange)); } +.tool-val { text-align: right; color: var(--muted); font-size: 12.5px; } +.waiting { background: var(--panel); border: 1px dashed var(--line); border-radius: var(--radius); padding: 18px; color: var(--muted); font-size: 13px; } + +.state { text-align: center; color: var(--muted); padding: 40px 0; } +.state.err { color: var(--danger); } +.skeleton { background: linear-gradient(90deg, var(--panel-2), var(--line), var(--panel-2)); background-size: 200% 100%; animation: sk 1.2s linear infinite; border-radius: var(--radius); min-height: 86px; } +@keyframes sk { to { background-position: -200% 0; } } + +.drawer { position: fixed; top: 0; right: 0; bottom: 0; width: min(580px, 100vw); background: var(--panel); border-left: 1px solid var(--line); box-shadow: -12px 0 40px rgba(0,0,0,.12); padding: 22px 22px 40px; overflow-y: auto; transform: translateX(100%); transition: transform .22s cubic-bezier(.2,.8,.2,1); z-index: 20; } +.drawer.open { transform: none; } +.scrim { position: fixed; inset: 0; background: rgba(0,0,0,.25); z-index: 10; } +.close { position: absolute; top: 14px; right: 14px; border: 0; background: var(--panel-2); color: var(--fg); width: 30px; height: 30px; border-radius: 8px; font-size: 18px; cursor: pointer; } +.detail h3 { margin: 0 0 4px; font-size: 18px; } +.detail .sec { margin-top: 20px; } +.detail .sec h4 { margin: 0 0 8px; font-size: 12px; color: var(--muted); font-weight: 600; letter-spacing: .02em; } +.dl { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 16px; } +.dl div { font-size: 12px; color: var(--muted); } +.dl b { display: block; font-size: 14px; color: var(--fg); font-weight: 600; } +.chips { display: flex; flex-wrap: wrap; gap: 6px; } +.chip { font-size: 12px; padding: 3px 9px; border-radius: 999px; background: var(--panel-2); border: 1px solid var(--line); } +.chip.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11.5px; border-radius: 6px; } +.spark.big { height: 80px; } + +.foot { display: flex; flex-wrap: wrap; gap: 6px 18px; color: var(--muted); font-size: 12px; padding-top: 10px; padding-bottom: 36px; } +.foot a { color: var(--teal-ink); text-decoration: none; margin-left: auto; } + +@media (max-width: 640px) { + .top, main, .foot { padding-left: 14px; padding-right: 14px; } + .tool-row { grid-template-columns: 96px 1fr 104px; gap: 8px; } + .card-big { font-size: 22px; } +} +@media (prefers-reduced-motion: reduce) { .card, .drawer { transition: none; } .skeleton { animation: none; } } + +.status { display: inline-flex; align-items: center; gap: 6px; margin: 4px 0 2px; font-size: 12px; color: var(--muted); } +.status::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--muted); } +.status.live { color: var(--teal-ink); } .status.live::before { background: var(--teal); box-shadow: 0 0 0 3px var(--teal-soft); animation: pulse 2s ease-in-out infinite; } +.status.idle::before { background: var(--yellow); } +@keyframes pulse { 50% { box-shadow: 0 0 0 5px transparent; } } +@media (prefers-reduced-motion: reduce) { .status.live::before { animation: none; } } + +.mark { display: inline-flex; flex: none; align-items: center; justify-content: center; border-radius: 6px; overflow: hidden; vertical-align: middle; } +.mark img { display: block; width: 100%; height: 100%; object-fit: contain; } +.mark.letter { color: #fff; font-weight: 700; line-height: 1; } +.who { display: inline-flex; align-items: center; gap: 8px; min-width: 0; } +.card-name { display: inline-flex; align-items: center; gap: 9px; } +.who .dot { margin: 0 0 0 2px; } +:root[data-theme="dark"] .mark img { background: #fff; border-radius: 5px; padding: 1px; } + +.tool-row .who { overflow: hidden; } .tool-row .who b { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + +/* ---------- explanations: a small "?" that opens the note ---------- */ +.tipwrap { display: inline-flex; align-items: baseline; gap: 4px; } +.tip { + position: relative; display: inline-flex; align-items: center; justify-content: center; flex: none; + width: 14px; height: 14px; border-radius: 50%; + border: 1px solid var(--line); color: var(--muted); font-size: 9px; line-height: 1; + cursor: help; vertical-align: middle; outline: none; +} +.tip::before { content: "?"; } +.tip:hover, .tip:focus { border-color: var(--teal); color: var(--teal-ink); background: var(--teal-soft); } +.tip-body { + position: absolute; bottom: calc(100% + 8px); left: 50%; transform: translateX(-50%) translateY(4px); + width: max-content; max-width: 280px; padding: 9px 11px; border-radius: 8px; + white-space: normal; font-weight: 400; + background: var(--tip-bg); color: var(--tip-fg); border: 1px solid var(--line); + box-shadow: 0 8px 28px rgba(0,0,0,.18); font-size: 12px; line-height: 1.55; font-weight: 400; + opacity: 0; pointer-events: none; transition: opacity .14s ease, transform .14s ease; z-index: 40; text-align: left; +} +.tip-body::after { + content: ""; position: absolute; top: 100%; left: 50%; transform: translateX(-50%); + border: 6px solid transparent; border-top-color: var(--tip-bg); +} +.tip.open .tip-body, .tip:hover .tip-body, .tip:focus-within .tip-body { opacity: 1; transform: translateX(-50%) translateY(0); } +.tip-body { display: none; } +.floating-tip { position: fixed; z-index: 100; width: max-content; max-width: min(280px, calc(100vw - 16px)); padding: 10px 12px; border-radius: 8px; background: var(--tip-bg); color: var(--tip-fg); border: 1px solid var(--line); box-shadow: 0 8px 28px rgba(0,0,0,.25); font-size: 12px; line-height: 1.55; white-space: normal; text-align: left; pointer-events: none; } +.floating-tip b { display: block; font-weight: 700; margin-bottom: 3px; } +/* near the top of the page the note would go off-screen: open downwards */ +.tip.flip .tip-body { bottom: auto; top: calc(100% + 8px); transform: translateX(-50%) translateY(-4px); } +.tip.flip.open .tip-body, .tip.flip:hover .tip-body, .tip.flip:focus-within .tip-body { transform: translateX(-50%) translateY(0); } +.tip.flip .tip-body::after { top: auto; bottom: 100%; border-top-color: transparent; border-bottom-color: var(--tip-bg); } + +/* ---------- sorting pills ---------- */ +.sortbar { display: flex; flex-wrap: wrap; gap: 6px; margin: 10px 0 2px; } +.sortbar.inline { display: inline-flex; margin: 6px 0 0; vertical-align: middle; } +.pill { + border: 1px solid var(--line); background: transparent; color: var(--muted); + border-radius: 999px; padding: 4px 11px; font-size: 12px; cursor: pointer; line-height: 1.4; + transition: background .12s ease, color .12s ease, border-color .12s ease; +} +.pill:hover { border-color: var(--teal); color: var(--teal-ink); } +.pill.on { background: var(--teal-soft); border-color: var(--teal); color: var(--teal-ink); font-weight: 600; } +.pill:focus-visible { outline: 2px solid var(--teal); outline-offset: 2px; } + +/* ---------- an agent in use right now ---------- */ +@property --flow-angle { syntax: ''; inherits: false; initial-value: 0deg; } +.card.live { position: relative; border-color: rgba(70,210,220,.38); box-shadow: 0 0 14px rgba(50,200,220,.16), var(--shadow); } +.card.live::before { + content: ""; position: absolute; inset: -1px; border-radius: inherit; pointer-events: none; + padding: 2px; + background: conic-gradient(from var(--flow-angle), transparent 0deg, rgba(50,190,225,.18) 145deg, #91fcff 195deg, #2cc8e4 215deg, transparent 265deg); + -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); + -webkit-mask-composite: xor; + mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); + mask-composite: exclude; + animation: flow-border 3s linear infinite; +} +@keyframes flow-border { to { --flow-angle: 360deg; } } +.live-badge { + display: inline-flex; align-items: center; gap: 5px; color: var(--teal-ink); + background: var(--teal-soft); border-radius: 999px; padding: 2px 8px 2px 6px; font-size: 11px; font-weight: 600; +} +.live-badge::before { + content: ""; width: 16px; height: 12px; flex: none; + background: linear-gradient(var(--teal),var(--teal)) left bottom / 3px 40% no-repeat, + linear-gradient(var(--teal),var(--teal)) center bottom / 3px 100% no-repeat, + linear-gradient(var(--teal),var(--teal)) right bottom / 3px 60% no-repeat; + animation: activity-bars .9s ease-in-out infinite alternate; +} +.live-badge .tip { margin-left: 2px; } +@keyframes activity-bars { + 0% { background-size: 3px 30%, 3px 90%, 3px 50%; } + 50% { background-size: 3px 95%, 3px 40%, 3px 75%; } + 100% { background-size: 3px 50%, 3px 65%, 3px 100%; } +} +@media (prefers-reduced-motion: reduce) { + .card.live::before, .live-badge::before { animation: none; } + .card.live { border-width: 2px; } +} + +/* ---------- small bits on the card ---------- */ +.card-foot { display: flex; gap: 8px; margin-top: 8px; font-size: 11px; color: var(--muted); } +.card-foot .proto, .card-foot .dur { + background: var(--chip-bg); border-radius: 5px; padding: 1px 6px; white-space: nowrap; +} +.proto-cell { font-family: var(--mono); font-size: 11px; color: var(--muted); } + +/* a label followed by a tip marker must not wrap */ +.kpi .k, th { white-space: nowrap; } +.card-meta .tipwrap { gap: 3px; align-items: center; } +.kpi .k { display: flex; align-items: center; gap: 2px; } +.kpi .k .tipwrap { gap: 3px; } +.live-badge { flex: none; white-space: nowrap; align-self: center; } +.live-badge .tipwrap { gap: 2px; } +.live-badge .tip { width: 13px; height: 13px; font-size: 9px; } +/* the live badge sits on one line with the name */ +.card-head { flex-wrap: wrap; row-gap: 4px; } +.card-name { min-width: 0; flex: 1 1 auto; } +/* the badge and the "most expensive" tag go to the next line on narrow cards */ +.card-head .live-badge, .card-head .tag { order: 2; } +/* the table header must breathe: many columns now carry a tip marker */ +th .tip { margin-left: 3px; } + +.detail-guide { font-size: 14px; line-height: 1.65; } +.detail-guide .sec { padding: 22px 0; border-top: 1px solid var(--line); margin-top: 0; } +.detail.detail-guide .sec h4 { font-size: 15px; color: var(--fg); margin: 0 0 12px; } +.detail-guide .detail-metrics b { white-space: nowrap; font-size: clamp(16px,2vw,22px); } +.drawer { overflow-x: hidden; } +.detail-guide .tip-body { left:auto; right:-12px; transform:translateY(4px); max-width:min(280px,75vw); } +.detail-guide .tip.open .tip-body, .detail-guide .tip:hover .tip-body { transform:translateY(0); } +.detail-guide .tip-body::after { left:auto; right:12px; transform:none; } +.detail-summary { padding: 16px; border-radius: 12px; background: var(--teal-soft); margin: 16px 0 24px; } +.detail-summary strong { color: var(--teal-ink); } +.detail-summary p { margin: 8px 0; } +.detail-summary small { color: var(--muted); } +.detail-metrics { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 10px; margin: 14px 0; } +.detail-metrics > div { padding: 12px; background: var(--panel-2); border-radius: 9px; } +.detail-metrics span { color: var(--muted); font-size: 11px; } +.detail-metrics b { display: block; font-size: 22px; color: var(--fg); font-variant-numeric: tabular-nums; } +.composition { display: flex; height: 16px; border-radius: 5px; overflow: hidden; } +.composition > span:first-child { background: var(--teal); } +.composition > span:last-child { background: var(--orange); } +.composition-key { display: flex; flex-wrap: wrap; gap: 8px 20px; margin: 8px 0; font-size: 12px; } +.composition-key span:first-child { color: var(--teal-ink); } +.composition-key span:last-child { color: var(--orange); } +.dist-row { margin: 12px 0; } +.dist-row > div:first-child { display:flex; justify-content:space-between; gap:12px; font-size:12px; } +.dist-row > div:first-child > span:first-child { overflow-wrap: anywhere; } +.dist-row .num { color:var(--muted); flex-shrink:0; } +.dist-track { background:var(--bar); height:7px; border-radius:4px; overflow:hidden; margin-top:5px; } +.dist-track span { background:var(--teal); display:block; height:100%; } +.detail-guide details { padding:12px; background:var(--panel-2); border-radius:9px; } +.detail-guide summary { cursor:pointer; font-weight:600; } +.detail-facts { display:grid; grid-template-columns:1fr auto; gap:8px; } +.detail-facts dd { margin:0; font-variant-numeric:tabular-nums; } +.tool-search { display:block; font-size:12px; margin:12px 0; color:var(--muted); } +.tool-search input { display:block; width:100%; margin-top:5px; padding:9px; border:1px solid var(--line); border-radius:7px; background:var(--panel); color:var(--fg); } +.tool-list { max-height:240px; overflow:auto; } +.tool-list [hidden] { display:none; } +.empty-note { padding:14px; background:var(--panel-2); border-radius:9px; color:var(--muted); } +.empty-note strong { color:var(--fg); } +.empty-note p { margin-bottom:0; } +@media(max-width:500px) { .detail-metrics { gap:5px; } .detail-metrics > div { padding:8px; } .detail-metrics b { font-size:18px; } } diff --git a/packages/page-harnessweight/brand/assets/lens-dark.svg b/packages/page-harnessweight/brand/assets/lens-dark.svg new file mode 100644 index 0000000..0f626bb --- /dev/null +++ b/packages/page-harnessweight/brand/assets/lens-dark.svg @@ -0,0 +1,17 @@ + +HarnessWeight + + + + + + + + + + + + + + + diff --git a/packages/page-harnessweight/brand/assets/lens.svg b/packages/page-harnessweight/brand/assets/lens.svg new file mode 100644 index 0000000..142cf03 --- /dev/null +++ b/packages/page-harnessweight/brand/assets/lens.svg @@ -0,0 +1,17 @@ + +HarnessWeight + + + + + + + + + + + + + + + diff --git a/packages/page-harnessweight/harnessweight.hooks.mjs b/packages/page-harnessweight/harnessweight.hooks.mjs new file mode 100644 index 0000000..488a152 --- /dev/null +++ b/packages/page-harnessweight/harnessweight.hooks.mjs @@ -0,0 +1,403 @@ +// HarnessWeight — the gateway hook that watches what each agent behind the +// gateway costs you. +// +// {"port": 3496, "dataDir": "", "gatewayTimeoutMs": 2000, "agents": []} +// +// One magpie request is one model request: the gateway routes it, the client +// (the agent) has already assembled the body, and the tool declarations in +// that body are what the agent re-sends on every turn. Their size is the +// part of the input the user pays for again and again, and no upstream +// usage page counts it per agent. +// +// What this hook records, per request, by agent: +// - the tokens the upstream reported (input, output, cache read, cache write) +// - the tool declarations' size: how many, how many bytes, and their names +// - the outcome (the request succeeded or not) +// +// What it never records: the conversation, the prompt, the user's words, the +// tool arguments, the credentials. Only names, counts and numbers, so the +// file it writes is safe to keep and to show. +// +// The rows go to ~/.config/magpie/harnessweight/tools.jsonl (or dataDir). The page (a +// local service next to it) reads that file and draws the comparison. +// +// The gateway's contract for this file: +// export async function onRequest(body, ctx) — before routing. Returning +// undefined leaves the request as it was; returning a body that changed +// the tools, the model or the streaming rolls the whole request back. +// This hook only reads, so it returns undefined. +// export async function onResponse(reply, ctx) — after the reply is whole. +// ctx.request is the accepted request, ctx.success says whether it +// worked. This is best-effort: a notification may be lost, and that is +// fine, a missing row is not a wrong row. + +import { appendFile, mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises" +import { randomUUID } from "node:crypto" +import { basename, dirname } from "node:path" +import { measureTools } from "./lib/measure.mjs" +import { toolsLog } from "./lib/paths.mjs" +import { activity } from "./lib/activity.mjs" + + +// Rows older than this are dropped when a generation is retired: the file is +// a rolling window of the recent past, not a ledger of all time. +const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000 +// One generation is rewritten when it passes this size. The previous +// generation is kept beside it as tools.jsonl.1, so two generations hold at +// most about 16 MiB; the next rollover retires the older one. +export const MAX_FILE_BYTES = 8 * 1024 * 1024 +// How often the age of the rows is checked. The check reads the file, so it +// runs on an hourly cadence rather than on every request. +export const AGE_CHECK_MS = 60 * 60 * 1000 +// The longest a response waits for the lock. The hook runs on the response +// path, so contention must cost the user almost nothing: past this window +// the sample is skipped (and a throttled warning printed) instead of +// waiting. An uncontended critical section takes a few milliseconds. +export const LOCK_TIMEOUT_MS = 100 +// How long to wait between attempts to take a lock (doubles up to the max). +const LOCK_RETRY_MS = 10 +const LOCK_RETRY_MAX_MS = 200 +// A skipped-sample warning is printed at most this often per file. +const WARN_EVERY_MS = 60 * 1000 +const append = createToolsWriter() + +// Two plugin hosts can run at once (the host may keep the old one alive +// during a restart) and share a dataDir. The in-process queue cannot stop +// host B from renaming over the generation host A just moved aside, so the +// whole critical section (stat, age check, rename, append) also runs under a +// cross-process lock. +// +// A lock is a small file holding the owner's pid and a token, created with +// an exclusive open ("wx"), so exactly one host can hold it. Two layers: +// - the main lock (.lock) guards the critical section; +// - the reaper lock (.reaper.lock) is held only while reclaiming a +// dead main lock. The reaper re-reads the main lock inside it, so two +// reclaimers cannot both unlink, and a slow one cannot delete the fresh +// lock a live host took in the meantime. +// +// A main lock is reclaimed only when its pid is provably dead (kill(pid, 0) +// reports ESRCH). Everything else fails closed — the sample is skipped and a +// warning printed, rather than a live host's lock removed: +// - a lock from a live pid, or a pid we cannot signal (EPERM, other user); +// - an empty or corrupt lock (a host died between creating it and writing +// its pid): remove .lock by hand once no host is running; +// - a leftover reaper lock (a host died while reclaiming): remove +// .reaper.lock by hand once no host is running. +// A reused pid makes a dead lock look alive: that also fails closed. +// +// Limits: local filesystems only (O_EXCL is not reliable over NFS and pids +// mean nothing across machines or pid namespaces). Normal exits, thrown +// errors and failed writes release the lock in finally; only a hard crash +// leaves one behind, and a dead holder's lock is then reclaimed. +function lockPath(file) { return file + ".lock" } +function reaperPath(file) { return file + ".reaper.lock" } + +// Create a lock file exclusively and write its owner. Returns the token, or +// null if the file already exists. A failed write removes our own empty +// file: nobody else can have replaced it, since it exists and is unreadable. +async function createLock(path) { + let handle + try { + handle = await open(path, "wx") + } catch (error) { + if (error.code === "EEXIST") return null + throw error + } + const token = randomUUID() + let closed = false + try { + await handle.writeFile(JSON.stringify({ pid: process.pid, token, at: Date.now() })) + closed = true + await handle.close() + } catch (error) { + // A failed write or close must not leave a lock naming this live pid: + // nobody could ever reclaim it. The file is ours (it exists, so no one + // else can have created it), so remove it. + if (!closed) await handle.close().catch(() => {}) + await unlink(path).catch(() => {}) + throw error + } + return token +} + +// Release a lock we hold. Unconditional: while we are alive nobody else +// removes it (a main lock is only reclaimed for a dead pid, a reaper lock +// never), so it cannot have been replaced. Re-reading it first would keep a +// live pid's lock forever whenever that read failed (EMFILE, EIO...). +// A failed unlink would leave this live host's lock in place and block every +// writer, this one included, until the host exits: say so (throttled, file +// name and error code only). +async function removeLock(path) { + await unlink(path).catch((error) => { + if (error.code === "ENOENT") return + const key = `${path}:release:${error.code}` + const at = Date.now() + if (at - (warnedAt.get(key) ?? -Infinity) < WARN_EVERY_MS) return + warnedAt.set(key, at) + console.warn(`[harnessweight] could not release ${basename(path)} (${error.code ?? "error"}); samples are skipped until it is removed or this host exits`) + }) +} + +function alive(pid) { + if (!Number.isInteger(pid) || pid <= 0) return null + try { + process.kill(pid, 0) + return true + } catch (error) { + // ESRCH: no such process, the owner is gone. + if (error.code === "ESRCH") return false + // EPERM: the process exists but belongs to another user. + return null + } +} + +// The lock's owner: undefined when there is no lock, null when it cannot be +// identified (empty, truncated, corrupt — including the instant between a +// live host creating it and writing its pid). +async function readLock(path) { + let text + try { + text = await readFile(path, "utf8") + } catch (error) { + if (error.code === "ENOENT") return undefined + return null + } + try { + const parsed = JSON.parse(text) + const pid = Number(parsed?.pid) + const token = typeof parsed?.token === "string" ? parsed.token : "" + if (!Number.isInteger(pid) || pid <= 0 || !token) return null + return { pid, token } + } catch { + // Empty, truncated or corrupt: the owner cannot be identified. + return null + } +} + +// Take the main lock, reclaiming it first if its owner is provably dead. +// The deadline is absolute, fixed when the request was queued. One attempt +// is always made, so a free lock is taken even late; a held one fails at +// once. Throws a coded error when it cannot be taken in time. +async function acquireLock(file, deadline) { + const path = lockPath(file) + let wait = LOCK_RETRY_MS + let reason = "held" + for (;;) { + const token = await createLock(path) + if (token) return { path, token } + const outcome = await reclaimDeadLock(file) + reason = outcome + // Checked on every path, "reclaimed" included: hosts that keep + // reclaiming and losing the race must still give up on time. + if (Date.now() >= deadline) { + const error = new Error(`tools log lock not acquired (${reason})`) + error.code = "HW_LOCK_TIMEOUT" + error.reason = reason + throw error + } + if (outcome === "reclaimed") continue + // Never sleep past the deadline: the wait bound is what keeps the + // response path fast. + await sleep(Math.min(wait, Math.max(0, deadline - Date.now()))) + wait = Math.min(wait * 2, LOCK_RETRY_MAX_MS) + } +} + +// Reclaim a main lock whose owner is provably dead. Only one host reclaims +// at a time (the reaper lock), and it re-reads the main lock inside the +// reaper lock, so it can only unlink the lock it judged dead. Returns +// "reclaimed", or why not: "held" (live or unprovable owner), "unreadable" +// (empty/corrupt lock), "reaper" (another reaper, or a leftover one). +async function reclaimDeadLock(file) { + const main = lockPath(file) + const reaper = reaperPath(file) + const reaperToken = await createLock(reaper) + // Never remove a reaper lock we did not create: it may belong to a live + // host. A leftover one blocks reclaiming until removed by hand. + if (!reaperToken) return "reaper" + try { + const current = await readLock(main) + if (current === undefined) return "reclaimed" // gone already: try again + if (current === null) return "unreadable" + if (alive(current.pid) !== false) return "held" + await unlink(main).catch((error) => { if (error.code !== "ENOENT") throw error }) + return "reclaimed" + } finally { + await removeLock(reaper) + } +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +// The hook's own options, filled in by the gateway before the first call. +let OPTIONS = { + port: 3496, + dataDir: "", + gatewayTimeoutMs: 2000, + agents: [], +} + +function dataPath() { + return toolsLog(OPTIONS) +} + +// The agent names this hook watches; empty means all of them. +function wanted(agent) { + if (!agent) return false + if (!Array.isArray(OPTIONS.agents) || OPTIONS.agents.length === 0) return true + return OPTIONS.agents.some((a) => String(a).trim().toLowerCase() === String(agent).toLowerCase()) +} + +// The tokens a reply reports, in the shapes the four protocols use. +function usageOf(reply) { + const u = reply?.usage ?? reply?.usage_metadata ?? reply?.usageMetadata + if (!u || typeof u !== "object") return null + return { + in: num(u.input_tokens ?? u.prompt_tokens ?? u.promptTokenCount ?? u.input), + out: num(u.output_tokens ?? u.completion_tokens ?? u.candidatesTokenCount ?? u.output), + cacheRead: num(u.cache_read_input_tokens ?? u.cached_content_token_count ?? u.cacheRead), + cacheWrite: num(u.cache_creation_input_tokens ?? u.cacheWrite), + } +} + +function num(v) { + return typeof v === "number" && Number.isFinite(v) ? v : 0 +} + +// The row this hook writes. Everything in it is a number or a name. +function row(ctx, body, reply, success) { + const tools = measureTools(body) + const r = { + t: Date.now(), + agent: ctx?.agent ?? "unknown", + model: ctx?.model ?? body?.model ?? "unknown", + protocol: ctx?.protocol ?? "unknown", + path: ctx?.path ?? "", + tools: tools.count, + toolBytes: tools.bytes, + toolNames: tools.names.slice(0, 60), + ok: success !== false, + } + const u = usageOf(reply) + if (u) { + r.in = u.in + r.out = u.out + r.cacheRead = u.cacheRead + r.cacheWrite = u.cacheWrite + } + return r +} + +// The hook's entry point: called before the request goes to the model. +// This hook only reads, so it returns undefined and the request goes on +// exactly as it came. +export async function onRequest(body, ctx) { + OPTIONS = { ...OPTIONS, ...(ctx?.options ?? {}) } + const agent = ctx?.agent ?? "unknown" + // ctx.state survives until onResponse. ctx.signal does NOT: the host + // aborts it when this hook returns, even while the model is still running. + try { + if (wanted(agent)) activity.start(dataPath(), ctx, agent) + } catch { /* Tracking must never interrupt the user's request. */ } + return undefined +} + +// The hook's other entry point: called after the model replied. This is +// where the row is written. +export async function onResponse(reply, ctx) { + // Clear before any filtering or disk work, including failed responses. + try { activity.finish(ctx) } catch { /* best-effort telemetry */ } + OPTIONS = { ...OPTIONS, ...(ctx?.options ?? {}) } + const agent = ctx?.agent ?? "unknown" + if (!wanted(agent)) return + + try { + // ctx.request is the request the gateway accepted; it carries the tool + // declarations, which the reply knows nothing about. + const body = ctx?.request + await append(dataPath(), row(ctx, body, reply, ctx?.success !== false)) + } catch { + // A hook that fails leaves the request as it was. Never let a write + // error touch the user's request. + } +} + +// A skipped sample is reported, at most once a minute per file and code, +// with no sample content: only the file name and the reason. +const warnedAt = new Map() +function warnSkipped(error, file) { + const code = error?.code ?? error?.name ?? "error" + const key = `${file}:${code}:${error?.reason ?? ""}` + const at = Date.now() + if (at - (warnedAt.get(key) ?? -Infinity) < WARN_EVERY_MS) return + warnedAt.set(key, at) + const why = error?.reason === "unreadable" ? `${basename(file)}.lock is empty or corrupt; remove it once no host is running` + : error?.reason === "reaper" ? `${basename(file)}.reaper.lock is held or left over; remove it once no host is running` + : error?.reason === "reclaimed" ? `${basename(file)}.lock was contended past the wait budget` + : error?.code === "HW_LOCK_TIMEOUT" ? `${basename(file)}.lock is held by another host` + : `${code}` + console.warn(`[harnessweight] tool sample skipped: ${why}`) +} + +// Append one row to the data file. The log is append-only: rows are never +// rewritten in place. When a generation grows past the size limit, or holds +// rows older than the window, it is renamed aside (tools.jsonl.1) and a new +// generation starts. The whole stat → age check → rename → append runs under +// the in-process queue and the cross-process lock, so no host can rename a +// generation another host just moved aside. +export function createToolsWriter({ + now = Date.now, + maxBytes = MAX_FILE_BYTES, + lockTimeoutMs = LOCK_TIMEOUT_MS, + warn = warnSkipped, +} = {}) { + const states = new Map() + return function append(file, row) { + const line = JSON.stringify(row) + "\n" + const bytes = Buffer.byteLength(line) + // Refuse an oversized sample rather than allow unbounded telemetry. + if (bytes > maxBytes) return Promise.reject(new RangeError(`Tool sample exceeds ${maxBytes} bytes`)) + let state = states.get(file) + if (!state) { state = { tail: Promise.resolve(), checkedAt: -Infinity }; states.set(file, state) } + // The wait budget starts now, not when this row reaches the head of the + // queue: N queued requests behind a held lock all give up about + // lockTimeoutMs after they arrived, instead of N × lockTimeoutMs. + const deadline = Date.now() + lockTimeoutMs + const pending = state.tail.then(async () => { + await mkdir(dirname(file), { recursive: true }) + const lock = await acquireLock(file, deadline) + try { + let st + try { st = await stat(file) } catch (error) { if (error.code !== "ENOENT") throw error } + const time = now() + let rotate = Boolean(st) && st.size + bytes > maxBytes + if (!rotate && time - state.checkedAt >= AGE_CHECK_MS) { + if (st?.size) { + const text = await readFile(file, "utf8") + rotate = text.split("\n").some((line) => { + try { const r = JSON.parse(line); return Number.isFinite(r?.t) && r.t < time - MAX_AGE_MS } + catch { return false } + }) + } + state.checkedAt = time + } + if (rotate) { + // The old generation moves aside whole; nothing is rewritten. + await rename(file, file + ".1") + state.checkedAt = time + } + await appendFile(file, line, "utf8") + } finally { + await removeLock(lock.path) + } + }).catch((error) => { + try { warn(error, file) } catch { /* reporting must not mask the error */ } + throw error + }) + // A failed sample must not poison later requests. + state.tail = pending.catch(() => {}) + return pending + } +} diff --git a/packages/page-harnessweight/index.mjs b/packages/page-harnessweight/index.mjs new file mode 100644 index 0000000..c4c83e0 --- /dev/null +++ b/packages/page-harnessweight/index.mjs @@ -0,0 +1,21 @@ +// HarnessWeight as an OpenCode v1 plugin: magpie's Bun host loads it and calls +// server(), which starts the local service the page navigates to. It adds no +// provider. Importing this module alone binds no port. +import { serve } from "./service.mjs" + +let started = null +function start(options) { + if (!started) { + started = serve(options || {}) + started.ready.then((p) => p && console.log(`[harnessweight] listening on http://127.0.0.1:${p}`)) + } + return started +} + +export default { + id: "harnessweight", + server: async (input, options) => { + start({ ...options, directory: input?.directory }) + return {} + }, +} diff --git a/packages/page-harnessweight/lib/activity.mjs b/packages/page-harnessweight/lib/activity.mjs new file mode 100644 index 0000000..3ba2418 --- /dev/null +++ b/packages/page-harnessweight/lib/activity.mjs @@ -0,0 +1,53 @@ +// Hook and service run in the same plugin-host process. Never infer active +// requests from completed usage rows. State is intentionally not persisted. +export const MAX_ACTIVITY_AGE_MS = 15 * 60 * 1000 +const REQUEST = Symbol("harnessweight.request") + +export function createActivityTracker({ now = Date.now, maxAgeMs = MAX_ACTIVITY_AGE_MS } = {}) { + const scopes = new Map() + function scope(key) { + if (!scopes.has(key)) scopes.set(key, { requests: new Map(), observed: false, expired: 0 }) + return scopes.get(key) + } + function expire(s, time) { + for (const [id, request] of s.requests) { + if (time - request.startedAt >= maxAgeMs) { + s.requests.delete(id) + s.expired++ + } + } + } + return { + start(key, ctx, agent) { + if (!ctx?.state || typeof ctx.state !== "object") return + const s = scope(key) + s.observed = true + const time = now() + expire(s, time) + if (ctx.state[REQUEST]) return + const id = Symbol() + ctx.state[REQUEST] = { key, id } + s.requests.set(id, { agent, startedAt: time }) + }, + finish(ctx) { + const request = ctx?.state?.[REQUEST] + if (!request) return + scopes.get(request.key)?.requests.delete(request.id) + delete ctx.state[REQUEST] + }, + snapshot(key) { + const s = scope(key) + const observedAt = now() + expire(s, observedAt) + const counts = new Map() + for (const { agent } of s.requests.values()) counts.set(agent, (counts.get(agent) || 0) + 1) + return { + agents: [...counts].map(([agent, count]) => ({ agent, count })).sort((a, b) => a.agent.localeCompare(b.agent)), + total: s.requests.size, observedAt, tracking: "hooks", available: s.observed, + maxAgeMs, expired: s.expired, + } + }, + } +} + +export const activity = createActivityTracker() diff --git a/packages/page-harnessweight/lib/brands.mjs b/packages/page-harnessweight/lib/brands.mjs new file mode 100644 index 0000000..a5a480c --- /dev/null +++ b/packages/page-harnessweight/lib/brands.mjs @@ -0,0 +1,90 @@ +// Each agent's display name and icon, exactly as magpie shows them. magpie's +// gateway already knows both: GET /v1/magpie/usage lists every agent with a +// name ("Claude Code") and an icon key ("claudecode-color"). The icon files +// live in app/icons/, named by that key; a key with no file falls back to the +// agent's initial in the page. +import { readFile, readdir } from "node:fs/promises" +import { dirname, join } from "node:path" +import { fileURLToPath } from "node:url" + +const ICONS = join(dirname(fileURLToPath(import.meta.url)), "..", "app", "icons") +const TTL_MS = 10 * 60e3 + +export function gatewayUrl(options = {}) { + const explicit = options.gatewayUrl || process.env.MAGPIE_GATEWAY_URL + if (explicit) return String(explicit).trim().replace(/\/+$/, "") + // MAGPIE_ADDR is the host's host:port, not a URL. Only wildcard bind + // addresses become IPv4 loopback; an explicit IPv6 listener stays IPv6. + const addr = String(process.env.MAGPIE_ADDR || "").trim().replace(/^(0\.0\.0\.0|\[::\])(:|$)/, "127.0.0.1$2") + if (/^(\[[0-9a-f:.]+\]|[\w.-]+):\d+$/i.test(addr)) return `http://${addr}` + return "http://127.0.0.1:3425" +} + +export function createBrands(options = {}, fetchImpl = globalThis.fetch) { + let at = 0 + let map = new Map() + let files = null + let pending = null + + async function iconFiles() { + if (!files) { + files = new Map() + for (const f of await readdir(ICONS).catch(() => [])) { + const dot = f.lastIndexOf(".") + if (dot > 0 && /\.(svg|png|webp)$/i.test(f)) files.set(f.slice(0, dot), f) + } + } + return files + } + + async function refresh() { + if (Date.now() - at < TTL_MS) return + if (pending) return pending + pending = (async () => { + const have = await iconFiles() + try { + const res = await fetchImpl(`${gatewayUrl(options)}/v1/magpie/usage?period=30d`, { signal: AbortSignal.timeout(3000) }) + if (!res.ok) throw new Error(`HTTP ${res.status}`) + const body = await res.json() + const next = new Map() + for (const g of body.agents || []) { + if (!g || !g.id) continue + const key = typeof g.icon === "string" && g.icon !== "generic" ? g.icon : "" + next.set(String(g.id), { name: String(g.name || g.id), icon: have.get(key) || null }) + } + map = next + } catch { + // the gateway is down or older: keep what we had, retry sooner + at = Date.now() - TTL_MS + 30e3 + return + } + at = Date.now() + })().finally(() => { pending = null }) + return pending + } + + // the brand for an agent id: magpie's, else the id itself and an icon file + // whose name is the id, else no icon + function of(agent) { + const b = map.get(agent) + if (b) return b + const f = files?.get(String(agent).toLowerCase()) || files?.get(`${String(agent).toLowerCase()}-color`) + return { name: agent, icon: f || null } + } + + // an icon as a data: URI, so the page needs no request for it (in magpie's + // sandboxed frame, images the script adds after load do not show) + const uris = new Map() + const TYPES = { svg: "image/svg+xml", png: "image/png", webp: "image/webp" } + async function dataUri(file) { + if (!file) return null + if (!uris.has(file)) { + const buf = await readFile(join(ICONS, file)).catch(() => null) + const ext = file.slice(file.lastIndexOf(".") + 1).toLowerCase() + uris.set(file, buf ? `data:${TYPES[ext]};base64,${buf.toString("base64")}` : null) + } + return uris.get(file) + } + + return { refresh, of, dataUri } +} diff --git a/packages/page-harnessweight/lib/measure.mjs b/packages/page-harnessweight/lib/measure.mjs new file mode 100644 index 0000000..a9f9fa3 --- /dev/null +++ b/packages/page-harnessweight/lib/measure.mjs @@ -0,0 +1,65 @@ +// Tool-declaration measurement, shared by the hook and the tests. + +// The size of a tool declaration, per protocol. magpie speaks four shapes +// to four families of models, and the tools live in a different place in +// each: +// +// anthropic (/v1/messages): tools: [{ name, description, input_schema }] +// chat (/v1/chat/completions): tools: [{ type, function: {...} }] +// responses (/v1/responses): tools: [{ type, name, parameters }] +// gemini (…/streamGenerateContent): tools: [{ functionDeclarations: [...] }] +// +// The numbers that matter for a cost comparison are the count and the +// bytes: the bytes are what the model reads again on every turn. +export function measureTools(body) { + const out = { count: 0, bytes: 0, names: [] } + if (!body || typeof body !== "object") return out + + const tools = Array.isArray(body.tools) ? body.tools : null + if (!tools) return out + + for (const t of tools) { + if (!t || typeof t !== "object") continue + // A namespace's tools are its own tools (OpenAI responses). + if (Array.isArray(t.tools)) { + const inner = measureTools({ tools: t.tools }) + out.count += inner.count + out.bytes += inner.bytes + out.names.push(...inner.names) + continue + } + // Gemini puts them one level deeper, under functionDeclarations. + if (Array.isArray(t.functionDeclarations)) { + for (const fd of t.functionDeclarations) { + out.count++ + out.bytes += sizeOf(fd) + if (fd && typeof fd.name === "string") out.names.push(fd.name) + } + continue + } + // OpenAI chat wraps them in a function object. + if (t.function && typeof t.function === "object") { + out.count++ + out.bytes += sizeOf(t.function) + if (typeof t.function.name === "string") out.names.push(t.function.name) + continue + } + // Anthropic and OpenAI responses keep them flat. + out.count++ + out.bytes += sizeOf(t) + if (typeof t.name === "string") out.names.push(t.name) + } + return out +} + +// The size of one declaration, in bytes of JSON. This is a proxy for the +// tokens the model reads, not a token count: JSON is not BPE, and no +// tokenizer is exact for every provider. It is the same measure for every +// agent, which is what a comparison needs. +export function sizeOf(value) { + try { + return Buffer.byteLength(JSON.stringify(value) ?? "", "utf8") + } catch { + return 0 + } +} diff --git a/packages/page-harnessweight/lib/paths.mjs b/packages/page-harnessweight/lib/paths.mjs new file mode 100644 index 0000000..9bc5e46 --- /dev/null +++ b/packages/page-harnessweight/lib/paths.mjs @@ -0,0 +1,64 @@ +// Where HarnessWeight reads and writes. Both the hook and the service resolve +// paths here, so they always agree. +import { homedir } from "node:os" +import { existsSync, realpathSync, renameSync } from "node:fs" +import { dirname, isAbsolute, join, parse, resolve } from "node:path" +import { fileURLToPath } from "node:url" + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..") + +// One directory, one string. The host may name the config dir through +// input.directory while the hook sees it as its cwd; a symlinked path +// (/var -> /private/var on macOS) would otherwise give the two different +// spellings of the same disk directory. Resolve symlinks as far as the +// directory exists, so both sides name it identically. +function canonical(dir) { + const path = resolve(dir) + try { + return realpathSync(path) + } catch { /* not created yet: canonicalize the nearest existing parent */ } + const parts = [] + let current = path + for (;;) { + const parent = dirname(current) + if (parent === current) return path + parts.unshift(parse(current).base) + try { + return join(realpathSync(parent), ...parts) + } catch { /* keep walking up */ } + current = parent + } +} + +// The host passes its config directory to server() and also starts the hook +// there. Probe cwd for the hook; standalone launches fall back to XDG/home. +export function magpieDir(options = {}) { + if (options.directory) return canonical(options.directory) + try { + const cwd = process.cwd() + if (cwd !== ROOT && ["usage.jsonl", "plugins.json", "providers.json"].some((f) => existsSync(join(cwd, f)))) return canonical(cwd) + } catch { /* cwd may have been removed */ } + const xdg = process.env.XDG_CONFIG_HOME + return canonical(xdg && isAbsolute(xdg) ? join(xdg, "magpie") : join(homedir(), ".config", "magpie")) +} + +// magpie's own usage ledger: one JSON line per gateway request. +export function usageLog(options = {}) { + return options.usageLog ? resolve(options.usageLog) : join(magpieDir(options), "usage.jsonl") +} + +// The tool-weight samples the hook writes. Kept outside the plugin's folder +// so a reinstall or an update does not wipe them. +export function toolsLog(options = {}) { + if (options.dataDir) return join(canonical(options.dataDir), "tools.jsonl") + const dir = join(magpieDir(options), "harnessweight") + // the plugin was called Agent Lens until 0.4.0: carry its samples over once + const old = join(magpieDir(options), "agent-lens") + if (!existsSync(dir) && existsSync(old)) { + try { renameSync(old, dir) } catch { + // Another host may have completed the same migration concurrently. + if (!existsSync(dir) && existsSync(old)) return join(old, "tools.jsonl") + } + } + return join(dir, "tools.jsonl") +} diff --git a/packages/page-harnessweight/lib/summarize.mjs b/packages/page-harnessweight/lib/summarize.mjs new file mode 100644 index 0000000..b89496c --- /dev/null +++ b/packages/page-harnessweight/lib/summarize.mjs @@ -0,0 +1,216 @@ +// The comparison: magpie's usage rows and the hook's tool samples, grouped by +// agent. Everything here is plain arithmetic over numbers already recorded; +// nothing is estimated except the tool tokens, which say so. +import { kindOf } from "./usage.mjs" +// the insight sentences live in the shared table, so the page and the service +// say the same thing in the same language +import { insight } from "../app/i18n.mjs" + +export const PERIODS = { today: 24 * 3600e3, "7d": 7 * 24 * 3600e3, "30d": 30 * 24 * 3600e3 } + +// JSON bytes per token of a tool declaration, roughly. JSON is dense (short +// ASCII keys), about 3.5 bytes a token. The same estimate for every agent. +export const BYTES_PER_TOKEN = 3.5 + +function median(xs) { + if (!xs.length) return 0 + const s = [...xs].sort((a, b) => a - b) + const m = s.length >> 1 + return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2 +} + +function bump(map, key, n = 1) { map.set(key, (map.get(key) || 0) + n) } +function top(map, n) { + return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, n).map(([name, count]) => ({ name, count })) +} + +function dayKey(t, tzOffsetMin) { + return new Date(t - tzOffsetMin * 60e3).toISOString().slice(0, 10) +} + +export function summarize({ usage = [], tools = [], period = "7d", now = Date.now(), showClients = false, tzOffsetMin = 0, nameOf = (a) => a, lang = "zh" }) { + const span = PERIODS[period] ?? PERIODS["7d"] + const since = now - span + const by = new Map() + const get = (agent) => { + let a = by.get(agent) + if (!a) { + a = { + agent, kind: kindOf(agent), calls: 0, failed: 0, cancelled: 0, + in: 0, out: 0, cacheRead: 0, cacheWrite: 0, credits: 0, + ms: [], ttft: [], models: new Map(), protocols: new Map(), days: new Map(), + sessions: new Map(), + first: Infinity, last: 0, + tool: { samples: 0, count: 0, bytes: 0, names: new Map(), first: Infinity }, + } + by.set(agent, a) + } + return a + } + + let hidden = 0 + for (const r of usage) { + if (r.t < since) continue + if (!showClients && kindOf(r.agent) === "client") { hidden++; continue } + const a = get(r.agent) + a.calls++ + if (r.failed) a.failed++ + if (r.cancelled) a.cancelled++ + a.in += r.in; a.out += r.out; a.cacheRead += r.cacheRead; a.cacheWrite += r.cacheWrite + a.credits += r.credits + if (r.ms > 0 && !r.failed) a.ms.push(r.ms) + if (r.ttft > 0 && !r.failed) a.ttft.push(r.ttft) + bump(a.models, r.model) + bump(a.protocols, r.protocol) + if (r.session) { + let s = a.sessions.get(r.session) + if (!s) { s = { first: r.t, last: r.t, calls: 0 }; a.sessions.set(r.session, s) } + if (r.t < s.first) s.first = r.t + if (r.t > s.last) s.last = r.t + s.calls++ + } + const prompt = r.in + r.cacheRead + r.cacheWrite + const d = dayKey(r.t, tzOffsetMin) + const day = a.days.get(d) || { day: d, calls: 0, prompt: 0, out: 0 } + day.calls++; day.prompt += prompt; day.out += r.out + a.days.set(d, day) + if (r.t < a.first) a.first = r.t + if (r.t > a.last) a.last = r.t + } + + let toolSamples = 0 + let toolsSince = Infinity + for (const r of tools) { + if (r.t < since) continue + if (!showClients && kindOf(r.agent) === "client") continue + const a = get(r.agent) + toolSamples++ + a.tool.samples++ + a.tool.count += r.tools || 0 + a.tool.bytes += r.toolBytes || 0 + for (const n of r.toolNames || []) bump(a.tool.names, n) + if (r.t < a.tool.first) a.tool.first = r.t + if (r.t < toolsSince) toolsSince = r.t + } + + const agents = [...by.values()].filter((a) => a.calls > 0 || a.tool.samples > 0).map((a) => { + const prompt = a.in + a.cacheRead + a.cacheWrite + const avgPrompt = a.calls ? prompt / a.calls : 0 + const tb = a.tool.samples ? a.tool.bytes / a.tool.samples : 0 + const toolTokens = tb / BYTES_PER_TOKEN + return { + agent: a.agent, kind: a.kind, + calls: a.calls, failed: a.failed, cancelled: a.cancelled, + errorRate: a.calls ? a.failed / a.calls : 0, + prompt, avgPrompt, out: a.out, avgOut: a.calls ? a.out / a.calls : 0, + in: a.in, cacheRead: a.cacheRead, cacheWrite: a.cacheWrite, + // share of what the model read that came from the cache (billed cheap) + cacheRate: prompt ? a.cacheRead / prompt : 0, + // what was read at full price: fresh input plus cache writes + fullPrice: a.in + a.cacheWrite, + credits: a.credits, + p50ms: median(a.ms), p50ttft: median(a.ttft), + models: top(a.models, 8), protocols: top(a.protocols, 4), + session: sessionStats(a.sessions), + series: [...a.days.values()].sort((x, y) => (x.day < y.day ? -1 : 1)), + first: Number.isFinite(a.first) ? a.first : null, last: a.last || null, + tools: a.tool.samples ? { + samples: a.tool.samples, + avgCount: a.tool.count / a.tool.samples, + avgBytes: tb, + avgTokens: toolTokens, + shareOfPrompt: avgPrompt ? Math.min(1, toolTokens / avgPrompt) : null, + names: top(a.tool.names, 40), + since: a.tool.first, + } : null, + } + }).sort((x, y) => y.prompt - x.prompt) + + const totals = agents.reduce((t, a) => { + t.calls += a.calls; t.failed += a.failed; t.prompt += a.prompt; t.out += a.out + t.cacheRead += a.cacheRead; t.fullPrice += a.fullPrice; t.credits += a.credits + return t + }, { calls: 0, failed: 0, prompt: 0, out: 0, cacheRead: 0, fullPrice: 0, credits: 0 }) + totals.cacheRate = totals.prompt ? totals.cacheRead / totals.prompt : 0 + + let lastUsage = 0, lastTool = 0 + for (let i = usage.length - 1; i >= 0 && i >= usage.length - 50; i--) if (usage[i].t > lastUsage) lastUsage = usage[i].t + for (const r of tools) if (r.t > lastTool) lastTool = r.t + return { + lastUsage: lastUsage || null, lastTool: lastTool || null, + period, since, generatedAt: now, agents, totals, hiddenClients: hidden, + toolSamples, toolsSince: Number.isFinite(toolsSince) ? toolsSince : null, + insights: insights(agents, nameOf, lang), + } +} + +// The few sentences a reader takes away. Only about agents with enough calls +// to say anything, and only when there is something to compare. +// How long one conversation lasts. A harness that keeps a session id gives us +// the span from a session's first request to its last. Sessions that stay open +// for days (a desktop app left running overnight) would skew the average, so +// anything longer than MAX_SESSION_MS is counted but not measured. +const MAX_SESSION_MS = 6 * 3600e3 + +function sessionStats(sessions) { + const spans = [] + let open = 0 + for (const s of sessions.values()) { + const span = s.last - s.first + if (span <= MAX_SESSION_MS) spans.push(span) + else open++ + } + if (!spans.length) return { count: sessions.size, measured: 0, median: null, p90: null, longest: null } + spans.sort((a, b) => a - b) + return { + count: sessions.size, + measured: spans.length, + median: spans[spans.length >> 1], + p90: spans[Math.min(spans.length - 1, Math.floor(spans.length * 0.9))], + longest: spans[spans.length - 1], + open, + } +} + +export function insights(agents, nameOf = (a) => a, lang = "zh") { + const N = (a) => nameOf(a.agent) + // only agents a person works in; scripts and probes never make a takeaway + agents = agents.filter((a) => a.kind === "agent") + const out = [] + const real = agents.filter((a) => a.calls >= 20) + if (real.length >= 2) { + const byPrompt = [...real].sort((a, b) => b.avgPrompt - a.avgPrompt) + const hi = byPrompt[0], lo = byPrompt[byPrompt.length - 1] + if (lo.avgPrompt > 0 && hi.avgPrompt / lo.avgPrompt >= 1.5) { + out.push({ kind: "prompt", agents: [hi.agent, lo.agent], ratio: hi.avgPrompt / lo.avgPrompt, + text: insight(lang, "prompt", { hi: N(hi), lo: N(lo), avg: fmt(hi.avgPrompt), ratio: (hi.avgPrompt / lo.avgPrompt).toFixed(1) }) }) + } + const byCache = [...real].sort((a, b) => b.cacheRate - a.cacheRate) + const c1 = byCache[0], c2 = byCache[byCache.length - 1] + if (c1.cacheRate - c2.cacheRate >= 0.05) { + out.push({ kind: "cache", agents: [c1.agent, c2.agent], + text: insight(lang, "cache", { hi: N(c1), lo: N(c2), hiRate: pct(c1.cacheRate), loRate: pct(c2.cacheRate) }) }) + } + const share = [...real].sort((a, b) => b.prompt - a.prompt)[0] + const total = real.reduce((n, a) => n + a.prompt, 0) + if (total) out.push({ kind: "volume", agents: [share.agent], + text: insight(lang, "volume", { name: N(share), share: pct(share.prompt / total) }) }) + } + const shaky = agents.filter((a) => a.calls >= 20 && a.errorRate >= 0.03).sort((a, b) => b.errorRate - a.errorRate)[0] + if (shaky) out.push({ kind: "errors", agents: [shaky.agent], + text: insight(lang, "errors", { name: N(shaky), rate: pct(shaky.errorRate) }) }) + const withTools = agents.filter((a) => a.tools && a.tools.samples >= 3 && a.tools.avgCount > 0).sort((a, b) => b.tools.avgBytes - a.tools.avgBytes) + if (withTools.length >= 2) { + const h = withTools[0], l = withTools[withTools.length - 1] + out.push({ kind: "tools", agents: [h.agent, l.agent], + text: insight(lang, "tools", { hi: N(h), lo: N(l), tokens: fmt(h.tools.avgTokens), count: Math.round(h.tools.avgCount), loTokens: fmt(l.tools.avgTokens), loCount: Math.round(l.tools.avgCount), ratio: (h.tools.avgTokens / Math.max(1, l.tools.avgTokens)).toFixed(1) }) }) + } + return out +} + +function fmt(n) { + if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M` + if (n >= 1e3) return `${(n / 1e3).toFixed(1)}K` + return String(Math.round(n)) +} +function pct(x) { return `${(x * 100).toFixed(1)}%` } diff --git a/packages/page-harnessweight/lib/tools.mjs b/packages/page-harnessweight/lib/tools.mjs new file mode 100644 index 0000000..5efe3b5 --- /dev/null +++ b/packages/page-harnessweight/lib/tools.mjs @@ -0,0 +1,51 @@ +// Both bounded generations belong to the rolling sample window. Cache by +// inode as well as size/mtime so a rename cannot masquerade as an append. +import { readFile, stat } from "node:fs/promises" + +const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000 +export function createToolsReader(file, { now = Date.now } = {}) { + const files = [file + ".1", file] + let key = "" + let rows = [] + let reading + async function signature() { + return (await Promise.all(files.map(async (path) => { + try { const s = await stat(path); return `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}` } + catch (error) { if (error.code === "ENOENT") return "missing"; throw error } + }))).join("|") + } + async function refresh() { + if (reading) return reading + reading = (async () => { + // Retention advances even if neither file has changed. + rows = rows.filter((r) => r.t >= now() - MAX_AGE_MS) + for (let attempt = 0; attempt < 3; attempt++) { + const before = await signature() + if (before === key) return + const texts = await Promise.all(files.map(async (path) => { + try { return await readFile(path, "utf8") } + catch (error) { if (error.code === "ENOENT") return ""; throw error } + })) + // Retry a rotation/append during the read rather than publish duplicate + // generations or a missing history. Under sustained writes retry later. + if (before !== await signature()) continue + const out = [] + for (const text of texts) { + const lines = text.split("\n") + lines.pop() // only complete, newline-terminated records + for (const line of lines) { + try { + const r = JSON.parse(line) + if (Number.isFinite(r?.t) && r.t >= now() - MAX_AGE_MS && r.agent) out.push(r) + } catch { /* malformed line */ } + } + } + rows = out + key = before + return + } + })().finally(() => { reading = null }) + return reading + } + return { refresh, rows: () => rows, file } +} diff --git a/packages/page-harnessweight/lib/usage.mjs b/packages/page-harnessweight/lib/usage.mjs new file mode 100644 index 0000000..873ce6c --- /dev/null +++ b/packages/page-harnessweight/lib/usage.mjs @@ -0,0 +1,124 @@ +// Reads magpie's usage ledger incrementally. The file is large (hundreds of +// MB) and only ever appended to, so the reader remembers how far it got and +// reads only what is new; when the file shrinks (rotated), it starts over. +import { createReadStream } from "node:fs" +import { open, stat } from "node:fs/promises" +import { createInterface } from "node:readline" + +// Rows older than this are not kept in memory: the page offers 30 days. +export const KEEP_MS = 31 * 24 * 60 * 60 * 1000 + +// Clients that are scripts, SDKs or magpie's own probes rather than agents a +// person works in. They are hidden by default and can be shown. +const CLIENTS = new Set([ + "gateway-probe", "python-urllib", "curl", "go-http-client", "openai", "node", + "asyncopenai", "bun", "anthropic", "magpie", "ai", "vercel-ai", "langchain", "litellm", "axios", "python-requests", "httpx", "wget", +]) +export function kindOf(agent) { + const a = String(agent || "").toLowerCase() + if (!a || a === "unknown") return "client" + if (CLIENTS.has(a) || a.startsWith("local-agent-mode")) return "client" + return "agent" +} + +// The request family, from magpie's endpoint note ("/v1/chat/completions → /v1/messages"). +export function protocolOf(ep) { + const e = String(ep || "") + const last = e.split("→").pop() + if (last.includes("streamGenerateContent") || last.includes("generateContent")) return "gemini" + if (last.includes("/messages")) return "anthropic" + if (last.includes("/responses")) return "responses" + if (last.includes("/chat/completions")) return "chat" + return "other" +} + +// One ledger line → a compact row, or null when it is not a model request. +export function parseUsageLine(line) { + let d + try { d = JSON.parse(line) } catch { return null } + if (!d || typeof d !== "object") return null + const t = typeof d.t === "number" ? d.t : Date.parse(d.t) + if (!Number.isFinite(t)) return null + const status = Number(d.status) || 0 + const cancelled = status === 499 + const failed = !cancelled && (status === 0 || status >= 400 || Boolean(d.err)) + return { + t, + agent: intern(String(d.agent || "unknown")), + // the conversation this request belongs to; harnesses that keep a session + // id let us measure how long one session actually lasts + session: d.session ? intern(String(d.session)) : "", + model: intern(String(d.model || "unknown")), + protocol: protocolOf(d.ep), + in: num(d.in), out: num(d.out), + cacheRead: num(d.cache_read), cacheWrite: num(d.cache_write), + credits: num(d.credits), + ms: num(d.ms), ttft: num(d.ttft_ms), + failed, cancelled, + } +} + +// Ledger strings repeat endlessly (a few agents, a few dozen models): keep one copy. +const pool = new Map() +function intern(s) { + let v = pool.get(s) + if (v === undefined) { v = s; pool.set(s, s) } + return v +} + +function num(v) { return typeof v === "number" && Number.isFinite(v) ? v : 0 } + +export function createUsageReader(file) { + let offset = 0 + let rows = [] + let reading = null + + async function refresh() { + if (reading) return reading + reading = (async () => { + let st + try { st = await stat(file) } catch { rows = []; offset = 0; return } + if (st.size < offset) { rows = []; offset = 0 } + if (st.size === offset) return + // a last line still being written has no newline yet: stop before it + const end = await lastNewline(file, offset, st.size) + if (end < offset) return + const cutoff = Date.now() - KEEP_MS + const fresh = [] + const stream = createReadStream(file, { start: offset, end, encoding: "utf8" }) + const rl = createInterface({ input: stream, crlfDelay: Infinity }) + for await (const line of rl) { + if (!line) continue + const r = parseUsageLine(line) + if (r && r.t >= cutoff) fresh.push(r) + } + offset = end + 1 + const keepFrom = Date.now() - KEEP_MS + rows = rows.length && rows[0].t < keepFrom ? rows.filter((r) => r.t >= keepFrom) : rows + for (const r of fresh) rows.push(r) + })().finally(() => { reading = null }) + return reading + } + + return { refresh, rows: () => rows, file } +} + +// The position of the last newline in [from, size), or from-1 when none. +async function lastNewline(file, from, size) { + const fh = await open(file, "r") + try { + const step = 64 * 1024 + let pos = size + while (pos > from) { + const start = Math.max(from, pos - step) + const buf = Buffer.alloc(pos - start) + await fh.read(buf, 0, buf.length, start) + const i = buf.lastIndexOf(10) + if (i >= 0) return start + i + pos = start + } + return from - 1 + } finally { + await fh.close() + } +} diff --git a/packages/page-harnessweight/package.json b/packages/page-harnessweight/package.json new file mode 100644 index 0000000..4b61ddc --- /dev/null +++ b/packages/page-harnessweight/package.json @@ -0,0 +1,71 @@ +{ + "name": "@magpie-community/page-harnessweight", + "version": "0.4.0", + "description": "HarnessWeight: a magpie page that weighs every agent harness behind your gateway, by agent rather than by model: input tokens, cache hit rate, tokens at full price, failures, latency, and the tool definitions each harness re-sends every turn", + "type": "module", + "files": [ + "index.mjs", + "harnessweight.hooks.mjs", + "service.mjs", + "lib", + "page", + "app", + "brand/assets", + "README.md", + "LICENSE" + ], + "keywords": [ + "magpie", + "magpie-plugin", + "agent-harness", + "harness", + "token-usage", + "claude-code", + "codex", + "cost", + "llm-gateway" + ], + "license": "MIT", + "magpie": { + "hooks": "./harnessweight.hooks.mjs", + "page": { + "title": "HarnessWeight", + "titles": { + "zh": "HarnessWeight", + "zh-TW": "HarnessWeight", + "ja": "HarnessWeight" + }, + "file": "page/index.html", + "icon": "page/icon.svg", + "service": { + "port": 3496, + "option": "port" + } + }, + "options": { + "port": 3496, + "dataDir": "", + "usageLog": "", + "agents": [], + "gatewayTimeoutMs": 2000, + "gatewayUrl": "" + }, + "permissions": [], + "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 采样工具大小并追踪进行中的请求。" + } + }, + "main": "./index.mjs", + "scripts": { + "test": "node --test test/*.test.mjs", + "dev": "node service.mjs" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/page-harnessweight" + }, + "homepage": "https://github.com/webkubor/harnessweight", + "author": "webkubor" +} diff --git a/packages/page-harnessweight/page/boot.js b/packages/page-harnessweight/page/boot.js new file mode 100644 index 0000000..f03e3d7 --- /dev/null +++ b/packages/page-harnessweight/page/boot.js @@ -0,0 +1,26 @@ +// The page in magpie's window is sandboxed (connect-src 'none'): it cannot +// fetch, so it cannot even check whether the service is up. The one thing it +// may do is navigate itself, so it goes straight to the plugin's service, +// carrying the window's theme and language. +(async () => { + let port = 3496, dark = null, lang = "", service = "" + try { + const t = await window.magpie?.ready + if (t && typeof t.dark === "boolean") dark = t.dark + if (t && t.lang) lang = String(t.lang) + } catch {} + try { + const s = window.magpie?.service + if (typeof s === "string" && /^https?:\/\//.test(s)) service = s + } catch {} + try { + const o = await window.magpie?.options?.get?.() + if (o && Number(o.port) > 0) port = Number(o.port) + } catch {} + const q = new URLSearchParams() + if (dark !== null) q.set("theme", dark ? "dark" : "light") + if (lang) q.set("lang", lang) + q.set("embed", "1") + const base = service ? service.replace(/\/?$/, "/") : `http://127.0.0.1:${port}/` + location.replace(base + "?" + q.toString()) +})() diff --git a/packages/page-harnessweight/page/icon.svg b/packages/page-harnessweight/page/icon.svg new file mode 100644 index 0000000..142cf03 --- /dev/null +++ b/packages/page-harnessweight/page/icon.svg @@ -0,0 +1,17 @@ + +HarnessWeight + + + + + + + + + + + + + + + diff --git a/packages/page-harnessweight/page/index.html b/packages/page-harnessweight/page/index.html new file mode 100644 index 0000000..1854e61 --- /dev/null +++ b/packages/page-harnessweight/page/index.html @@ -0,0 +1,31 @@ + + + + + +HarnessWeight + + + + + +

Opening HarnessWeight…

+ + + diff --git a/packages/page-harnessweight/service.mjs b/packages/page-harnessweight/service.mjs new file mode 100644 index 0000000..2308fa2 --- /dev/null +++ b/packages/page-harnessweight/service.mjs @@ -0,0 +1,172 @@ +// HarnessWeight — the local service. magpie's plugin page is sandboxed with +// connect-src 'none' and cannot fetch anything, so the page navigates its +// frame here, and this serves the real interface and the data behind it. +// +// GET / the interface (app/) +// GET /api/summary ?period=today|7d|30d&clients=1&tz= +// GET /api/health +// +// Loopback only: the data is the user's own usage. +import { createServer } from "node:http" +import { randomBytes, timingSafeEqual } from "node:crypto" +import { readFile } from "node:fs/promises" +import { dirname, join, normalize, sep } from "node:path" +import { fileURLToPath } from "node:url" +import { toolsLog, usageLog } from "./lib/paths.mjs" +import { createToolsReader } from "./lib/tools.mjs" +import { createUsageReader } from "./lib/usage.mjs" +import { PERIODS, summarize } from "./lib/summarize.mjs" +import { createBrands } from "./lib/brands.mjs" +import { activity } from "./lib/activity.mjs" +// the same table the page imports, so both sides speak one language +import { pageLanguage, languageTags } from "./app/i18n.mjs" + +const HERE = dirname(fileURLToPath(import.meta.url)) +const APP = join(HERE, "app") +const MIME = { + ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", + // app/i18n.mjs is a module both sides import, so the browser must get a + // JavaScript media type for it. + ".mjs": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".webp": "image/webp", +} + +// Guards, as magpie's chat page does them. The page frame is sandboxed, so its +// Origin is the literal "null" — and so is any other site's sandboxed frame. +// Origin alone proves nothing, so every /api/ route also needs a token that +// lives only in this process and is written into the interface's HTML when +// this service serves it (that HTML carries no CORS header, so no other page +// can read it). Host must be this service itself, against DNS rebinding. +export const TOKEN_HEADER = "x-harnessweight-token" + +export function createHandler(options = {}) { + const port = Number(options.port) > 0 ? Number(options.port) : 3496 + const token = options.token || randomBytes(32).toString("hex") + const own = new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]) + const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]) + const hostOK = (req) => hosts.has(String(req.headers.host || "").toLowerCase()) + const originOK = (req) => { const o = req.headers.origin; return o === undefined || o === "null" || own.has(o) } + const tokenOK = (req) => { + // a query param, not only a header: a custom header makes the sandboxed + // frame's fetch a preflighted request, which Chrome's private-network + // checks block from an opaque origin; a plain GET goes through + const q = new URL(req.url ?? "/", "http://127.0.0.1").searchParams.get("k") + const got = Buffer.from(String(req.headers[TOKEN_HEADER] || q || "")) + const want = Buffer.from(token) + return got.length === want.length && timingSafeEqual(got, want) + } + + const usage = createUsageReader(usageLog(options)) + const tools = createToolsReader(toolsLog(options)) + const brands = createBrands(options) + + return async function handle(req, res) { + const url = new URL(req.url ?? "/", "http://127.0.0.1") + res.setHeader("Cache-Control", "no-store") + res.setHeader("X-Content-Type-Options", "nosniff") + res.setHeader("Referrer-Policy", "no-referrer") + if (!hostOK(req) || !originOK(req)) return text(res, 403, "HarnessWeight only serves its own page in magpie") + // after the sandboxed frame navigates here its origin is opaque ("null"), so + // even its own module script is cross-origin: allow that, nothing else + const cors = () => { if (req.headers.origin) res.setHeader("Access-Control-Allow-Origin", req.headers.origin === "null" ? "null" : req.headers.origin) } + if (req.method === "OPTIONS") { + cors() + res.setHeader("Access-Control-Allow-Headers", TOKEN_HEADER) + res.setHeader("Access-Control-Allow-Private-Network", "true") + res.writeHead(204); return res.end() + } + if (req.method !== "GET" && req.method !== "HEAD") return text(res, 405, "method not allowed") + try { + if (url.pathname.startsWith("/api/") && url.pathname !== "/api/health" && !tokenOK(req)) { + cors() + // the service restarted and the token changed: the page reloads once + return json(res, 403, { error: "stale token", reload: true }) + } + if (url.pathname === "/api/activity") { + cors() + return json(res, 200, activity.snapshot(tools.file)) + } + if (url.pathname === "/api/summary") { + await Promise.all([usage.refresh(), tools.refresh(), brands.refresh()]) + const period = PERIODS[url.searchParams.get("period")] ? url.searchParams.get("period") : "7d" + const tz = Number(url.searchParams.get("tz")) + // the page sends the language it rendered in, so the insights it gets + // back are in the same language as the rest of the page + const lang = pageLanguage(url.searchParams.get("lang")) + const body = summarize({ + usage: usage.rows(), tools: tools.rows(), period, + showClients: url.searchParams.get("clients") === "1", + tzOffsetMin: Number.isFinite(tz) ? tz : 0, + nameOf: (a) => brands.of(a).name, + lang, + }) + for (const a of body.agents) { + const b = brands.of(a.agent) + Object.assign(a, { name: b.name, icon: await brands.dataUri(b.icon) }) + } + body.sources = { usageLog: usage.file, toolsLog: tools.file, usageRows: usage.rows().length, toolRows: tools.rows().length } + cors() + return json(res, 200, body) + } + if (url.pathname === "/api/health") { + return json(res, 200, { ok: true, service: "harnessweight" }) + } + let rel + try { rel = url.pathname === "/" ? "index.html" : decodeURIComponent(url.pathname.slice(1)) } + catch { return text(res, 400, "bad path") } + const full = normalize(join(APP, rel)) + if (!full.startsWith(APP + sep)) return text(res, 400, "bad path") + const content = await readFile(full).catch(() => null) + if (!content) return text(res, 404, "not found") + const ext = full.slice(full.lastIndexOf(".")) + if (full === join(APP, "index.html")) { + // the token goes into the HTML, which gets no CORS header + // the lang attribute follows the same ?lang= the page reads, so the + // document says what language it is before anything paints + const lang = pageLanguage(url.searchParams.get("lang")) + const html = content.toString("utf8") + .replace("", `\n`) + .replace('', ``) + res.writeHead(200, { "Content-Type": MIME[".html"] }) + return res.end(html) + } + cors() + res.writeHead(200, { "Content-Type": MIME[ext] ?? "application/octet-stream" }) + res.end(content) + } catch (e) { + json(res, 500, { error: String(e?.message || e) }) + } + } +} + +function json(res, code, body) { + res.writeHead(code, { "Content-Type": "application/json; charset=utf-8" }) + res.end(JSON.stringify(body)) +} +function text(res, code, body) { + res.writeHead(code, { "Content-Type": "text/plain; charset=utf-8" }) + res.end(body) +} + +// Start listening. A port still held by a previous host is retried in the +// background instead of failing the host's start. +export function serve(options = {}) { + const port = Number(options.port) > 0 ? Number(options.port) : 3496 + const server = createServer(createHandler({ ...options, port })) + const ready = new Promise((resolve) => { + let tries = 0 + const attempt = () => server.listen(port, "127.0.0.1") + server.on("listening", () => resolve(port)) + server.on("error", (e) => { + if (e.code === "EADDRINUSE" && tries++ < 30) setTimeout(attempt, 2000) + else { console.error("[harnessweight] could not listen:", e.message); resolve(null) } + }) + attempt() + }) + return { server, port, ready } +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const s = serve({ port: process.env.HARNESSWEIGHT_PORT }) + s.ready.then((p) => p && console.log(`harnessweight on http://127.0.0.1:${p}/`)) +} diff --git a/packages/page-harnessweight/test/activity.test.mjs b/packages/page-harnessweight/test/activity.test.mjs new file mode 100644 index 0000000..7bf05c9 --- /dev/null +++ b/packages/page-harnessweight/test/activity.test.mjs @@ -0,0 +1,68 @@ +import { test } from "node:test" +import assert from "node:assert/strict" +import { createServer } from "node:http" +import { mkdtemp } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { createActivityTracker } from "../lib/activity.mjs" +import { onRequest, onResponse } from "../harnessweight.hooks.mjs" +import { createHandler } from "../service.mjs" + +test("overlapping requests finish independently and duplicate finishes are harmless", () => { + const tracker = createActivityTracker() + const a = { state: {} }, b = { state: {} }, c = { state: {} } + tracker.start("one", a, "dsh") + tracker.start("one", a, "dsh") + tracker.start("one", b, "dsh") + tracker.start("two", c, "claude") + assert.deepEqual(tracker.snapshot("one").agents, [{ agent: "dsh", count: 2 }]) + tracker.finish(b) + tracker.finish(b) + assert.equal(tracker.snapshot("one").total, 1) + assert.equal(tracker.snapshot("two").total, 1) + tracker.finish(a) + assert.equal(tracker.snapshot("one").total, 0) +}) + +test("unknown tracking is distinct from idle; unmatched requests expire explicitly", () => { + let now = 0 + const tracker = createActivityTracker({ now: () => now, maxAgeMs: 100 }) + assert.equal(tracker.snapshot("one").available, false) + tracker.start("one", {}, "untrackable") + assert.equal(tracker.snapshot("one").available, false) + const a = { state: {} } + tracker.start("one", a, "dsh") + now = 99 + assert.equal(tracker.snapshot("one").total, 1) + now = 100 + const result = tracker.snapshot("one") + assert.equal(result.total, 0) + assert.equal(result.expired, 1) + assert.equal(result.available, true) + tracker.finish(a) + assert.equal(tracker.snapshot("one").expired, 1) +}) + +test("hook lifecycle reaches authenticated service, including failures and hook-signal abort", async (t) => { + const dataDir = await mkdtemp(join(tmpdir(), "hw-activity-")) + const server = createServer() + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)) + t.after(() => { server.closeAllConnections(); server.close() }) + const port = server.address().port + server.on("request", createHandler({ port, token: "test", dataDir })) + const url = `http://127.0.0.1:${port}/api/activity` + assert.equal((await fetch(url)).status, 403) + const get = async () => (await fetch(url + "?k=test")).json() + assert.equal((await get()).available, false) + const controller = new AbortController() + const ctx = { state: {}, agent: "dsh", options: { dataDir }, signal: controller.signal } + const second = { state: {}, agent: "dsh", options: { dataDir } } + assert.equal(await onRequest({}, ctx), undefined) + await onRequest({}, second) + controller.abort() // Host does this after onRequest, not after the request. + assert.deepEqual((await get()).agents, [{ agent: "dsh", count: 2 }]) + await onResponse(null, { ...ctx, success: false }) + assert.equal((await get()).total, 1) + await onResponse({}, { ...second, success: true }) + assert.equal((await get()).total, 0) +}) diff --git a/packages/page-harnessweight/test/cross-process.test.mjs b/packages/page-harnessweight/test/cross-process.test.mjs new file mode 100644 index 0000000..c039c04 --- /dev/null +++ b/packages/page-harnessweight/test/cross-process.test.mjs @@ -0,0 +1,276 @@ +import { test } from "node:test" +import assert from "node:assert/strict" +import { spawn } from "node:child_process" +import { chmod, mkdtemp, mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises" +import { chmodSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { dirname, join } from "node:path" +import { fileURLToPath } from "node:url" +import { createToolsWriter, LOCK_TIMEOUT_MS } from "../harnessweight.hooks.mjs" + +const CHILD = fileURLToPath(new URL("./fixtures/append-child.mjs", import.meta.url)) + +async function fixture(t) { + const dir = await mkdtemp(join(tmpdir(), "hw-xproc-")) + t.after(() => rm(dir, { recursive: true, force: true })) + return join(dir, "tools.jsonl") +} +const exists = (path) => stat(path).then(() => true, () => false) +// Resolves with the exit code, even if the child already exited before the +// listener was attached ("exit" fires only once). +const exited = (child) => new Promise((resolve) => { + if (child.exitCode !== null || child.signalCode !== null) resolve(child.exitCode) + else child.once("exit", (code) => resolve(code)) +}) +async function ids(file) { + const out = [] + for (const path of [file + ".1", file]) { + const text = await readFile(path, "utf8").catch(() => "") + for (const line of text.split("\n").filter(Boolean)) out.push(JSON.parse(line).id) + } + return out +} +// A child that holds the main lock until killed. +async function holder(t, file) { + const child = spawn(process.execPath, [CHILD, "--hold", file], { stdio: ["ignore", "pipe", "inherit"] }) + t.after(() => { if (child.exitCode === null) child.kill("SIGKILL") }) + await new Promise((resolve, reject) => { + child.stdout.on("data", (d) => { if (String(d).includes("LOCKED")) resolve() }) + child.on("exit", () => reject(new Error("holder exited early"))) + }) + return child +} +// A pid that certainly belonged to a process that has exited. +async function deadPid() { + const child = spawn(process.execPath, ["-e", ""]) + await exited(child) + return child.pid +} + +test("two host processes rotating the same log concurrently lose no row", async (t) => { + // 64 KiB generations, ~5.9 KB rows: 20 rows fill one generation and part + // of the next, so exactly one rotation happens and every row must survive. + for (let round = 0; round < 5; round++) { + const file = await fixture(t) + const kids = ["a", "b"].map((tag) => + spawn(process.execPath, [CHILD, file, `${tag}${round}`, "10", String(64 * 1024), "5800"], { stdio: "inherit" })) + const codes = await Promise.all(kids.map(exited)) + assert.deepEqual(codes, [0, 0], "both writers exit cleanly (no ENOENT on rename)") + const seen = await ids(file) + assert.equal(seen.length, 20, `round ${round}: every row is present`) + assert.equal(new Set(seen).size, 20, `round ${round}: no row is duplicated`) + assert.ok(await exists(file + ".1"), "the boundary was crossed") + assert.ok(!(await exists(file + ".lock")), "no lock is left behind") + } +}) + +test("a crashed holder's lock is reclaimed once its pid is gone", async (t) => { + const file = await fixture(t) + const child = await holder(t, file) + child.kill("SIGKILL") + await exited(child) + const append = createToolsWriter({ lockTimeoutMs: 2000, warn: () => {} }) + await append(file, { t: Date.now(), agent: "a", id: "after-crash" }) + assert.deepEqual(await ids(file), ["after-crash"]) + assert.ok(!(await exists(file + ".lock"))) + assert.ok(!(await exists(file + ".reaper.lock"))) +}) + +test("a live holder's lock is never removed; the sample fails closed", async (t) => { + const file = await fixture(t) + await writeFile(file, JSON.stringify({ t: Date.now(), agent: "a", id: "old" }) + "\n") + await holder(t, file) + const append = createToolsWriter({ lockTimeoutMs: 300, warn: () => {} }) + await assert.rejects(append(file, { t: Date.now(), agent: "a", id: "new" }), + (e) => e.code === "HW_LOCK_TIMEOUT" && e.reason === "held") + assert.ok(await exists(file + ".lock"), "the live lock is still there") + assert.deepEqual(await ids(file), ["old"], "existing data untouched") +}) + +test("by default a held lock delays a response by about 100 ms, then skips the sample", async (t) => { + const file = await fixture(t) + await holder(t, file) + const append = createToolsWriter({ warn: () => {} }) // default LOCK_TIMEOUT_MS + const started = performance.now() + await assert.rejects(append(file, { t: Date.now(), agent: "a", id: "x" }), { code: "HW_LOCK_TIMEOUT" }) + const waited = performance.now() - started + assert.equal(LOCK_TIMEOUT_MS, 100) + assert.ok(waited >= 90 && waited < 1500, `waited ${waited.toFixed(0)} ms`) + assert.ok(!(await exists(file)), "no row written while another host holds the lock") +}) + +test("queued requests behind a held lock do not add up their waits", async (t) => { + const file = await fixture(t) + await holder(t, file) + const lines = [] + const original = console.warn + console.warn = (msg) => lines.push(String(msg)) + t.after(() => { console.warn = original }) + const append = createToolsWriter() // default 100 ms, default throttled warning + const started = performance.now() + const results = await Promise.allSettled(Array.from({ length: 30 }, (_, i) => + append(file, { t: Date.now(), agent: "a", id: `q${i}` }))) + const elapsed = performance.now() - started + assert.ok(results.every((r) => r.status === "rejected" && r.reason.code === "HW_LOCK_TIMEOUT")) + // 30 × 100 ms would be 3 s; the shared budget keeps it near 100 ms. + assert.ok(elapsed < 1500, `30 queued requests took ${elapsed.toFixed(0)} ms`) + t.diagnostic(`30 queued requests behind a held lock: ${elapsed.toFixed(0)} ms in total`) + assert.equal(lines.length, 1, "one warning for 30 skipped samples") + assert.match(lines[0], /tool sample skipped: tools\.jsonl\.lock is held by another host/) +}) + +test("under a concurrent peak from two hosts, every accepted row is kept and latency stays bounded", async (t) => { + const file = await fixture(t) + // The other host writes 200 rows continuously while this one takes a burst. + const other = spawn(process.execPath, [CHILD, file, "other", "200", String(1 << 20), "200"], { stdio: "inherit" }) + const append = createToolsWriter({ maxBytes: 1 << 20, warn: () => {} }) // default 100 ms + await new Promise((r) => setTimeout(r, 20)) + const latencies = [] + const results = await Promise.allSettled(Array.from({ length: 100 }, async (_, i) => { + const started = performance.now() + try { await append(file, { t: Date.now(), agent: "peak", id: `peak-${i}` }) } + finally { latencies.push(performance.now() - started) } + })) + assert.equal(await exited(other), 0) + const kept = new Set(await ids(file)) + const accepted = results.map((r, i) => r.status === "fulfilled" && `peak-${i}`).filter(Boolean) + const skipped = results.filter((r) => r.status === "rejected") + assert.ok(skipped.every((r) => r.reason.code === "HW_LOCK_TIMEOUT"), "only lock timeouts skip") + for (const id of accepted) assert.ok(kept.has(id), `accepted ${id} is in the log`) + for (let i = 0; i < 100; i++) if (results[i].status === "rejected") assert.ok(!kept.has(`peak-${i}`)) + for (let i = 0; i < 200; i++) assert.ok(kept.has(`other-${i}`), `other host row ${i} kept`) + const worst = Math.max(...latencies) + assert.ok(worst < 1500, `worst response delay ${worst.toFixed(0)} ms`) + t.diagnostic(`peak: ${accepted.length}/100 kept, ${skipped.length} skipped, worst delay ${worst.toFixed(0)} ms`) +}) + +test("an uncontended append takes the lock without waiting", async (t) => { + const file = await fixture(t) + const append = createToolsWriter({ warn: () => {} }) + await append(file, { t: Date.now(), agent: "a", id: "warm" }) + const started = performance.now() + for (let i = 0; i < 20; i++) await append(file, { t: Date.now(), agent: "a", id: `n${i}` }) + const each = (performance.now() - started) / 20 + assert.ok(each < 100, `per append ${each.toFixed(2)} ms`) +}) + +test("an empty or corrupt lock is not reclaimed", async (t) => { + for (const content of ["", "{not json", JSON.stringify({ token: "x" })]) { + const file = await fixture(t) + await writeFile(file + ".lock", content) + const append = createToolsWriter({ lockTimeoutMs: 150, warn: () => {} }) + await assert.rejects(append(file, { t: Date.now(), agent: "a", id: "x" }), + (e) => e.code === "HW_LOCK_TIMEOUT" && e.reason === "unreadable") + assert.equal(await readFile(file + ".lock", "utf8"), content) + assert.ok(!(await exists(file))) + } +}) + +test("a leftover reaper lock blocks reclaiming instead of being removed", async (t) => { + const file = await fixture(t) + await writeFile(file + ".lock", JSON.stringify({ pid: await deadPid(), token: "dead" })) + await writeFile(file + ".reaper.lock", "") + const append = createToolsWriter({ lockTimeoutMs: 150, warn: () => {} }) + await assert.rejects(append(file, { t: Date.now(), agent: "a", id: "x" }), + (e) => e.code === "HW_LOCK_TIMEOUT" && e.reason === "reaper") + assert.ok(await exists(file + ".lock")) + assert.ok(await exists(file + ".reaper.lock")) +}) + +test("an error inside the critical section releases the lock", async (t) => { + const file = await fixture(t) + await mkdir(file) // appendFile on a directory fails with EISDIR + const append = createToolsWriter({ lockTimeoutMs: 1000, warn: () => {} }) + await assert.rejects(append(file, { t: Date.now(), agent: "a", id: "fail" }), { code: "EISDIR" }) + assert.ok(!(await exists(file + ".lock")), "lock released in finally") + await rm(file, { recursive: true }) + await append(file, { t: Date.now(), agent: "a", id: "ok" }) + assert.deepEqual(await ids(file), ["ok"]) +}) + +test("the holder releases its lock even when the lock can no longer be read", async (t) => { + const file = await fixture(t) + // now() runs inside the critical section: make the held lock unreadable + // there, as a failed read (EMFILE, EIO) at release time would. + const append = createToolsWriter({ warn: () => {}, now: () => { writeFileSync(file + ".lock", ""); return Date.now() } }) + await append(file, { t: Date.now(), agent: "a", id: "one" }) + assert.ok(!(await exists(file + ".lock")), "a live holder never leaves its lock behind") + await append(file, { t: Date.now(), agent: "a", id: "two" }) + assert.deepEqual(await ids(file), ["one", "two"]) +}) + +test("a failed release is reported, throttled and without sample content", async (t) => { + const file = await fixture(t) + const dir = dirname(file) + const lines = [] + const original = console.warn + console.warn = (msg) => lines.push(String(msg)) + t.after(async () => { console.warn = original; await chmod(dir, 0o755).catch(() => {}) }) + // Inside the critical section, make the directory read-only: the append + // still works (the file is open for append) but unlinking the lock fails. + await writeFile(file, "") + const append = createToolsWriter({ warn: () => {}, now: () => { chmodSync(dir, 0o555); return Date.now() } }) + await append(file, { t: Date.now(), agent: "a", id: "SECRET" }) + await chmod(dir, 0o755) + assert.ok(await exists(file + ".lock"), "the release really failed") + await rm(file + ".lock") + await append(file, { t: Date.now(), agent: "a", id: "SECRET2" }) + await chmod(dir, 0o755) + await rm(file + ".lock", { force: true }) + assert.equal(lines.length, 1, "one warning per minute") + assert.match(lines[0], /could not release tools\.jsonl\.lock \(EACCES\)/) + assert.ok(!lines[0].includes("SECRET") && !lines[0].includes(dir)) +}) + +test("a lock whose close fails is removed, not left naming a live pid", async (t) => { + const file = await fixture(t) + const probe = await open(file + ".probe", "w") + const proto = Object.getPrototypeOf(probe) + await probe.close() + // Node defines close per handle, so hook writeFile (shared) and make the + // close of that one handle — the lock file's — fail after really closing. + const writeFileOrig = proto.writeFile + let failNext = true + proto.writeFile = async function (...args) { + const result = await writeFileOrig.apply(this, args) + if (failNext) { + failNext = false + const close = this.close + this.close = async () => { await close.call(this); throw Object.assign(new Error("close failed"), { code: "EIO" }) } + } + return result + } + t.after(() => { proto.writeFile = writeFileOrig }) + const append = createToolsWriter({ warn: () => {} }) + // The first handle.writeFile in append is the lock file's owner record. + await assert.rejects(append(file, { t: Date.now(), agent: "a", id: "x" }), { code: "EIO" }) + assert.ok(!(await exists(file + ".lock")), "no orphaned lock") + await append(file, { t: Date.now(), agent: "a", id: "ok" }) + assert.deepEqual(await ids(file), ["ok"]) +}) + +test("reclaiming a dead lock still respects the deadline", async (t) => { + const file = await fixture(t) + await writeFile(file + ".lock", JSON.stringify({ pid: await deadPid(), token: "dead" })) + // A deadline already passed: reclaiming must not loop on past it. + const append = createToolsWriter({ lockTimeoutMs: -1, warn: () => {} }) + await assert.rejects(append(file, { t: Date.now(), agent: "a", id: "late" }), + (e) => e.code === "HW_LOCK_TIMEOUT" && e.reason === "reclaimed") + assert.ok(!(await exists(file + ".lock")), "the dead lock was still reclaimed") + await createToolsWriter({ warn: () => {} })(file, { t: Date.now(), agent: "a", id: "next" }) + assert.deepEqual(await ids(file), ["next"]) +}) + +test("skipped samples warn at most once a minute and name no sample content", async (t) => { + const file = await fixture(t) + await writeFile(file + ".lock", "") + const lines = [] + const original = console.warn + console.warn = (msg) => lines.push(String(msg)) + t.after(() => { console.warn = original }) + const append = createToolsWriter({ lockTimeoutMs: 50 }) + for (let i = 0; i < 3; i++) await append(file, { t: Date.now(), agent: "secret-agent", id: "SECRET" }).catch(() => {}) + assert.equal(lines.length, 1) + assert.match(lines[0], /tools\.jsonl\.lock is empty or corrupt/) + assert.ok(!lines[0].includes("SECRET") && !lines[0].includes(file)) +}) diff --git a/packages/page-harnessweight/test/fixtures/append-child.mjs b/packages/page-harnessweight/test/fixtures/append-child.mjs new file mode 100644 index 0000000..e479325 --- /dev/null +++ b/packages/page-harnessweight/test/fixtures/append-child.mjs @@ -0,0 +1,23 @@ +// A second plugin host in miniature: appends rows to a shared tools log. +// node append-child.mjs +// node append-child.mjs --hold take the lock, print LOCKED, wait +import { createToolsWriter } from "../../harnessweight.hooks.mjs" +import { open } from "node:fs/promises" + +const args = process.argv.slice(2) +if (args[0] === "--hold") { + // Take the main lock the way the writer does and keep it until killed. + const handle = await open(args[1] + ".lock", "wx") + await handle.writeFile(JSON.stringify({ pid: process.pid, token: "held-by-child", at: Date.now() })) + await handle.close() + process.stdout.write("LOCKED\n") + setInterval(() => {}, 1 << 30) +} else { + const [file, tag, count, maxBytes, pad] = args + // A longer wait than the 100 ms default: this test checks that no row is + // lost under contention, not that contention skips samples. + const append = createToolsWriter({ maxBytes: Number(maxBytes), lockTimeoutMs: 5000, warn: () => {} }) + for (let i = 0; i < Number(count); i++) { + await append(file, { t: Date.now(), agent: tag, id: `${tag}-${i}`, pad: "x".repeat(Number(pad)) }) + } +} diff --git a/packages/page-harnessweight/test/harnessweight.test.mjs b/packages/page-harnessweight/test/harnessweight.test.mjs new file mode 100644 index 0000000..6073ecd --- /dev/null +++ b/packages/page-harnessweight/test/harnessweight.test.mjs @@ -0,0 +1,127 @@ +import { test } from "node:test" +import assert from "node:assert/strict" +import { mkdtemp, readFile, writeFile, appendFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { measureTools } from "../lib/measure.mjs" +import { parseUsageLine, protocolOf, kindOf, createUsageReader } from "../lib/usage.mjs" +import { summarize } from "../lib/summarize.mjs" +import { onRequest, onResponse } from "../harnessweight.hooks.mjs" + +const schema = { type: "object", properties: { path: { type: "string" } } } + +test("measureTools reads all four protocol shapes", () => { + assert.equal(measureTools({ tools: [{ name: "Read", description: "d", input_schema: schema }] }).count, 1) // anthropic + assert.deepEqual(measureTools({ tools: [{ type: "function", function: { name: "shell", parameters: schema } }] }).names, ["shell"]) // chat + assert.deepEqual(measureTools({ tools: [{ type: "namespace", tools: [{ type: "function", name: "a" }, { type: "function", name: "b" }] }] }).names, ["a", "b"]) // responses namespace + assert.deepEqual(measureTools({ tools: [{ functionDeclarations: [{ name: "g1" }, { name: "g2" }] }] }).names, ["g1", "g2"]) // gemini + assert.equal(measureTools({}).count, 0) + assert.ok(measureTools({ tools: [{ name: "x", input_schema: schema }] }).bytes > 0) +}) + +test("usage lines: protocol, failure, cancel, clients", () => { + assert.equal(protocolOf("/v1/chat/completions → /v1/messages"), "anthropic") + assert.equal(protocolOf("/v1/chat/completions → /v1internal:streamGenerateContent?alt=sse"), "gemini") + const ok = parseUsageLine(JSON.stringify({ t: "2026-11-09T10:00:00+08:00", agent: "dsh", model: "m", status: 200, in: 10, cache_read: 90, out: 5 })) + assert.equal(ok.failed, false); assert.equal(ok.cacheRead, 90) + assert.equal(parseUsageLine(JSON.stringify({ t: 1, agent: "a", status: 502 })).failed, true) + const c = parseUsageLine(JSON.stringify({ t: 1, agent: "a", status: 499 })) + assert.equal(c.failed, false); assert.equal(c.cancelled, true) + assert.equal(parseUsageLine("{broken"), null) + assert.equal(kindOf("curl"), "client"); assert.equal(kindOf("ai"), "client"); assert.equal(kindOf("magpie"), "client"); assert.equal(kindOf("dsh"), "agent") +}) + +test("summarize groups by agent, hides clients, computes cache rate", () => { + const now = Date.now() + const r = (agent, inp, cr, failed = false) => ({ t: now - 1000, agent, model: "m", protocol: "anthropic", in: inp, out: 1, cacheRead: cr, cacheWrite: 0, credits: 0, ms: 100, ttft: 10, failed, cancelled: false }) + const usage = [...Array(30)].map(() => r("a", 10, 90)).concat([...Array(30)].map(() => r("b", 50, 50)), [r("curl", 1, 0)]) + const s = summarize({ usage, period: "7d", now }) + assert.deepEqual(s.agents.map((x) => x.agent).sort(), ["a", "b"]) + assert.equal(s.hiddenClients, 1) + const a = s.agents.find((x) => x.agent === "a") + assert.equal(a.cacheRate, 0.9) + assert.ok(s.insights.some((i) => i.kind === "cache")) + assert.equal(summarize({ usage, period: "7d", now, showClients: true }).agents.length, 3) +}) + +test("usage reader is incremental and skips a half-written last line", async () => { + const dir = await mkdtemp(join(tmpdir(), "al-")) + const f = join(dir, "usage.jsonl") + const line = (n) => JSON.stringify({ t: new Date().toISOString(), agent: "x" + n, status: 200, in: 1 }) + "\n" + await writeFile(f, line(1) + line(2) + '{"t":"half') + const r = createUsageReader(f) + await r.refresh(); assert.equal(r.rows().length, 2) + await appendFile(f, '-written"}\n' + line(3)) + await r.refresh(); assert.equal(r.rows().length, 3) +}) + +test("hook never changes the request and writes only names and numbers", async () => { + const dir = await mkdtemp(join(tmpdir(), "al-")) + const body = { model: "m", messages: [{ role: "user", content: "SECRET PROMPT" }], tools: [{ name: "Read", input_schema: schema }] } + const ctx = { agent: "dsh", protocol: "anthropic", model: "m", options: { dataDir: dir } } + assert.equal(await onRequest(structuredClone(body), ctx), undefined) + await onResponse({ usage: { input_tokens: 3, output_tokens: 4, cache_read_input_tokens: 5 } }, { ...ctx, request: body, success: true }) + const text = await readFile(join(dir, "tools.jsonl"), "utf8") + const row = JSON.parse(text.trim()) + assert.equal(row.agent, "dsh"); assert.equal(row.tools, 1); assert.deepEqual(row.toolNames, ["Read"]); assert.equal(row.cacheRead, 5) + assert.ok(!text.includes("SECRET")) +}) + +test("insights ignore clients and use display names", () => { + const now = Date.now() + const r = (agent, inp, cr) => ({ t: now - 1000, agent, model: "m", protocol: "chat", in: inp, out: 1, cacheRead: cr, cacheWrite: 0, credits: 0, ms: 1, ttft: 1, failed: false, cancelled: false }) + const usage = [...Array(30)].flatMap(() => [r("a", 10, 90), r("b", 50, 50), r("curl", 1, 0)]) + const s = summarize({ usage, period: "7d", now, showClients: true, nameOf: (x) => ({ a: "Agent A" })[x] || x }) + assert.ok(s.insights.every((i) => !i.text.includes("curl"))) + assert.ok(s.insights.some((i) => i.text.includes("Agent A"))) +}) + +test("brands come from the gateway and fall back softly", async () => { + const { createBrands } = await import("../lib/brands.mjs") + const ok = createBrands({}, async () => ({ ok: true, json: async () => ({ agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }, { id: "x", name: "X", icon: "generic" }] }) })) + await ok.refresh() + assert.deepEqual(ok.of("claude"), { name: "Claude Code", icon: "claudecode-color.svg" }) + assert.equal(ok.of("x").icon, null) + assert.match(await ok.dataUri("claudecode-color.svg"), /^data:image\/svg\+xml;base64,/) + const down = createBrands({}, async () => { throw new Error("down") }) + await down.refresh() + assert.equal(down.of("codex").name, "codex") +}) + +test("session length is measured, and runaway sessions are counted not measured", () => { + const now = Date.now() + const r = (agent, session, t) => ({ t, agent, model: "m", protocol: "chat", in: 1, out: 1, cacheRead: 0, cacheWrite: 0, ms: 1, ttft: 1, failed: false, cancelled: false, session }) + const usage = [ + r("a", "s1", now - 600e3), r("a", "s1", now - 300e3), // 5 minutes + r("a", "s2", now - 20_000e3), r("a", "s2", now - 10_000e3), // 10 seconds + r("a", "s3", now - 30 * 3600e3), r("a", "s3", now - 10e3), // open for a day: not measured + ] + const s = summarize({ usage, period: "7d", now, showClients: true }) + const a = s.agents.find((x) => x.agent === "a") + assert.equal(a.session.count, 3) + assert.equal(a.session.measured, 2) + assert.equal(a.session.open, 1) + assert.equal(a.session.median, 10_000_000) + assert.ok(a.session.longest <= 6 * 3600e3) +}) + +test("agents without a session id report no session length", () => { + const now = Date.now() + const usage = [{ t: now, agent: "a", model: "m", protocol: "chat", in: 1, out: 1, cacheRead: 0, cacheWrite: 0, ms: 1, ttft: 1, failed: false, cancelled: false }] + const s = summarize({ usage, period: "7d", now, showClients: true }) + const a = s.agents.find((x) => x.agent === "a") + assert.equal(a.session.count, 0) + assert.equal(a.session.median, null) +}) + +test("the protocol each agent speaks is reported", () => { + const now = Date.now() + const usage = [ + { t: new Date(now).toISOString(), agent: "a", model: "m", ep: "/v1/messages", status: 200, in: 1, out: 1, cache_read: 0, cache_write: 0, ms: 1, ttft_ms: 1 }, + { t: new Date(now).toISOString(), agent: "a", model: "m", ep: "/v1/messages", status: 200, in: 1, out: 1, cache_read: 0, cache_write: 0, ms: 1, ttft_ms: 1 }, + { t: new Date(now).toISOString(), agent: "a", model: "m", ep: "/v1/responses", status: 200, in: 1, out: 1, cache_read: 0, cache_write: 0, ms: 1, ttft_ms: 1 }, + ].map((d) => parseUsageLine(JSON.stringify(d))) + const s = summarize({ usage, period: "7d", now, showClients: true }) + const a = s.agents.find((x) => x.agent === "a") + assert.deepEqual(a.protocols.map((p) => p.name), ["anthropic", "responses"]) +}) diff --git a/packages/page-harnessweight/test/i18n.test.mjs b/packages/page-harnessweight/test/i18n.test.mjs new file mode 100644 index 0000000..ab83169 --- /dev/null +++ b/packages/page-harnessweight/test/i18n.test.mjs @@ -0,0 +1,103 @@ +import { test } from "node:test" +import assert from "node:assert/strict" +import { createServer } from "node:http" +import { mkdtemp, readFile, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { TEXT, languageFor, pageLanguage, languageTags, translate, insight } from "../app/i18n.mjs" +import { insights } from "../lib/summarize.mjs" +import { createHandler } from "../service.mjs" + +const CJK = /[\u4e00-\u9fff]/ + +test("English and Chinese tables have the same keys and no empty strings", () => { + assert.deepEqual(Object.keys(TEXT.en).sort(), Object.keys(TEXT.zh).sort()) + for (const lang of ["en", "zh"]) for (const [k, v] of Object.entries(TEXT[lang])) assert.ok(v.trim(), `${lang} ${k}`) + for (const [k, v] of Object.entries(TEXT.en)) assert.doesNotMatch(v, CJK, `en ${k} still Chinese`) +}) + +test("placeholders match between languages", () => { + const names = (s) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort() + for (const k of Object.keys(TEXT.en)) assert.deepEqual(names(TEXT.en[k]), names(TEXT.zh[k]), k) +}) + +test("languageFor follows magpie's tags; untranslated languages read English", () => { + assert.equal(languageFor("zh-CN"), "zh") + assert.equal(languageFor("zh_Hans"), "zh") + assert.equal(languageFor("zh-Hant-TW"), "zh-TW") + assert.equal(languageFor("ja-JP"), "ja") + assert.equal(languageFor("en-US"), "en") + assert.equal(languageFor(""), "en") + assert.equal(languageTags.zh, "zh-CN") + assert.equal(pageLanguage("zh-TW"), "en") + assert.equal(pageLanguage("ja-JP"), "en") + assert.equal(pageLanguage("zh-CN"), "zh") + // zh-TW and ja have no table yet: they must fall back to English, never Simplified Chinese + assert.equal(translate("zh-TW", "status.loading"), TEXT.en["status.loading"]) + assert.equal(translate("ja", "status.loading"), TEXT.en["status.loading"]) + assert.equal(translate("zh", "status.loading"), "正在读取…") + assert.equal(translate("en", "kpi.requests", { count: "1,234" }), "1,234 requests") + assert.equal(translate("en", "kpi.requests"), "{count} requests") + assert.equal(translate("en", "no.such.key"), "no.such.key") +}) + +test("insights speak the requested language with the same numbers and real Chinese names", () => { + const mk = (agent, avgPrompt, cacheRate, prompt, errorRate) => ({ agent, kind: "agent", calls: 50, avgPrompt, cacheRate, prompt, errorRate }) + const agents = [mk("a", 30000, 0.9, 1.5e6, 0.0), mk("b", 6000, 0.4, 3e5, 0.1)] + const names = { a: "克劳德", b: "代码助手" } + const zh = insights(agents, (a) => names[a], "zh") + const en = insights(agents, (a) => names[a], "en") + assert.deepEqual(zh.map((i) => i.kind), en.map((i) => i.kind)) + const zp = zh.find((i) => i.kind === "prompt").text, ep = en.find((i) => i.kind === "prompt").text + assert.equal(zp, "克劳德 每次请求平均读 30.0K token,是 代码助手 的 5.0 倍。") + assert.equal(ep, "克劳德 reads an average of 30.0K tokens per request, 5.0x 代码助手.") + // apart from user-supplied agent names, the English sentences carry no Chinese + for (const i of en) assert.doesNotMatch(i.text.replaceAll(names.a, "").replaceAll(names.b, ""), CJK, i.kind) + // default stays Chinese for existing callers + assert.equal(insights(agents, (a) => names[a])[0].text, zh[0].text) + assert.equal(insight("ja", "errors", { name: "x", rate: "10.0%" }), "x has a failure rate of 10.0%; failed requests may still consume tokens.") +}) + +test("interface sources outside the table carry no hardcoded Chinese", async () => { + for (const f of ["../app/app.js", "../app/explain.js", "../lib/summarize.mjs"]) { + const src = await readFile(new URL(f, import.meta.url), "utf8") + const lines = src.split("\n").filter((l) => CJK.test(l) && !l.trim().startsWith("//")) + assert.deepEqual(lines, [], f) + } + const html = await readFile(new URL("../app/index.html", import.meta.url), "utf8") + for (const l of html.split("\n").filter((l) => CJK.test(l))) assert.match(l, /data-t=|aria-label-t=/, l) +}) + +test("app.js escapes translated text it puts into HTML", async () => { + const src = await readFile(new URL("../app/app.js", import.meta.url), "utf8") + // every T(...) interpolated straight into markup goes through esc() + const raw = src.split("\n").filter((l) => l.includes("<") && l.includes("${T(")) + assert.deepEqual(raw, [], "found ${T(...)} in markup without esc()") +}) + +async function start() { + const dir = await mkdtemp(join(tmpdir(), "hw-i18n-")) + const usageLog = join(dir, "usage.jsonl") + await writeFile(usageLog, "") + const srv = createServer() + await new Promise((r) => srv.listen(0, "127.0.0.1", r)) + const port = srv.address().port + srv.on("request", createHandler({ port, usageLog, dataDir: dir, token: "t".repeat(64), gatewayUrl: "http://127.0.0.1:9" })) + return { port, close: () => srv.close() } +} + +test("service serves the shared module as JavaScript and marks the page language", async () => { + const s = await start() + try { + const mod = await fetch(`http://127.0.0.1:${s.port}/i18n.mjs`, { headers: { Origin: "null" } }) + assert.equal(mod.status, 200) + assert.match(mod.headers.get("content-type"), /^text\/javascript/) + const en = await (await fetch(`http://127.0.0.1:${s.port}/?lang=en-US`)).text() + assert.match(en, //) + const zh = await (await fetch(`http://127.0.0.1:${s.port}/?lang=zh-CN`)).text() + assert.match(zh, //) + const bad = await (await fetch(`http://127.0.0.1:${s.port}/?lang=%22%3E%3Cscript%3E`)).text() + assert.match(bad, //) + assert.match(await (await fetch(`http://127.0.0.1:${s.port}/?lang=ja-JP`)).text(), //) + } finally { s.close() } +}) diff --git a/packages/page-harnessweight/test/paths-brands.test.mjs b/packages/page-harnessweight/test/paths-brands.test.mjs new file mode 100644 index 0000000..870401f --- /dev/null +++ b/packages/page-harnessweight/test/paths-brands.test.mjs @@ -0,0 +1,155 @@ +import test from "node:test" +import assert from "node:assert/strict" +import { mkdtempSync, mkdirSync, symlinkSync, writeFileSync, existsSync, realpathSync, rmSync } from "node:fs" +import { tmpdir, homedir } from "node:os" +import { join, resolve } from "node:path" +import { magpieDir, usageLog, toolsLog } from "../lib/paths.mjs" +import { gatewayUrl } from "../lib/brands.mjs" +import { spawnSync } from "node:child_process" +import { createServer } from "node:http" + +function isolated(fn) { + const dir = mkdtempSync(join(tmpdir(), "harnessweight-paths-")) + const cwd = process.cwd() + const keys = ["XDG_CONFIG_HOME", "MAGPIE_ADDR", "MAGPIE_GATEWAY_URL", "HOME"] + const previous = Object.fromEntries(keys.map((k) => [k, process.env[k]])) + for (const k of keys) delete process.env[k] + process.env.HOME = realpathSync(dir) + process.chdir(dir) + try { return fn(dir) } finally { + process.chdir(cwd) + for (const k of keys) { + if (previous[k] === undefined) delete process.env[k] + else process.env[k] = previous[k] + } + // dir is the absolute directory created by mkdtempSync above. + rmSync(realpathSync(dir), { recursive: true, force: true }) + } +} + +test("hook process and service process select the same files", () => isolated((dir) => { + const real = realpathSync(dir) + writeFileSync(join(real, "plugins.json"), "{}") + // The host runs the hook with its cwd on the config dir; the service is + // told the same dir through input.directory. Two processes, one answer. + const hook = spawnSync(process.execPath, ["--input-type=module", "-e", ` + import { toolsLog, usageLog } from ${JSON.stringify(new URL("../lib/paths.mjs", import.meta.url).href)} + process.stdout.write(JSON.stringify({ tools: toolsLog(), usage: usageLog() })) + `], { cwd: real, encoding: "utf8", timeout: 10000 }) + assert.equal(hook.status, 0, hook.stderr || String(hook.error || "")) + const fromHook = JSON.parse(hook.stdout) + assert.equal(fromHook.tools, join(real, "harnessweight", "tools.jsonl")) + assert.equal(fromHook.usage, join(real, "usage.jsonl")) + assert.equal(fromHook.tools, toolsLog({ directory: real })) + assert.equal(fromHook.usage, usageLog({ directory: real })) +})) + +test("server forwards host input.directory to its usage and tools readers", async () => { + const entry = new URL("../index.mjs", import.meta.url).href + const directory = realpathSync(mkdtempSync(join(tmpdir(), "harnessweight-portable-"))) + const probe = createServer() + await new Promise((resolve, reject) => { + probe.once("error", reject) + probe.listen(0, "127.0.0.1", resolve) + }) + const port = probe.address().port + await new Promise((resolve, reject) => probe.close((error) => error ? reject(error) : resolve())) + try { + const result = spawnSync(process.execPath, ["--input-type=module", "-e", ` + import assert from "node:assert/strict" + const { default: plugin } = await import(${JSON.stringify(entry)}) + assert.equal(process.env.HARNESSWEIGHT_PORT, undefined) + await plugin.server({ directory: ${JSON.stringify(directory)} }, { token: "test", port: ${port} }) + let response + for (let attempt = 0; attempt < 50; attempt++) { + try { + response = await fetch("http://127.0.0.1:${port}/api/summary?k=test") + break + } catch { await new Promise((resolve) => setTimeout(resolve, 20)) } + } + assert.ok(response, "service should start") + const body = await response.json() + assert.equal(body.sources.usageLog, ${JSON.stringify(join(directory, "usage.jsonl"))}) + assert.equal(body.sources.toolsLog, ${JSON.stringify(join(directory, "harnessweight", "tools.jsonl"))}) + process.exit(0) + `], { encoding: "utf8", timeout: 10000 }) + assert.equal(result.status, 0, result.stderr || String(result.error || "")) + } finally { + rmSync(directory, { recursive: true, force: true }) + } +}) + +test("portable host directory wins, including a fresh directory", () => isolated((dir) => { + process.env.XDG_CONFIG_HOME = join(dir, "xdg") + writeFileSync(join(dir, "providers.json"), "{}") + const directory = join(realpathSync(dir), "fresh-portable") + assert.equal(magpieDir({ directory }), directory) + assert.equal(usageLog({ directory }), join(directory, "usage.jsonl")) + assert.equal(toolsLog({ directory }), join(directory, "harnessweight", "tools.jsonl")) + assert.equal(usageLog({ directory, usageLog: "custom.jsonl" }), resolve("custom.jsonl")) + assert.equal(toolsLog({ directory, dataDir: "samples" }), resolve("samples/tools.jsonl")) +})) + +for (const marker of ["usage.jsonl", "plugins.json", "providers.json"]) { + test(`hook cwd and service input agree with ${marker}`, () => isolated((dir) => { + process.env.XDG_CONFIG_HOME = join(dir, "wrong-xdg") + writeFileSync(join(dir, marker), "") + const real = realpathSync(dir) + assert.equal(magpieDir(), real) + assert.equal(magpieDir({ directory: dir }), real) + assert.equal(usageLog(), usageLog({ directory: dir })) + assert.equal(toolsLog(), toolsLog({ directory: dir })) + })) +} + +test("a symlinked config dir names the same directory as its real path", () => isolated((dir) => { + writeFileSync(join(dir, "plugins.json"), "{}") + const link = join(dir, "link") + symlinkSync(dir, link) + const real = realpathSync(dir) + assert.equal(magpieDir({ directory: link }), real) + assert.equal(magpieDir({ directory: dir }), real) + assert.equal(magpieDir({ directory: join(link, "not-yet") }), join(real, "not-yet")) +})) + +test("standalone uses absolute XDG and rejects relative XDG", () => isolated((dir) => { + const expectedHome = magpieDir({ directory: join(homedir(), ".config", "magpie") }) + assert.equal(magpieDir(), expectedHome) + process.env.XDG_CONFIG_HOME = "relative-config" + assert.equal(magpieDir(), expectedHome) + process.env.XDG_CONFIG_HOME = join(dir, "xdg") + assert.equal(magpieDir(), join(realpathSync(dir), "xdg", "magpie")) +})) + +test("legacy samples migrate within the selected portable directory", () => isolated((dir) => { + writeFileSync(join(dir, "plugins.json"), "{}") + const real = realpathSync(dir) + mkdirSync(join(real, "agent-lens")) + writeFileSync(join(real, "agent-lens", "tools.jsonl"), "sample\n") + assert.equal(toolsLog(), join(real, "harnessweight", "tools.jsonl")) + assert.equal(existsSync(join(real, "harnessweight", "tools.jsonl")), true) + assert.equal(existsSync(join(real, "agent-lens")), false) +})) + +test("gateway respects explicit overrides and host address forms", () => isolated(() => { + assert.equal(gatewayUrl(), "http://127.0.0.1:3425") + for (const [addr, expected] of [ + ["localhost:18086", "localhost:18086"], + [" 127.0.0.1:1234 ", "127.0.0.1:1234"], + ["0.0.0.0:1234", "127.0.0.1:1234"], + ["[::]:1234", "127.0.0.1:1234"], + ["[::1]:1234", "[::1]:1234"], + ["[2001:DB8::1]:1234", "[2001:DB8::1]:1234"], + ]) { + process.env.MAGPIE_ADDR = addr + assert.equal(gatewayUrl(), `http://${expected}`) + } + for (const addr of ["bad", "::1:1234", "localhost:abc", "host:123/path"]) { + process.env.MAGPIE_ADDR = addr + assert.equal(gatewayUrl(), "http://127.0.0.1:3425") + } + process.env.MAGPIE_ADDR = "localhost:18086" + process.env.MAGPIE_GATEWAY_URL = "https://gateway.example/" + assert.equal(gatewayUrl(), "https://gateway.example") + assert.equal(gatewayUrl({ gatewayUrl: "http://custom:8080///" }), "http://custom:8080") +})) diff --git a/packages/page-harnessweight/test/paths-migration.test.mjs b/packages/page-harnessweight/test/paths-migration.test.mjs new file mode 100644 index 0000000..b4b888c --- /dev/null +++ b/packages/page-harnessweight/test/paths-migration.test.mjs @@ -0,0 +1,163 @@ +// The migration of the legacy agent-lens samples into harnessweight is done +// on the way to the path, so two hosts (the hook and the service) can reach +// it at the same time. These tests pin the outcome of that race: one path, +// and no sample left behind. +import { test } from "node:test" +import assert from "node:assert/strict" +import { mkdtempSync, mkdirSync, writeFileSync, existsSync, readFileSync, chmodSync, realpathSync, rmSync, readdirSync, symlinkSync } from "node:fs" +import { tmpdir } from "node:os" +import { join, dirname, basename } from "node:path" +import { spawn } from "node:child_process" +import { magpieDir, toolsLog, usageLog } from "../lib/paths.mjs" + +const PATHS_URL = new URL("../lib/paths.mjs", import.meta.url).href + +function sandbox() { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "hw-migration-"))) + return dir +} + +// A config dir that still holds the legacy samples. +function legacy(base, rows = [{ t: Date.now(), agent: "dsh", id: "legacy" }]) { + writeFileSync(join(base, "plugins.json"), "{}") + mkdirSync(join(base, "agent-lens")) + writeFileSync(join(base, "agent-lens", "tools.jsonl"), rows.map((r) => JSON.stringify(r) + "\n").join("")) + return base +} + +function cleanup(dir) { + try { chmodSync(dir, 0o755) } catch { /* already gone */ } + rmSync(dir, { recursive: true, force: true }) +} + +test("a host that already migrated is never sent back to the legacy directory", () => { + const base = sandbox() + try { + // The other host won the race: the new directory is there, the old one + // is gone. + mkdirSync(join(base, "harnessweight")) + writeFileSync(join(base, "harnessweight", "tools.jsonl"), "") + assert.equal(toolsLog({ directory: base }), join(base, "harnessweight", "tools.jsonl")) + } finally { + cleanup(base) + } +}) + +test("both directories present keeps the new one and leaves the legacy samples alone", () => { + const base = sandbox() + try { + legacy(base) + mkdirSync(join(base, "harnessweight")) + writeFileSync(join(base, "harnessweight", "tools.jsonl"), "") + assert.equal(toolsLog({ directory: base }), join(base, "harnessweight", "tools.jsonl")) + // The legacy samples are untouched, not moved and not deleted. + assert.equal(existsSync(join(base, "agent-lens", "tools.jsonl")), true) + } finally { + cleanup(base) + } +}) + +test("a migration that cannot happen keeps the legacy directory usable", { skip: process.getuid?.() === 0 ? "root ignores directory permissions" : false }, () => { + const base = sandbox() + try { + legacy(base) + chmodSync(base, 0o555) + // The rename cannot succeed here, so the samples must stay readable + // where they are instead of pointing at a directory that never appears. + assert.equal(toolsLog({ directory: base }), join(base, "agent-lens", "tools.jsonl")) + assert.equal(existsSync(join(base, "agent-lens", "tools.jsonl")), true) + } finally { + cleanup(base) + } +}) + +// Hosts that ask for the path at the same time must get the same answer. +// The loser of the rename is the interesting one: the samples are already +// moved, so answering with the legacy path would hide them. +test("concurrent hosts agree on one path and every sample survives", async () => { + const base = sandbox() + try { + legacy(base, Array.from({ length: 50 }, (_, i) => ({ t: Date.now(), agent: "dsh", id: "row-" + i }))) + const workers = 8 + mkdirSync(join(base, "ready")) + const child = ` + import { writeFileSync, existsSync } from "node:fs"; + import { join } from "node:path"; + import { toolsLog } from ${JSON.stringify(PATHS_URL)}; + const base = ${JSON.stringify(base)}; + writeFileSync(join(base, "ready", ${JSON.stringify("x")} + process.argv[1]), ""); + while (!existsSync(join(base, "go"))) await new Promise((r) => setTimeout(r, 2)); + process.stdout.write(toolsLog({ directory: base })); + ` + const runs = Array.from({ length: workers }, (_, i) => new Promise((resolve, reject) => { + const child1 = spawn(process.execPath, ["--input-type=module", "-e", child, String(i)], { encoding: "utf8" }) + let out = "" + let err = "" + child1.stdout.on("data", (c) => { out += c }) + child1.stderr.on("data", (c) => { err += c }) + child1.on("error", reject) + child1.on("close", (code) => resolve({ code, out, err })) + })) + // Release them together. + const deadline = Date.now() + 10000 + while (existsSync(join(base, "ready")) && Date.now() < deadline) { + const ready = readdirSync(join(base, "ready")) + if (ready.length >= workers) break + await new Promise((r) => setTimeout(r, 10)) + } + writeFileSync(join(base, "go"), "") + const results = await Promise.all(runs) + for (const r of results) assert.equal(r.code, 0, r.err) + const paths = new Set(results.map((r) => r.out)) + assert.equal(paths.size, 1, "every host must name the same file: " + [...paths].join(", ")) + const expected = join(base, "harnessweight", "tools.jsonl") + assert.equal([...paths][0], expected) + // The migration happened exactly once and the samples are all there. + assert.equal(existsSync(join(base, "agent-lens")), false) + const rows = readFileSync(expected, "utf8").trim().split("\n").map((l) => JSON.parse(l)) + assert.equal(rows.length, 50) + assert.equal(new Set(rows.map((r) => r.id)).size, 50) + } finally { + cleanup(base) + } +}) + +test("hook and service agree on the path in every branch", () => { + const base = sandbox() + try { + legacy(base) + // The host names the directory (service) and runs the hook with the + // same directory as its working directory (hook). Both must land on + // the same file, whichever spelling they use. + const fromService = toolsLog({ directory: base }) + const fromHook = toolsLog({ directory: join(base, "..", base.split("/").pop()) }) + assert.equal(fromService, fromHook) + assert.equal(fromService, join(base, "harnessweight", "tools.jsonl")) + // The usage log follows the same directory. + assert.equal(usageLog({ directory: base }), join(base, "usage.jsonl")) + // An explicit data directory is used as given, by both sides. + const data = join(base, "samples") + mkdirSync(data) + assert.equal(toolsLog({ directory: base, dataDir: data }), join(data, "tools.jsonl")) + assert.equal(usageLog({ directory: base, usageLog: join(base, "u.jsonl") }), join(base, "u.jsonl")) + } finally { + cleanup(base) + } +}) + +test("a symlinked config dir is named the same way by both hosts", () => { + const base = sandbox() + const linkPath = join(dirname(base), "hw-migration-link-" + basename(base)) + try { + legacy(base) + symlinkSync(base, linkPath) + const real = realpathSync(base) + // The service is told the symlinked path, the hook sees the real one. + assert.equal(toolsLog({ directory: linkPath }), join(real, "harnessweight", "tools.jsonl")) + assert.equal(toolsLog({ directory: real }), join(real, "harnessweight", "tools.jsonl")) + assert.equal(magpieDir({ directory: linkPath }), real) + } finally { + rmSync(linkPath, { force: true }) + cleanup(base) + } +}) diff --git a/packages/page-harnessweight/test/rollover.test.mjs b/packages/page-harnessweight/test/rollover.test.mjs new file mode 100644 index 0000000..04c6487 --- /dev/null +++ b/packages/page-harnessweight/test/rollover.test.mjs @@ -0,0 +1,96 @@ +import { test } from "node:test" +import assert from "node:assert/strict" +import { mkdtemp, readFile, writeFile, stat, rename, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { createToolsWriter, MAX_FILE_BYTES, AGE_CHECK_MS } from "../harnessweight.hooks.mjs" +import { createToolsReader } from "../lib/tools.mjs" + +const AGE = 30 * 24 * 3600e3 +async function fixture(t) { + const dir = await mkdtemp(join(tmpdir(), "hw-rollover-")) + t.after(() => rm(dir, { recursive: true, force: true })) + return join(dir, "tools.jsonl") +} +const sample = (t, id) => ({ t, agent: "test", id }) +function padded(row, bytes) { + const base = JSON.stringify({ ...row, pad: "" }) + "\n" + return JSON.stringify({ ...row, pad: "x".repeat(bytes - Buffer.byteLength(base)) }) + "\n" +} + +test("concurrent appends crossing 8 MiB preserve every row across both generations", async (t) => { + const file = await fixture(t) + const now = Date.now() + await writeFile(file, padded(sample(now, "seed"), MAX_FILE_BYTES - 300)) + const append = createToolsWriter() + await Promise.all(Array.from({ length: 200 }, (_, i) => append(file, sample(now, i)))) + for (const path of [file, file + ".1"]) assert.ok((await stat(path)).size <= MAX_FILE_BYTES) + const reader = createToolsReader(file) + await reader.refresh() + assert.equal(reader.rows().length, 201) + assert.equal(new Set(reader.rows().map((r) => r.id)).size, 201) + assert.equal(reader.rows()[0].id, "seed") +}) + +test("second rollover retires only the oldest generation", async (t) => { + const file = await fixture(t) + const now = Date.now() + const append = createToolsWriter() + const full = (id) => JSON.parse(padded(sample(now, id), MAX_FILE_BYTES)) + await append(file, full("first")) + await append(file, full("second")) + await append(file, sample(now, "third")) + const reader = createToolsReader(file) + await reader.refresh() + assert.deepEqual(reader.rows().map((r) => r.id), ["second", "third"]) + assert.equal((await stat(file + ".1")).size, MAX_FILE_BYTES) +}) + +test("age check runs hourly even below 512 KiB and reader expires unchanged rows", async (t) => { + const file = await fixture(t) + let now = Date.now() + const append = createToolsWriter({ now: () => now }) + const old = sample(now - AGE + 1, "aging") + await writeFile(file, JSON.stringify(old) + "\n") + await append(file, sample(now, "fresh")) + now += AGE_CHECK_MS - 1 + await append(file, sample(now, "before-hour")) + await assert.rejects(stat(file + ".1"), { code: "ENOENT" }) + now += 1 + await append(file, sample(now, "at-hour")) + assert.ok((await readFile(file + ".1", "utf8")).includes("aging")) + const reader = createToolsReader(file, { now: () => now }) + await reader.refresh() + assert.deepEqual(reader.rows().map((r) => r.id), ["fresh", "before-hour", "at-hour"]) + now += AGE + 1 + await reader.refresh() + assert.deepEqual(reader.rows(), []) +}) + +test("reader detects same-size inode replacement, ignores malformed and incomplete records", async (t) => { + const file = await fixture(t) + const now = Date.now() + await writeFile(file, JSON.stringify(sample(now, "one")) + "\n") + const reader = createToolsReader(file) + await reader.refresh() + await writeFile(file + ".replacement", JSON.stringify(sample(now, "two")) + "\n") + await rename(file + ".replacement", file) + await reader.refresh() + assert.deepEqual(reader.rows().map((r) => r.id), ["two"]) + await writeFile(file + ".1", 'null\nmalformed\n' + JSON.stringify(sample(now - AGE - 1, "expired")) + "\n") + await writeFile(file, JSON.stringify(sample(now, "complete")) + "\n" + JSON.stringify(sample(now, "partial"))) + await reader.refresh() + assert.deepEqual(reader.rows().map((r) => r.id), ["complete"]) +}) + +test("oversized sample is rejected and failed writes do not poison the queue", async (t) => { + const file = await fixture(t) + const append = createToolsWriter() + await assert.rejects(append(file, { pad: "x".repeat(MAX_FILE_BYTES) }), RangeError) + await writeFile(file, "") + await assert.rejects(append(join(file, "child"), sample(Date.now(), "fail"))) + // Repair the failed destination and retry the exact same queued path. + await rm(file) + await append(join(file, "child"), sample(Date.now(), "recovered")) + assert.equal(JSON.parse(await readFile(join(file, "child"), "utf8")).id, "recovered") +}) diff --git a/packages/page-harnessweight/test/service.test.mjs b/packages/page-harnessweight/test/service.test.mjs new file mode 100644 index 0000000..0f3c0eb --- /dev/null +++ b/packages/page-harnessweight/test/service.test.mjs @@ -0,0 +1,80 @@ +import { test } from "node:test" +import assert from "node:assert/strict" +import { createServer } from "node:http" +import { mkdtemp, readFile, readdir, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { createHandler, TOKEN_HEADER } from "../service.mjs" + +async function start() { + const dir = await mkdtemp(join(tmpdir(), "al-svc-")) + const usageLog = join(dir, "usage.jsonl") + await writeFile(usageLog, JSON.stringify({ t: new Date().toISOString(), agent: "dsh", model: "m", status: 200, in: 1, cache_read: 9, out: 2 }) + "\n") + const srv = createServer() + await new Promise((r) => srv.listen(0, "127.0.0.1", r)) + const port = srv.address().port + srv.on("request", createHandler({ port, usageLog, dataDir: dir, token: "t".repeat(64), gatewayUrl: "http://127.0.0.1:9" })) + return { port, close: () => srv.close() } +} +const get = (port, path, headers = {}) => fetch(`http://127.0.0.1:${port}${path}`, { headers }) + +test("api needs the token; the token is only in the page HTML, which has no CORS header", async () => { + const s = await start() + try { + assert.equal((await get(s.port, "/api/summary")).status, 403) + assert.equal((await get(s.port, "/api/summary", { [TOKEN_HEADER]: "wrong" })).status, 403) + const ok = await get(s.port, "/api/summary", { [TOKEN_HEADER]: "t".repeat(64), Origin: "null" }) + assert.equal(ok.status, 200) + assert.equal((await ok.json()).agents[0].agent, "dsh") + assert.equal((await get(s.port, `/api/summary?k=${"t".repeat(64)}`, { Origin: "null" })).status, 200) + const page = await get(s.port, "/", { Origin: "null" }) + assert.equal(page.headers.get("access-control-allow-origin"), null) + assert.match(await page.text(), /name="harnessweight-token" content="t{64}"/) + const health = await (await get(s.port, "/api/health")).json() + assert.deepEqual(Object.keys(health).sort(), ["ok", "service"]) + } finally { s.close() } +}) + +test("other hosts, other origins and path traversal are refused", async () => { + const s = await start() + try { + const h = { [TOKEN_HEADER]: "t".repeat(64) } + assert.equal((await get(s.port, "/api/summary", { ...h, Origin: "https://evil.example" })).status, 403) + // DNS rebinding: same socket, foreign Host + const r = await new Promise((resolve) => { + import("node:http").then(({ request }) => { + const q = request({ host: "127.0.0.1", port: s.port, path: "/api/summary", headers: { ...h, Host: "evil.example" } }, resolve) + q.end() + }) + }) + assert.equal(r.statusCode, 403) + const t = await new Promise((resolve) => { + import("node:http").then(({ request }) => { + const q = request({ host: "127.0.0.1", port: s.port, path: "/../service.mjs" }, resolve) + q.end() + }) + }) + assert.notEqual(t.statusCode, 200) + assert.equal((await get(s.port, '/%E0')).status, 400) + } finally { s.close() } +}) + +test("the service, page bridge and defaults agree on the community port", async () => { + const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")) + const boot = await readFile(new URL("../page/boot.js", import.meta.url), "utf8") + const server = await readFile(new URL("../service.mjs", import.meta.url), "utf8") + assert.equal(pkg.magpie.page.service.port, 3496) + assert.equal(pkg.magpie.options.port, 3496) + assert.match(boot, /let port = 3496\b/) + assert.match(server, /Number\(options\.port\) > 0 \? Number\(options\.port\) : 3496/) +}) + +test("the page in magpie's frame reaches no network and declares no reads", async () => { + const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")) + assert.deepEqual(pkg.magpie.permissions, []) + const dir = new URL("../page/", import.meta.url) + for (const f of (await readdir(dir)).filter((f) => /\.(js|html)$/.test(f))) { + const src = await readFile(new URL(f, dir), "utf8") + assert.doesNotMatch(src, /\bfetch\s*\(|XMLHttpRequest|WebSocket|EventSource|sendBeacon|magpie\.read\s*\(/, f) + } +}) diff --git a/registry.json b/registry.json index dbe561a..db5b484 100644 --- a/registry.json +++ b/registry.json @@ -282,6 +282,8 @@ "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 本地用量历史,不联网。" } } + "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-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 采样工具大小并追踪进行中的请求。" } } ] }