diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index d4b0ba6..a5377f6 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -440,6 +440,14 @@ What is measured, and what is easy to read wrongly: 429 whose named reset is still ahead makes the window full — `used: 100`, `resetsAt` the reset the vendor named — whatever the rows add up to. The sum carries the window only until the first refusal. +- **A refusal hidden by routing still counts.** A group that moves to + another provider after the 429 writes only the 200 that answered, so the + failed WorkBuddy attempt is read from `routing/YYYY-MM-DD.jsonl` (or its + `.gz`) as well: its vendor words — or the gateway rest's `until` and + `key`, which names the account and model — pin the window the same way. + Three days of traces are read, the current plain file and the compressed + days before it, and what they held is kept until a trace itself changes; + an append to `usage.jsonl` does not decompress them again. - **The sum is shown, not routed on.** Until the vendor refuses, the card is set aside (`aside: true`): magpie draws it beside the account and never counts it as the account's allowance, so an estimate near its cap does not diff --git a/packages/workbuddy/freewindow.test.mjs b/packages/workbuddy/freewindow.test.mjs index c1b7ddc..ecdf832 100644 --- a/packages/workbuddy/freewindow.test.mjs +++ b/packages/workbuddy/freewindow.test.mjs @@ -4,15 +4,19 @@ // freeWindowOf for the readings and how each was checked. import { test, expect, beforeAll } from "bun:test" import { tmpdir } from "node:os" -import { mkdtempSync, mkdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs" +import { appendFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs" import { homedir } from "node:os" -import { join } from "node:path" +import { basename, join } from "node:path" +import { gzipSync } from "node:zlib" let _internal +let routingReads +let routingParsed beforeAll(async () => { // as usage.test.mjs: run with HOME=$(mktemp -d) bun test if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") ;({ _internal } = await import("./index.mjs")) + ;({ routingReads, routingParsed } = _internal) }) // a row of magpie's usage ledger (usage.Record), as the plugin reads it @@ -40,6 +44,23 @@ const FAT = "x".repeat(1400) // the vendor's words before the reset it names const TIMEOUT_BEFORE_RESET = "WorkBuddy AI: usage exceeds frequency limit, but don't worry, your usage will reset at " +const routingTrace = (tries, orders = [{ id: "wb-me", provider: "workbuddy-ai", who: "me@example.com" }]) => + JSON.stringify({ time: "2026-11-02T12:00:00+08:00", order: orders, tries }) + +const routingRefusal = (reset, { model = "deepseek-v4.1-flash", id = "wb-me", provider = "workbuddy-ai", rest = undefined } = {}) => ({ + id, + model, + status: 429, + start: "2026-11-02T12:00:01+08:00", + error: `${TIMEOUT_BEFORE_RESET}${reset} UTC+8, alternatively, you can switch to the other models to continue using it.`, + ...(rest ? { rest } : {}), +}) + +const localDay = (now) => { + const d = new Date(now) + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}` +} + // the refusal WorkBuddy AI sends when the window is spent const refusal = (reset, account = "me@example.com") => row(`2026-10-20T19:47:41+08:00`, { @@ -99,6 +120,45 @@ test("-sg counts in the same window as the free id", () => { expect(w.models).toEqual(["deepseek-v4.1-flash", "deepseek-v4.1-flash-sg"]) }) +test("a routing trace refusal of an alias counts in the same window", () => { + const now = at("2026-11-02T12:30:00+08:00") + const rows = [..._internal.routingRefusalRows( + "", + false, + now, + "me@example.com", + undefined, + routingTrace([routingRefusal("2026-11-02 19:17:02", { model: "deepseek-v4.1-flash-sg" })]), + ), row("2026-11-02T02:00:00+08:00", { in: 1 })] + const w = _internal.freeWindowOf(rows, "me@example.com", now) + expect(w.refused).toBe(true) + expect(w.resetsAt).toBe(iso("2026-11-02T19:17:02+08:00")) +}) + +test("a gateway rest key names an account with @ or slash in it", () => { + const now = at("2026-11-02T12:30:00+08:00") + const account = "team/example@workbuddy.com" + const trace = routingTrace( + [{ + ...routingRefusal("2026-11-02 19:17:02", { id: "provider-member" }), + error: "429", + rest: { by: "resets", key: `workbuddy-ai@${account.toLowerCase()}/deepseek-v4.1-flash`, until: "2026-11-02T19:17:02+08:00" }, + }], + [], + ) + const rows = _internal.routingRefusalRows("", false, now, account, undefined, trace) + expect(rows).toHaveLength(1) + expect(rows[0].providerAccount).toBe(account) + expect(rows[0].restUntil).toBe(Date.parse("2026-11-02T19:17:02+08:00")) + expect(_internal.routingRefusalRows("", false, now, "other@example.com", undefined, trace)).toEqual([]) +}) + +test("a routing entry with neither a rest key nor a named account is left out", () => { + const now = at("2026-11-02T12:30:00+08:00") + const trace = routingTrace([routingRefusal("2026-11-02 19:17:02")], [{ id: "wb-me", provider: "workbuddy-ai" }]) + expect(_internal.routingRefusalRows("", false, now, "me@example.com", undefined, trace)).toEqual([]) +}) + test("other accounts, other models and the other build are left out", () => { const rows = [ row("2026-10-20T19:53:48+08:00", { in: 1_000 }), @@ -226,6 +286,316 @@ test("the parse cache keys the build", () => { } }) +test("a routing trace's failed WorkBuddy attempt pins the vendor reset", () => { + const now = at("2026-11-02T12:30:00+08:00") + const day = localDay(now) + const root = writeLedger([JSON.stringify(row("2026-11-02T02:00:00+08:00", { in: 3_000_000 }))]) + try { + mkdirSync(join(root, "routing")) + writeFileSync(join(root, "routing", `${day}.jsonl`), routingTrace([routingRefusal("2026-11-02 19:17:02")]) + "\n") + const rows = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + const w = _internal.freeWindowOf(rows, "me@example.com", now) + expect(w.amount).toBe(1e8) + expect(w.refused).toBe(true) + expect(w.aside).toBeUndefined() + expect(w.resetsAt).toBe(iso("2026-11-02T19:17:02+08:00")) + const refusal = rows.find((r) => Number(r.status) === 429) + expect(refusal.in).toBeUndefined() + expect(refusal.out).toBeUndefined() + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("a routing trace resets, then the next answered row opens a new window", () => { + const now = at("2026-11-02T20:00:00+08:00") + const day = localDay(now) + const root = writeLedger([ + JSON.stringify(row("2026-11-01T10:00:00+08:00", { in: 3_000_000 })), + JSON.stringify(row("2026-11-02T19:30:00+08:00", { in: 250_000 })), + ]) + try { + mkdirSync(join(root, "routing")) + writeFileSync(join(root, "routing", `${day}.jsonl`), routingTrace([routingRefusal("2026-11-02 19:17:02")]) + "\n") + const w = _internal.freeWindowOf(_internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")), "me@example.com", now) + expect(w.amount).toBe(250_000) + expect(w.refused).toBeUndefined() + expect(w.aside).toBe(true) + expect(w.resetsAt).toBe(iso("2026-11-03T19:30:00+08:00")) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("a routing trace keeps accounts, models and builds apart", () => { + const now = at("2026-11-02T12:30:00+08:00") + const day = localDay(now) + const root = writeLedger([ + JSON.stringify(row("2026-11-02T02:00:00+08:00", { in: 3_000_000 })), + JSON.stringify(cnRow("2026-11-02T02:10:00+08:00", { in: 4_000_000 })), + ]) + try { + mkdirSync(join(root, "routing")) + writeFileSync( + join(root, "routing", `${day}.jsonl`), + [ + routingTrace([routingRefusal("2026-11-02 19:17:02", { id: "wb-other", who: "other@example.com" })], [ + { id: "wb-other", provider: "workbuddy-ai", who: "other@example.com" }, + ]), + routingTrace([routingRefusal("2026-11-02 19:17:02", { model: "glm-5.3" })]), + routingTrace([routingRefusal("2026-11-02 19:17:02", { id: "workbuddy" })], [ + { id: "workbuddy", who: "me@example.com" }, + ]), + ].join("\n") + "\n", + ) + const ai = _internal.freeWindowOf(_internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")), "me@example.com", now) + expect(ai.amount).toBe(3_000_000) + expect(ai.refused).toBeUndefined() + const cn = _internal.freeWindowOf( + _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome"), _internal.CN_ESTIMATED_WINDOWS[0]), + "me@example.com", + now, + _internal.CN_ESTIMATED_WINDOWS[0], + ) + expect(cn.amount).toBe(2e8) + expect(cn.refused).toBe(true) + expect(cn.resetsAt).toBe(iso("2026-11-02T19:17:02+08:00")) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("a routing entry whose id names two accounts is left out", () => { + const now = at("2026-11-02T12:30:00+08:00") + const rows = _internal.routingRefusalRows( + "", + false, + now, + "me@example.com", + undefined, + routingTrace( + [routingRefusal("2026-11-02 19:17:02")], + [ + { id: "wb-me", provider: "workbuddy-ai", who: "me@example.com" }, + { id: "wb-me", provider: "workbuddy-ai", who: "other@example.com" }, + { id: "wb-me", provider: "workbuddy-ai", who: "me@example.com" }, + ], + ), + ) + expect(rows).toEqual([]) +}) + +test("routing traces are read compressed and missing or damaged files fall back", () => { + const now = at("2026-11-02T12:30:00+08:00") + const day = localDay(now) + const root = writeLedger([JSON.stringify(row("2026-11-02T02:00:00+08:00", { in: 3_000_000 }))]) + try { + mkdirSync(join(root, "routing")) + writeFileSync(join(root, "routing", `${day}.jsonl.gz`), gzipSync(Buffer.from(routingTrace([routingRefusal("2026-11-02 19:17:02")]) + "\n"))) + writeFileSync(join(root, "routing", `${localDay(now - 24 * 3600_000)}.jsonl.gz`), Buffer.from("not gzip")) + const rows = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + expect(_internal.freeWindowOf(rows, "me@example.com", now).resetsAt).toBe(iso("2026-11-02T19:17:02+08:00")) + const trace = join(root, "routing", `${day}.jsonl.gz`) + writeFileSync(trace, gzipSync(Buffer.from("{ torn"))) + utimesSync(trace, new Date(), new Date(Date.now() + 5)) + expect(_internal.readRoutingRefusals(trace, true, _internal.FREE_WINDOW_AI)).toEqual([]) + expect(_internal.routingRefusalRows(trace, true, now + 2000, "me@example.com")).toEqual([]) + const fallbackRows = [row("2026-11-02T02:00:00+08:00", { in: 3_000_000 })] + expect(_internal.freeWindowOf(fallbackRows, "me@example.com", now + 2000).resetsAt).toBe( + iso("2026-11-03T02:00:00+08:00"), + ) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("a usage append does not read the routing trace again", () => { + const now = at("2026-11-02T12:30:00+08:00") + const day = localDay(now) + const first = JSON.stringify(row("2026-11-02T02:00:00+08:00", { in: 1 })) + const root = writeLedger([first]) + const routingPath = join(root, "routing", `${day}.jsonl.gz`) + try { + mkdirSync(join(root, "routing")) + writeFileSync(routingPath, gzipSync(Buffer.from(routingTrace([routingRefusal("2026-11-02 19:17:02")]) + "\n"))) + const before = routingReads.count + const firstRows = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + expect(routingReads.count).toBe(before + 1) + expect(_internal.freeWindowOf(firstRows, "me@example.com", now).resetsAt).toBe(iso("2026-11-02T19:17:02+08:00")) + + writeFileSync(join(root, "usage.jsonl"), `${first}\n${JSON.stringify(row("2026-11-02T03:00:00+08:00", { in: 2 }))}\n`) + const secondRows = _internal.freeWindowRows("me@example.com", now + 1000, root, {}, join(root, "nohome")) + expect(routingReads.count).toBe(before + 1) + expect(secondRows.filter((r) => Number(r.status) !== 429).reduce((sum, r) => sum + (r.in ?? 0), 0)).toBe(3) + expect(_internal.freeWindowOf(secondRows, "me@example.com", now + 1000).resetsAt).toBe(iso("2026-11-02T19:17:02+08:00")) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("a routing trace rest names the reset when its error does not", () => { + const root = writeLedger([]) + try { + const path = join(root, "routing.jsonl") + const rows = _internal.routingRefusalRows( + path, + false, + at("2026-11-02T12:30:00+08:00"), + "me@example.com", + _internal.FREE_WINDOW_AI, + routingTrace([{ ...routingRefusal("2026-11-02 19:17:02"), error: "429", rest: { by: "resets", key: "workbuddy-ai@me@example.com/deepseek-v4.1-flash", until: "2026-11-02T19:17:02+08:00" } }]), + ) + expect(rows).toHaveLength(1) + expect(_internal.freeWindowOf([...rows, row("2026-11-02T02:00:00+08:00", { in: 1 })], "me@example.com", at("2026-11-02T12:30:00+08:00")).resetsAt).toBe( + iso("2026-11-02T19:17:02+08:00"), + ) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("a gateway rest reset names a window and other rest reasons do not", () => { + const now = at("2026-11-02T12:30:00+08:00") + for (const by of ["cooldown", "backoff", "quota", "window", "retry-after", "unknown"]) { + const trace = routingTrace( + [{ + ...routingRefusal("2026-11-02 19:17:02"), + error: "429", + rest: { by, key: "workbuddy-ai@me@example.com/deepseek-v4.1-flash", until: "2026-11-02T19:17:02+08:00" }, + }], + ) + expect(_internal.routingRefusalRows("", false, now, "me@example.com", undefined, trace)).toEqual([]) + } + const resets = routingTrace( + [{ + ...routingRefusal("2026-11-02 19:17:02"), + error: "429", + rest: { by: "resets", key: "workbuddy-ai@me@example.com/deepseek-v4.1-flash", until: "2026-11-02T19:17:02+08:00" }, + }], + ) + const rows = _internal.routingRefusalRows("", false, now, "me@example.com", undefined, resets) + expect(rows).toHaveLength(1) + expect(rows[0].restUntil).toBe(at("2026-11-02T19:17:02+08:00")) +}) + +test("a gateway rest key must name the provider and model", () => { + expect(_internal.restIdentity({ key: "other@me@example.com/deepseek-v4.1-flash" }, _internal.FREE_WINDOW_AI)).toBeNull() + expect(_internal.restIdentity({ key: "workbuddy-ai@me@example.com/glm-5.3" }, _internal.FREE_WINDOW_AI)).toBeNull() + expect(_internal.restIdentity({ key: "workbuddy-ai@me@example.com/deepseek-v4.1-flash" }, _internal.FREE_WINDOW_AI)).toEqual({ + account: "me@example.com", + model: "deepseek-v4.1-flash", + }) +}) + +test("rest account comparison is case-insensitive and keeps the caller's spelling", () => { + const now = at("2026-11-02T12:30:00+08:00") + const keyedAccount = "mixed-case@example.com" + const rest = { by: "resets", key: `workbuddy-ai@${keyedAccount}/deepseek-v4.1-flash`, until: "2026-11-02T19:17:02+08:00" } + const refusal = (id, restKey = rest.key) => ({ id, model: "deepseek-v4.1-flash", status: 429, start: "2026-11-02T12:00:01+08:00", error: "reset at 2026-11-02 19:17:02 UTC+8", rest: { ...rest, key: restKey } }) + const trace = routingTrace([ + refusal("workbuddy-ai"), + refusal("unknown"), + refusal("workbuddy-ai", "workbuddy-ai@other@example.com/deepseek-v4.1-flash"), + ], [ + { id: "workbuddy-ai", provider: "workbuddy-ai", who: "Mixed-Case@Example.com" }, + { id: "workbuddy-ai", provider: "workbuddy-ai", who: "MIXED-CASE@example.com" }, + ]) + const rows = _internal.routingRefusalRows("", false, now, "MIXED-CASE@example.com", undefined, trace) + expect(rows.map((r) => r.providerAccount)).toEqual(["Mixed-Case@Example.com", "MIXED-CASE@example.com"]) +}) + +test("a real-shaped WorkBuddy trace is attributed through order and keyed rest", () => { + const now = at("2026-11-02T12:30:00+08:00") + const keyedAccount = "mixed-case@example.com" + const trace = JSON.stringify({ + time: "2026-11-02T12:00:00+08:00", + order: [{ id: "workbuddy-ai", who: "Mixed-Case@Example.com" }], + tries: [{ + id: "workbuddy-ai", + model: "deepseek-v4.1-flash", + status: 429, + start: "2026-11-02T12:00:01+08:00", + error: "429", + rest: { by: "resets", key: `workbuddy-ai@${keyedAccount}/deepseek-v4.1-flash`, until: "2026-11-02T19:17:02+08:00" }, + }], + }) + const rows = _internal.routingRefusalRows("", false, now, "mixed-CASE@example.COM", undefined, trace) + expect(rows).toHaveLength(1) + expect(rows[0].providerAccount).toBe("Mixed-Case@Example.com") +}) + +test("routing refusals outside twice-the-window are ignored", () => { + const now = at("2026-11-02T12:30:00+08:00") + const refusal = (start) => ({ + id: "workbuddy-ai", + model: "deepseek-v4.1-flash", + status: 429, + start, + error: "429", + rest: { by: "resets", key: "{{SECRET_tkvhbn6p}}", until: "2026-11-02T19:17:02+08:00" }, + }) + const trace = JSON.stringify({ order: [{ id: "workbuddy-ai", who: "me@example.com" }], tries: [refusal("2026-10-31T12:29:59+08:00"), refusal("2026-11-02T12:30:01+08:00")] }) + expect(_internal.routingRefusalRows("", false, now, "me@example.com", undefined, trace)).toEqual([]) +}) + +test("only the routing files a window can reach are read", () => { + const now = at("2026-11-02T12:30:00+08:00") + const days = [0, 1, 2].map((offset) => localDay(now - offset * 24 * 3600_000)) + const root = mkdtempSync(join(tmpdir(), "wb-routing-days-")) + try { + mkdirSync(join(root, "routing")) + const other = localDay(now + 24 * 3600_000) + for (const day of [...days, other, localDay(now - 3 * 24 * 3600_000)]) writeFileSync(join(root, "routing", `${day}.jsonl`), "{}\n") + expect(_internal.freeWindowRouting(root, now).map((path) => basename(path))).toEqual(days.map((day) => `${day}.jsonl`)) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("routing filenames follow the local day and read both forms for one day", () => { + const now = at("2026-11-02T12:30:00+08:00") + const day = localDay(now) + const older = new Date(now - 3 * 24 * 3600_000) + const oldDay = localDay(older) + const root = writeLedger([JSON.stringify(row(new Date(now - 3600_000).toISOString(), { in: 1 }))]) + try { + mkdirSync(join(root, "routing")) + for (const name of [`${day}.jsonl`, `${day}.jsonl.gz`, `${oldDay}.jsonl`]) { + const text = routingTrace([routingRefusal("2026-11-02 19:17:02")]) + "\n" + writeFileSync(join(root, "routing", name), name.endsWith(".gz") ? gzipSync(Buffer.from(text)) : text) + } + const paths = _internal.freeWindowRouting(root, now) + expect(paths.map((path) => basename(path))).toEqual([`${day}.jsonl`, `${day}.jsonl.gz`]) + const rows = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + expect(rows.filter((r) => Number(r.status) === 429)).toHaveLength(2) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("routing append updates one cache entry and stale days are dropped", () => { + const now = at("2026-11-02T12:30:00+08:00") + const day = localDay(now) + const root = writeLedger([JSON.stringify(row(new Date(now - 3600_000).toISOString(), { in: 1 }))]) + const routing = join(root, "routing") + const route = join(routing, `${day}.jsonl`) + try { + mkdirSync(routing) + for (let i = 0; i < 50; i++) { + appendFileSync(route, routingTrace([routingRefusal("2026-11-02 19:17:02")]) + "\n") + const rows = _internal.freeWindowRows("me@example.com", now + i, root, {}, join(root, "nohome")) + expect(rows.filter((r) => Number(r.status) === 429)).toHaveLength(i + 1) + expect(routingParsed.size).toBe(1) + } + const future = now + 3 * 24 * 3600_000 + writeFileSync(join(routing, `${localDay(future)}.jsonl`), "{}\n") + _internal.freeWindowRows("me@example.com", future, root, {}, join(root, "nohome")) + expect([...routingParsed.values()].every((held) => basename(held.path) === `${localDay(future)}.jsonl`)).toBe(true) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + // a refusal carries no tokens: it neither counts nor opens a window test("a 429 neither counts nor opens a window", () => { diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index d60991c..8ef8171 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -10,10 +10,10 @@ // those of its current desktop app (see SITES' app, cli and appName). import { createHash, randomBytes } from "node:crypto" -import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs" +import { closeSync, openSync, readFileSync, readdirSync, readSync, statSync } from "node:fs" import { homedir } from "node:os" -import { isAbsolute, join } from "node:path" -import { gzipSync } from "node:zlib" +import { dirname, isAbsolute, join } from "node:path" +import { gzipSync, gunzipSync } from "node:zlib" const POLL_MS = 1000 const SIGN_IN_MS = 5 * 60 * 1000 @@ -2388,6 +2388,19 @@ function windowReset(text) { return Date.UTC(+at[1], +at[2] - 1, +at[3], +at[4], +at[5], +at[6]) - off * 60000 } +// resetOf is the vendor reset a row names, whether its words spell it out or +// a routing trace handed it as the instant itself. +function resetOf(row) { + const said = windowReset(row?.err) + if (Number.isFinite(said)) return said + const until = Number(row?.restUntil) + return Number.isFinite(until) ? until : NaN +} + +function windowModel(model, win) { + return typeof model === "string" && (model.startsWith(win.model) || win.aliases.some((alias) => model.startsWith(alias))) +} + // freeWindowOf is the window account is in now, from rows (magpie's usage // records), or null when it has lapsed — the next request opens a new one. // now is passed in so the reading is testable; win is the build's window @@ -2404,7 +2417,7 @@ function freeWindowOf(rows, account, now = Date.now(), win = FREE_WINDOW_AI) { r?.provider === win.provider && r.providerAccount === account && typeof r.model === "string" && - r.model.startsWith(win.model) && + windowModel(r.model, win) && r.t, ) if (!mine.length) return null @@ -2423,7 +2436,7 @@ function freeWindowOf(rows, account, now = Date.now(), win = FREE_WINDOW_AI) { const edges = [] for (const r of mine) { if (Number(r.status) !== 429) continue - const t = windowReset(r.err) + const t = resetOf(r) if (Number.isFinite(t)) edges.push(t) } edges.sort((a, b) => a - b) @@ -2500,7 +2513,7 @@ function freeWindowOf(rows, account, now = Date.now(), win = FREE_WINDOW_AI) { let live = null for (const r of mine) { if (Number(r.status) !== 429) continue - const t = windowReset(r.err) + const t = resetOf(r) if (!Number.isFinite(t) || t <= now || t <= start) continue if (live === null || t > live) live = t } @@ -2536,6 +2549,13 @@ function tokensShort(n) { // own now. let ledgerParsed = null +// routingParsed is the WorkBuddy refusals read from a routing file, keyed by +// that file, provider and model. The +// usage ledger beside it changes on every request; the routing files need not +// be read — least of all the gzip days — merely because usage did. +const routingParsed = new Map() +const routingReads = { count: 0 } + // ledgerBad is the number of whole lines the ledger last had that could // not be decoded, and the file it was read from, so that a ledger read // once and read again is complained about once, not on every panel open. @@ -2558,6 +2578,144 @@ function freeWindowLedger(cwd = process.cwd(), env = process.env, home = homedir return dirs.map((d) => join(d, "usage.jsonl")) } +// freeWindowRouting is the trace files a window can need, from the same root +// as the ledger. Magpie writes one plain file a day and gzips the days before, +// so only the local dates a 24h window and its lead can reach are named: +// three, from the day two days back through today. +function freeWindowRouting(base, now = Date.now()) { + const days = new Set() + for (let at = new Date(now); days.size < 3; at.setDate(at.getDate() - 1)) { + days.add(`${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, "0")}-${String(at.getDate()).padStart(2, "0")}`) + } + let names + try { + names = readdirSync(join(base, "routing")) + } catch { + return [] + } + const found = [] + for (const day of days) { + for (const name of [`${day}.jsonl`, `${day}.jsonl.gz`]) if (names.includes(name)) found.push(join(base, "routing", name)) + } + return found +} + +// restIdentity reads the gateway rest key's exact shape, +// workbuddy@/: the provider must be this build's whole name, +// the model starts at the last slash, and the account is everything before it, +// so an account may itself contain @ or /. +function restIdentity(rest, win) { + if (typeof rest?.key !== "string") return null + if (!rest.key.startsWith(win.provider + "@")) return null + const tail = rest.key.slice(win.provider.length + 1) + const modelAt = tail.lastIndexOf("/") + if (modelAt <= 0 || modelAt === tail.length - 1) return null + const model = tail.slice(modelAt + 1) + return windowModel(model, win) ? { account: tail.slice(0, modelAt), model } : null +} + +// routingRefusals turns a routing trace's failed WorkBuddy attempts into the +// same shape as a usage row, so freeWindowOf can read the vendor reset an +// ordinary usage read never saw. An attempt is named either by order[]'s who +// or, when the gateway rest carries a reset, by rest.key's account and model; +// keyed accounts are compared case-insensitively, and an order's spelling is +// kept. Where both name different accounts the attempt is left out rather +// than guessed onto one of them. +function routingRefusals(win, text) { + const rows = [] + for (const line of text.split("\n")) { + if (!/"status"\s*:\s*429/.test(line)) continue + if (!line.includes(win.provider)) continue + let event + try { + event = JSON.parse(line) + } catch { + continue + } + const orders = Array.isArray(event?.order) ? event.order : [] + const named = new Map() + const ambiguous = new Set() + for (const order of orders) { + if (order?.provider !== undefined && order.provider !== win.provider) continue + if (typeof order.id !== "string" || typeof order.who !== "string") continue + if (ambiguous.has(order.id)) continue + const was = named.get(order.id) + if (was === undefined) named.set(order.id, order.who) + else if (was.toLowerCase() !== order.who.toLowerCase()) { + named.delete(order.id) + ambiguous.add(order.id) + } + } + for (const attempt of Array.isArray(event?.tries) ? event.tries : []) { + if (Number(attempt?.status) !== 429) continue + if (attempt.provider !== undefined && attempt.provider !== win.provider) continue + if (!windowModel(attempt.model, win)) continue + const error = typeof attempt.error === "string" ? attempt.error : typeof attempt.error?.message === "string" ? attempt.error.message : "" + const keyed = restIdentity(attempt.rest, win) + let reset = windowReset(error) + let restUntil = NaN + if (!Number.isFinite(reset)) { + restUntil = keyed && attempt.rest.by === "resets" ? Date.parse(typeof attempt.rest.until === "string" ? attempt.rest.until : "") : NaN + if (Number.isFinite(restUntil)) reset = restUntil + } + if (!Number.isFinite(reset)) continue + const ordered = named.get(String(attempt.id ?? "")) + if (ordered !== undefined && keyed && ordered.toLowerCase() !== keyed.account.toLowerCase()) continue + const account = ordered ?? keyed?.account + if (typeof account !== "string" || !account) continue + const keyedOnly = ordered === undefined + rows.push({ + provider: win.provider, + providerAccount: account, + model: attempt.model, + t: attempt.start ?? event?.time, + status: 429, + err: error, + ...(keyedOnly ? { keyedOnly: true } : {}), + ...(Number.isFinite(windowReset(error)) ? {} : { restUntil }), + }) + } + } + return rows +} + +function readRoutingRefusals(path, compressed, win) { + let st + try { + st = statSync(path) + } catch { + return [] + } + const key = `${path}|${win.provider}|${win.model}` + const held = routingParsed.get(key) + const fingerprint = `${st.mtimeMs}:${st.size}` + if (held?.fingerprint === fingerprint) return held.rows + routingReads.count++ + let text + try { + text = compressed ? gunzipSync(readFileSync(path)).toString("utf8") : readFileSync(path, "utf8") + } catch { + routingParsed.set(key, { key, path, fingerprint, rows: [] }) + return [] + } + const rows = routingRefusals(win, text) + routingParsed.set(key, { key, path, fingerprint, rows }) + return rows +} + +function routingRefusalRows(path, compressed, now, account, win = FREE_WINDOW_AI, text) { + const parsed = text === undefined ? readRoutingRefusals(path, compressed, win) : routingRefusals(win, text) + const rows = [] + const oldest = now - 2 * FREE_WINDOW_SPAN + for (const attempt of parsed) { + const t = Date.parse(attempt.t) + if (!Number.isFinite(t) || t < oldest || t > now) continue + if (attempt.providerAccount.toLowerCase() !== account.toLowerCase()) continue + rows.push({ ...attempt, providerAccount: attempt.keyedOnly ? account : attempt.providerAccount }) + } + return rows +} + // freeWindowRows reads magpie's usage ledger for account, oldest row first. // null when no ledger can be read: the window is then left unknown rather // than guessed. @@ -2594,22 +2752,30 @@ function freeWindowRows(account, now = Date.now(), cwd = process.cwd(), env = pr // answer for each other (the same phone number can be signed in to both), // and two windows of one build count different models const key = file + "|" + win.provider + "|" + win.model + "|" + account - if (ledgerParsed?.key === key) return ledgerParsed.rows let got - try { - got = readLedgerTail(path, st, now, undefined, account, win) - } catch { - return null + if (ledgerParsed?.key === key) { + got = ledgerParsed + } else { + try { + got = readLedgerTail(path, st, now, undefined, account, win) + } catch { + return null + } + if (got.bad && ledgerBad.key !== file) { + ledgerBad = { key: file, count: got.bad } + console.error( + `workbuddy: ${got.bad} whole line${got.bad === 1 ? "" : "s"} of ${path} could not be decoded ` + + `(not the last line, so not a write in progress); the free-token window may read short`, + ) + } + ledgerParsed = { key, rows: got.rows } } - if (got.bad && ledgerBad.key !== file) { - ledgerBad = { key: file, count: got.bad } - console.error( - `workbuddy: ${got.bad} whole line${got.bad === 1 ? "" : "s"} of ${path} could not be decoded ` + - `(not the last line, so not a write in progress); the free-token window may read short`, - ) - } - ledgerParsed = { key, rows: got.rows } - return got.rows + const routes = freeWindowRouting(dirname(path), now) + const current = new Set(routes) + for (const [key, held] of routingParsed) if (!current.has(held.path)) routingParsed.delete(key) + const refused = routes.flatMap((route) => routingRefusalRows(route, route.endsWith(".gz"), now, account, win)) + const rows = [...got.rows, ...refused].sort((a, b) => Date.parse(a.t) - Date.parse(b.t)) + return rows } // LEDGER_T is where a row's time sits: "t" is among the first keys @@ -2665,7 +2831,7 @@ function ofAccount(row, account, win = FREE_WINDOW_AI) { row?.provider === win.provider && row.providerAccount === account && typeof row.model === "string" && - row.model.startsWith(win.model) + windowModel(row.model, win) ) } @@ -2813,7 +2979,7 @@ function pinned(rows, account) { // the same job and keeps the latest. let denied = null for (let i = rows.length - 1; i >= 0; i--) { - const reset = Number(rows[i]?.status) === 429 ? windowReset(rows[i].err) : NaN + const reset = Number(rows[i]?.status) === 429 ? resetOf(rows[i]) : NaN if (Number.isFinite(reset)) denied = reset } if (denied !== null) return denied - FREE_WINDOW_LEAD @@ -2869,7 +3035,7 @@ function pinning() { const status = Number(row?.status) if (status === 429) { if (denied === null) { - const reset = windowReset(row.err) + const reset = resetOf(row) if (Number.isFinite(reset)) denied = reset } return 0 @@ -4241,4 +4407,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { HIDE_DSH, hideDsh, dshHidden, planCodes, listedExtra, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, SMALL_BUDGET, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, readLedgerTail, pinned, pinning, rowTime, rowAccount, ofAccount, windowOffset, windowReset, CN_ESTIMATED_WINDOWS, FREE_WINDOW_AI, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } +export const _internal = { HIDE_DSH, hideDsh, dshHidden, planCodes, listedExtra, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, SMALL_BUDGET, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, freeWindowRouting, routingRefusalRows, readRoutingRefusals, readLedgerTail, pinned, pinning, rowTime, rowAccount, ofAccount, windowOffset, windowReset, CN_ESTIMATED_WINDOWS, FREE_WINDOW_AI, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM, routingReads, routingParsed, restIdentity } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 0f58383..ad42824 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.2.28", + "version": "0.2.29", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./opencode.mjs",