diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index b57f6e3..2635a83 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -289,6 +289,79 @@ credits are read from the enterprise meter page reads: the cycle's credits used of its limit, and when the cycle resets (magpie #1904). +## The free model's daily window (WorkBuddy AI) + +The credits above are not the only limit. `deepseek-v4.1-flash` is served at +`x0.00` and costs the plan nothing, yet WorkBuddy AI refuses it long before +160 credits are touched: + +``` +429 usage exceeds frequency limit, but don't worry, your usage will reset at +2026-10-20 19:47:41 UTC+8, alternatively, you can switch to the other models +to continue using it. +``` + +That is a token allowance of its own — per account, per 24 hours, about 1e8 +tokens, counted as prompt + cache-read + completion. Nothing the vendor +answers with reports it, so the plugin rebuilds the current window from +magpie's `usage.jsonl` and gives it to the card as **Free model tokens** +beside **Credits**. `quota alert` and `magpie quota` show it too; before, +the card read 0% on an account that was already refused. + +What is measured, and what is easy to read wrongly: + +- **`cache_read` counts.** Prompt and completion alone are 20× smaller and + never approach the cap, so a window read that way looks empty while full. +- **The window is fixed, not sliding.** It runs 24 hours from the first + request answered after the previous window ended, not from the reset + instant; a gap between the two means the new window starts later. +- **`deepseek-v4.1-flash-sg` shares the window.** It is the paid id of the + same model (`ModelRateLimitCap` in the product config), not a second + allowance — switching to it continues the same window, at `x0.03`. +- **1e8 is an estimate within 0.2%.** The largest value seen to still be + answered is 100,183,315, and the next request is refused, so it cannot be + probed higher. +- **A refusal is exact, and the sum is not.** The ledger is this machine's + only: one window was refused at 92,792,962 because the rest of that + account's spending happened on another machine, which read as 93%. So a + 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. +- **The card names both ids**, `deepseek-v4.1-flash` and + `deepseek-v4.1-flash-sg`: magpie matches a window's models by exact id + (only an `@size` suffix folds into the bare id), so one alone would leave + the other unrestricted. +- **The ledger is read in magpie's own folder** (`appdir.Config()`: the + portable data folder, `$XDG_CONFIG_HOME/magpie` when that is set (an + absolute path, as `appdir.rooted` has it), or `~/.config/magpie`), from its + end backwards — a heavy ledger runs to hundreds of MB. + - The window is a chain, so where it now began depends on every window + before it: read a slice of the ledger that starts mid-chain and every + window after it is shifted (4% on an account two hours from its cap, or + 100% on one still served). The read therefore goes back until it reaches + an edge this account's own rows spell out — a refusal whose reset can be + read, or a gap of a day between two of its answered rows — plus a day + below that, and with neither it reads to the file's start, where there is + no earlier window to be shifted by. + - Nothing bounds that by age, so two things keep a heavy ledger cheap: a + line's time is read before the line is decoded, so a line under the edge + (of any provider or account) ends the read at once; and a read past 24h + with no answered free-model row of this account stops, since the window + has lapsed and nothing would be reported. Both bounds leave out a line + a client reported (`"source":"reported"`, #1874): magpie appends those + dated where the client's call happened, so a backfilled row says nothing + about where the file has got to. + - `providerAccount` is the account's label. Two accounts sharing a label + get its slot added (`pluginLabels`), the label no longer matches what + their rows were written under, and the card reports no free window. +- **The offset comes from the refusal's words** (`UTC+8`, `GMT-5`, + `UTC+05:30`). A reset whose offset cannot be read is no edge at all, + rather than +08:00 guessed. + +A window that has lapsed reports nothing rather than 0%: nothing is +exhausted, and the next request opens a fresh one. The China build is not +covered; its limit has not been measured. + ## When free models work but a credit model does not Check the failing account and model separately before concluding that the diff --git a/packages/workbuddy/freewindow.test.mjs b/packages/workbuddy/freewindow.test.mjs new file mode 100644 index 0000000..7449c02 --- /dev/null +++ b/packages/workbuddy/freewindow.test.mjs @@ -0,0 +1,558 @@ +// The free model's daily token window: what WorkBuddy AI refuses a chat on +// long before a free plan's credits are spent, and which the credit meter +// does not show. Every figure here is one measured on a real account; see +// 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 { homedir } from "node:os" +import { join } from "node:path" + +let _internal +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")) +}) + +// a row of magpie's usage ledger (usage.Record), as the plugin reads it +// pad stands in for a real row's request fields (conversation, client, price, +// error text), so a row can be made as fat as a ledger's own and a handful of +// them can outgrow one 64 KiB chunk, as they do in a live ledger +const row = (t, { status = 200, in: inp = 0, cache = 0, out = 0, err = "", model = "deepseek-v4.1-flash", account = "me@example.com", provider = "workbuddy-ai", pad = "" } = {}) => ({ + provider, + providerAccount: account, + model, + t, + status, + in: inp, + cache_read: cache, + out, + err, + ...(pad ? { pad } : {}), +}) +const iso = (s) => new Date(s).toISOString() +const at = (s) => Date.parse(s) + +// enough padding to make a row a live ledger's size +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 " + +// 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`, { + status: 429, + account, + err: `WorkBuddy AI: usage exceeds frequency limit, but don't worry, your usage will reset at ${reset} UTC+8, alternatively, you can switch to the other models to continue using it.`, + }) + +test("a window counts in + cache_read + out", () => { + const rows = [row("2026-10-20T19:53:48+08:00", { in: 1_000_000, cache: 4_000_000, out: 100_000 }), row("2026-10-20T20:00:00+08:00", { in: 500_000, cache: 2_000_000 })] + const w = _internal.freeWindowOf(rows, "me@example.com", at("2026-10-20T21:00:00+08:00")) + expect(w.amount).toBe(7_600_000) + expect(w.used).toBeCloseTo(7.6, 6) + expect(w.resetsAt).toBe(iso("2026-10-21T19:53:48+08:00")) + expect(w.span).toBe(86400) + expect(w.limit).toBe(1e8) + expect(w.unit).toBe("tokens") + expect(w.display).toBe("7.6M / 100M") + expect(w.models).toEqual(["deepseek-v4.1-flash", "deepseek-v4.1-flash-sg"]) +}) + +// reading in + out alone is 20x too small and never reaches a cap, so a +// window read that way looks empty while it is full +test("cache_read alone can fill a window", () => { + const w = _internal.freeWindowOf([row("2026-10-20T19:53:48+08:00", { in: 200, cache: 99_000_000, out: 300 })], "me@example.com", at("2026-10-20T21:00:00+08:00")) + expect(w.used).toBeGreaterThan(98) + expect(w.used).toBeLessThanOrEqual(100) +}) + +// the reset a refusal names is the old window's end; the new one starts at +// the next request, which a real account made 68 minutes later +test("a new window opens at the next request, not at the reset instant", () => { + const rows = [ + row("2026-10-16T15:40:03+08:00", { in: 60_000_000 }), + row("2026-10-17T08:00:00+08:00", { in: 40_000_000 }), + refusal("2026-10-17 08:00:13"), + row("2026-10-17T09:08:00+08:00", { in: 1_000 }), + ] + const w = _internal.freeWindowOf(rows, "me@example.com", at("2026-10-17T10:00:00+08:00")) + expect(w.resetsAt).toBe(iso("2026-10-18T09:08:00+08:00")) + expect(w.amount).toBe(1_000) +}) + +// a window never refused still ends 24h after its first request +test("an unrefused window lapses 24h after its first request", () => { + const rows = [row("2026-10-19T19:52:24+08:00", { in: 90_000_000 }), row("2026-10-19T23:00:00+08:00", { in: 2_000_000 })] + expect(_internal.freeWindowOf(rows, "me@example.com", at("2026-10-20T19:00:00+08:00")).amount).toBe(92_000_000) + // lapsed: nothing is exhausted, so no window is reported + expect(_internal.freeWindowOf(rows, "me@example.com", at("2026-10-20T20:00:00+08:00"))).toBeNull() +}) + +// the paid id draws on the same window, so its rows are in this one +test("-sg counts in the same window as the free id", () => { + const rows = [row("2026-10-20T19:53:48+08:00", { in: 50_000_000 }), row("2026-10-20T20:00:00+08:00", { in: 10_000, model: "deepseek-v4.1-flash-sg" })] + const w = _internal.freeWindowOf(rows, "me@example.com", at("2026-10-20T21:00:00+08:00")) + expect(w.amount).toBe(50_010_000) + expect(w.models).toEqual(["deepseek-v4.1-flash", "deepseek-v4.1-flash-sg"]) +}) + +test("other accounts, other models and the China build are left out", () => { + const rows = [ + row("2026-10-20T19:53:48+08:00", { in: 1_000 }), + row("2026-10-20T19:54:00+08:00", { in: 9_000_000, account: "other@example.com" }), + row("2026-10-20T19:55:00+08:00", { in: 9_000_000, model: "glm-5.3-flash" }), + row("2026-10-20T19:56:00+08:00", { in: 9_000_000, model: "kimi-k2.6" }), + row("2026-10-20T19:57:00+08:00", { in: 9_000_000, provider: "workbuddy" }), + ] + expect(_internal.freeWindowOf(rows, "me@example.com", at("2026-10-20T21:00:00+08:00")).amount).toBe(1_000) +}) + +// a refusal carries no tokens: it neither counts nor opens a window +test("a 429 neither counts nor opens a window", () => { + const rows = [row("2026-10-20T19:53:48+08:00", { in: 100 }), row("2026-10-20T22:00:00+08:00", { status: 429, in: 5_000, err: "429 usage exceeds frequency limit" })] + const w = _internal.freeWindowOf(rows, "me@example.com", at("2026-10-20T23:00:00+08:00")) + expect(w.amount).toBe(100) + expect(w.resetsAt).toBe(iso("2026-10-21T19:53:48+08:00")) +}) + +// a refusal with no readable reset time is no edge; the 24h span still ends +// the window +test("a refusal that names no reset falls back to the 24h span", () => { + const rows = [ + row("2026-10-20T10:00:00+08:00", { in: 99_000_000 }), + row("2026-10-20T12:00:00+08:00", { status: 429, err: "WorkBuddy AI: usage exceeds frequency limit" }), + row("2026-10-21T11:00:00+08:00", { in: 1_000 }), + ] + const w = _internal.freeWindowOf(rows, "me@example.com", at("2026-10-21T12:00:00+08:00")) + expect(w.resetsAt).toBe(iso("2026-10-22T11:00:00+08:00")) + expect(w.amount).toBe(1_000) +}) + +test("nothing to read yields no window, not a made-up one", () => { + expect(_internal.freeWindowOf([], "me@example.com")).toBeNull() + expect(_internal.freeWindowOf(null, "me@example.com")).toBeNull() + expect(_internal.freeWindowOf([row("2026-10-20T19:53:48+08:00")], "nobody@example.com")).toBeNull() + expect(_internal.freeWindowOf([row("2026-10-20T19:53:48+08:00", { status: 429, err: "429 usage exceeds frequency limit" })], "me@example.com")).toBeNull() +}) + +test("the card reads a token count, not a credits count", () => { + expect(_internal.tokensShort(99_971_831)).toBe("100.0M") + expect(_internal.tokensShort(11_950_000)).toBe("11.9M") + expect(_internal.tokensShort(812_400)).toBe("812k") + expect(_internal.tokensShort(6)).toBe("6") +}) + +test("no ledger means no window rather than a guess", () => { + // HOME is a temp dir in tests and no folder it reads holds a ledger + expect(_internal.freeWindowRows("me@example.com", Date.now(), join(homedir(), "magpie-test-nowhere"), {}, homedir())).toBeNull() +}) + +// --- the review's points, each red on 33ca87f8 ------------------------- + +// point 1: an account refused under the cap read as 93% because the rest of +// its spending was on another machine. The refusal is the one exact signal +// there is: a 429 whose named reset is still ahead makes the window full. +test("an account refused under the cap reads full, not 93%", () => { + const rows = [ + row("2026-10-18T19:47:00+08:00", { in: 62_000_000, cache: 30_000_000, out: 700_000 }), + row("2026-10-18T19:52:00+08:00", { in: 92_962, model: "deepseek-v4.1-flash-sg" }), + row("2026-10-18T19:52:04+08:00", { status: 429, err: `${TIMEOUT_BEFORE_RESET}2026-10-19 19:52:24 UTC+8, alternatively, you can switch to the other models to continue using it.` }), + ] + const w = _internal.freeWindowOf(rows, "me@example.com", at("2026-10-18T23:00:00+08:00")) + expect(w.amount).toBe(1e8) // the rows sum to 92,792,962 + expect(w.used).toBe(100) + expect(w.display).toBe("100.0M / 100M") + expect(w.resetsAt).toBe(iso("2026-10-19T19:52:24+08:00")) + expect(w.refused).toBe(true) +}) + +// the refusal belongs to its window: once its reset passes, the sum reads +test("a refusal whose reset has passed does not hold the next window full", () => { + const rows = [ + row("2026-10-18T19:47:00+08:00", { in: 92_000_000 }), + row("2026-10-18T19:52:04+08:00", { status: 429, err: `${TIMEOUT_BEFORE_RESET}2026-10-19 19:52:24 UTC+8, alternatively, you can switch to the other models to continue using it.` }), + row("2026-10-19T20:00:00+08:00", { in: 1_000 }), + ] + const w = _internal.freeWindowOf(rows, "me@example.com", at("2026-10-19T21:00:00+08:00")) + expect(w.amount).toBe(1_000) + expect(w.refused).toBeUndefined() +}) + +// point 6: the offset is read from the refusal, and one that cannot be read +// is no edge at all rather than +08:00 +test("the reset's offset is read from the text", () => { + expect(_internal.windowOffset("reset at 2026-10-20 19:47:41 UTC+8")).toBe(480) + expect(_internal.windowOffset("reset at 2026-10-20 19:47:41 UTC+08:00")).toBe(480) + expect(_internal.windowOffset("reset at 2026-10-20 19:47:41 GMT-5")).toBe(-300) + expect(_internal.windowOffset("reset at 2026-10-20 19:47:41 UTC+05:30")).toBe(330) + expect(_internal.windowOffset("reset at 2026-10-20 19:47:41")).toBeNull() + expect(_internal.windowReset("reset at 2026-10-20 19:47:41 UTC+8")).toBe(Date.parse("2026-10-20T19:47:41+08:00")) + expect(Number.isNaN(_internal.windowReset("reset at 2026-10-20 19:47:41"))).toBe(true) +}) + +// point 3: magpie keeps usage.jsonl in appdir.Config(), which is the folder +// the plugin host runs in — portable, or $XDG_CONFIG_HOME/magpie — and only +// ~/.config/magpie otherwise +test("the ledger is found through $XDG_CONFIG_HOME", () => { + const root = mkdtempSync(join(tmpdir(), "wb-xdg-")) + try { + const home = join(root, "home") + const xdg = join(root, "xdg") + mkdirSync(join(home, ".config", "magpie"), { recursive: true }) + mkdirSync(join(xdg, "magpie"), { recursive: true }) + writeFileSync(join(home, ".config", "magpie", "usage.jsonl"), JSON.stringify(row("2026-10-01T10:00:00+08:00", { in: 1 })) + "\n") + writeFileSync(join(xdg, "magpie", "usage.jsonl"), JSON.stringify(row("2026-10-20T10:00:00+08:00", { in: 5_000_000 })) + "\n") + const rows = _internal.freeWindowRows("me@example.com", at("2026-10-20T12:00:00+08:00"), join(root, "elsewhere"), { XDG_CONFIG_HOME: xdg }, home) + expect(rows.map((r) => r.in)).toEqual([5_000_000]) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("the ledger is found through the folder the host runs in", () => { + const root = mkdtempSync(join(tmpdir(), "wb-cwd-")) + try { + writeFileSync(join(root, "usage.jsonl"), JSON.stringify(row("2026-10-20T10:00:00+08:00", { in: 7_000_000 })) + "\n") + const rows = _internal.freeWindowRows("me@example.com", at("2026-10-20T12:00:00+08:00"), root, {}, join(root, "nohome")) + expect(rows.map((r) => r.in)).toEqual([7_000_000]) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +// point 4: a heavy ledger runs to hundreds of MB, so the read starts at its +// end. Where it stops is the chain's business (see the probes below); with no +// edge in reach it goes back to an edge it can stand on, or to the file's end. +test("the read starts at the file's end", () => { + const root = mkdtempSync(join(tmpdir(), "wb-tail-")) + try { + const now = at("2026-10-20T20:00:00+08:00") + const lines = [] + for (let i = 0; i < 3000; i++) lines.push(JSON.stringify(row(new Date(now - (2999 - i) * 3600_000).toISOString(), { in: i === 2999 ? 9_000_000 : 1 }))) + lines.push(JSON.stringify({ ...row(new Date(now).toISOString(), { in: 4 }), provider: "zcode" })) + writeFileSync(join(root, "usage.jsonl"), lines.join("\n") + "\n" + '{"provider":"workbuddy-ai","t":"2026-10-20T') + const rows = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + expect(rows.every((r) => r.provider === "workbuddy-ai")).toBe(true) + expect(rows.at(-1).in).toBe(9_000_000) // the newest row, and never the torn one + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +// --- the next round: the read must stop on a pinned edge, not on an age -- + +// writeLedger puts rows into a fresh folder's usage.jsonl, one JSON line +// each, the last one whole — unless torn asks for a call still being written +function writeLedger(lines, torn = false) { + const root = mkdtempSync(join(tmpdir(), "wb-window-")) + writeFileSync(join(root, "usage.jsonl"), lines.join("\n") + "\n" + (torn ? '{"provider":"workbuddy-ai","t":"2026-10-' : "")) + return root +} + +// The window is a chain: it starts at the first request answered after the +// previous one ended, so where the window now began depends on every window +// before it. A read that stops after 48 hours hands freeWindowOf a first row +// that is usually in the middle of a window, and every window after it is +// shifted — the review's probe read 4% two hours before the account is +// refused. Two things stand at an edge exactly, and the read stops for both: +// a refusal whose reset can be read, and a gap of a day between two of this +// account's answered rows. +const AN_HOUR = 3600_000 +const A_DAY = 86_400_000 +// spread is rows served every hour from start to now, 4M each +function spread(start, now) { + const rows = [] + for (let t = start; t <= now; t += AN_HOUR) rows.push(row(new Date(t).toISOString(), { cache: 4_000_000 })) + return rows +} +// a ledger holding those rows, padded to a live ledger's row size, then +// another provider's 2000 rows after them, so this account's rows sit +// further back than one 64 KiB chunk and the 48h cutoff falls between them +function spreadLedger(rows, now) { + const lines = rows.map((r) => JSON.stringify({ ...r, pad: FAT })) + for (let i = 0; i < 2000; i++) lines.push(JSON.stringify(row(new Date(now - 3599_000 + i).toISOString(), { in: 1, provider: "zcode" }))) + return writeLedger(lines) +} + +// a day of rows, and the account served every hour after them: the window is +// whatever the ledger's own chain makes of it, and the tail alone makes +// something else +test("a day of rows pins the chain where the whole ledger does", () => { + const now = at("2026-10-20T20:00:00+08:00") + // served hourly for a week before, then a gap of 5h, then hourly + const rows = spread(now - 7 * A_DAY, now - 5 * AN_HOUR).concat(spread(now - 1 * AN_HOUR, now)) + const root = spreadLedger(rows, now) + try { + const whole = _internal.freeWindowOf(rows, "me@example.com", now) + const read = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + // the read goes past the 48h tail to the day before where the gap lets + // the chain be read: the tail alone holds 41 of these rows + expect(read.length).toBeGreaterThan(41) + const w = _internal.freeWindowOf(read, "me@example.com", now) + expect(w.amount).toBe(whole.amount) + expect(w.resetsAt).toBe(whole.resetsAt) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +// with a refusal to stand at, the chain is anchored exactly: the window +// opens at the first request answered after the reset it names +test("a refusal the read reaches pins the window exactly", () => { + const now = at("2026-10-22T12:00:00+08:00") + const rows = spread(now - 70 * AN_HOUR, now) + // the window the 70h row opened was refused once its day ran out + const reset = now - 70 * AN_HOUR + A_DAY + const atReset = `${new Date(reset).toISOString().slice(0, 19).replace("T", " ")} UTC+0` + const refused = [ + ...rows, + row(new Date(now - 46 * AN_HOUR + 60_000).toISOString(), { status: 429, err: `${TIMEOUT_BEFORE_RESET}${atReset}, alternatively, you can switch to the other models to continue using it.` }), + ].sort((a, b) => Date.parse(a.t) - Date.parse(b.t)) + const root = spreadLedger(refused, now) + try { + const w = _internal.freeWindowOf(_internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")), "me@example.com", now) + // the refusal names the window's end; the window holding now opened on + // the span after it, and the rows read say the same as all of them + const whole = _internal.freeWindowOf(refused, "me@example.com", now) + expect(whole.amount).toBe(23 * 4_000_000) + expect(w.amount).toBe(whole.amount) + expect(w.resetsAt).toBe(whole.resetsAt) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +// a gap of a day or more ends every window before it, so the row after the +// gap opens one: the second thing that pins the chain without a refusal +test("a gap of a day or more pins the chain too", () => { + const now = at("2026-10-22T12:00:00+08:00") + // served hourly until 50h ago, then nothing for 30h, then hourly since + const rows = spread(now - 100 * AN_HOUR, now - 50 * AN_HOUR).concat(spread(now - 20 * AN_HOUR, now)) + const root = spreadLedger(rows, now) + try { + const whole = _internal.freeWindowOf(rows, "me@example.com", now) + // the idle ended every window before it, so the window now is the one the + // first row after it opened, 20h ago + expect(whole.amount).toBe(21 * 4_000_000) + expect(whole.resetsAt).toBe(iso(new Date(now - 20 * AN_HOUR + A_DAY))) + + const read = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + const w = _internal.freeWindowOf(read, "me@example.com", now) + // the read stops a day before the row after the idle: the 21 rows since + // it, and the 25 of the day before the gap — not the 100 before them + expect(read.length).toBe(46) + expect(w.amount).toBe(whole.amount) + expect(w.resetsAt).toBe(whole.resetsAt) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +// The review's probe, unchanged: hourly rows for 70h, 4M of cache_read each, +// six days after the last of them is 2000 rows of another provider, and no +// refusal anywhere. With no edge to stand at there is no window chain to be +// read, so the whole ledger and the read agree — and a run of use with no gap +// and no refusal is exactly that: there is no window edge in it to find. +test("the review's probe: a run with no edge reads as the whole ledger", () => { + const now = at("2026-10-22T12:00:00+08:00") + // rows from two hours before the file's other rows, so the tail read alone + // would still open the window mid-run + const rows = spread(now - 70 * AN_HOUR, now - 1 * AN_HOUR) + const root = spreadLedger(rows, now) + try { + const whole = _internal.freeWindowOf(rows, "me@example.com", now) + const read = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + const w = _internal.freeWindowOf(read, "me@example.com", now) + expect(read.length).toBe(rows.length) // every row: no edge, so the file's start + expect(w.amount).toBe(whole.amount) + expect(w.resetsAt).toBe(whole.resetsAt) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +// magpie appends the calls a client reports through POST +// /v1/magpie/usage/requests to the same ledger (#1874), dated where the +// client's call happened — a backfill reaching back on purpose +// (docs/integrating.md). Such a line is written at the file's end, so its +// time says nothing about where the read has got to: magpie's own index +// leaves it out of firstOwn for the same reason. It never carries +// providerAccount, so it is never a row of this account's either. +test("a backfilled row of a client's does not end the read", () => { + const now = at("2026-10-22T12:00:00+08:00") + const rows = spread(now - 70 * AN_HOUR, now - AN_HOUR) + const reported = (t) => ({ t: new Date(t).toISOString(), agent: "myapp", provider: "openai", model: "gpt-5", in: 10, out: 5, status: 200, rid: "r1", source: "reported" }) + // one, dated a day and an hour ago, and a batch of 50 behind the same run + for (const backfilled of [[reported(now - 25 * AN_HOUR)], Array.from({ length: 50 }, (_, i) => reported(now - (60 + i) * AN_HOUR))]) { + const root = writeLedger([...rows, ...backfilled].map((r) => JSON.stringify(r))) + try { + const whole = _internal.freeWindowOf(rows, "me@example.com", now) + const read = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + const w = read && _internal.freeWindowOf(read, "me@example.com", now) + // the card is there, and reads as the whole ledger does + expect(w).not.toBeNull() + expect(w.amount).toBe(whole.amount) + expect(w.resetsAt).toBe(whole.resetsAt) + // and none of them is this account's row + expect(read.every((r) => r.providerAccount === "me@example.com")).toBe(true) + } finally { + rmSync(root, { recursive: true, force: true }) + } + } +}) + +// The chain is this account's own: a refusal of another account's, or of a +// paid model, says nothing about where this account's window opened +test("another account's refusal does not pin this account", () => { + const now = at("2026-10-22T12:00:00+08:00") + const rows = spread(now - 70 * AN_HOUR, now - 1 * AN_HOUR) + const root = spreadLedger( + [...rows, row(new Date(now - 30 * AN_HOUR).toISOString(), { status: 429, account: "b@example.com", err: `${TIMEOUT_BEFORE_RESET}2026-10-22 09:00:00 UTC+8, alternatively, you can switch to the other models to continue using it.` })].sort((a, b) => Date.parse(a.t) - Date.parse(b.t)), + now, + ) + try { + const whole = _internal.freeWindowOf(rows, "me@example.com", now) + const read = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + // the other account's row is not this account's, and is not kept either + expect(read.every((r) => r.providerAccount === "me@example.com")).toBe(true) + const w = _internal.freeWindowOf(read, "me@example.com", now) + expect(w.amount).toBe(whole.amount) + expect(w.resetsAt).toBe(whole.resetsAt) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +// A ledger under one chunk used to line the chain up by luck: the file's +// first line was parsed and kept even after the loop had stopped on an older +// row, so a stray row far back opened the window and the answer was right by +// accident. It is kept only when the read runs to the file's start. +test("the file's first line is kept only when the read runs to the start", () => { + const now = at("2026-10-20T20:00:00+08:00") + const lines = [ + JSON.stringify(row(new Date(now - 20 * 3600_000).toISOString(), { in: 1 })), // the file's first line + JSON.stringify(row(new Date(now - 10 * 3600_000).toISOString(), { in: 2 })), + JSON.stringify(row(new Date(now - 60 * 60_000).toISOString(), { in: 3 })), + ] + const root = writeLedger(lines) + try { + const rows = _internal.freeWindowRows("me@example.com", now, root, {}, join(root, "nohome")) + // with no edge in reach the read goes back to the start, and then the + // first line is a row of the ledger like any other + expect(rows.map((r) => r.in)).toEqual([1, 2, 3]) + } finally { + rmSync(root, { recursive: true, force: true }) + } + // a day's gap stops the read with rows under it: the first line is under + // that stop and is not kept + const gap = at("2026-10-20T20:00:00+08:00") + const stopped = writeLedger([ + JSON.stringify(row(new Date(gap - 90 * 3600_000).toISOString(), { in: 1 })), // under the stop + JSON.stringify(row(new Date(gap - 80 * 3600_000).toISOString(), { in: 2 })), // the gap's earlier side + JSON.stringify(row(new Date(gap - 50 * 3600_000).toISOString(), { in: 3 })), // 30h later: a window opens + JSON.stringify(row(new Date(gap - 3600_000).toISOString(), { in: 4 })), + ]) + try { + const rows = _internal.freeWindowRows("me@example.com", gap, stopped, {}, join(stopped, "nohome")) + // 3 and 4: the day before the gap's later row stopped the read, and the + // first line, 10h under it, is not kept + expect(rows.map((r) => r.in)).toEqual([3, 4]) + } finally { + rmSync(stopped, { recursive: true, force: true }) + } +}) + +// The read must be bounded by what it can report, not by how busy the account +// is. A ledger of another provider's rows, with this account's only row 60 +// days back, is read from its end and stops a day in: a lapsed window is +// nothing to report, and no row above the day can open one. +test("a ledger of another provider's rows is not read whole", () => { + const now = at("2026-10-20T20:00:00+08:00") + const lines = [JSON.stringify(row(new Date(now - 60 * 24 * 3600_000).toISOString(), { in: 5 }))] + // a fortnight of another provider's rows, a minute apart: nine days of them + // are past the day the read stops at + for (let i = 0; i < 20000; i++) lines.push(JSON.stringify(row(new Date(now - (20000 - i) * 60_000).toISOString(), { in: 1, provider: "zcode" }))) + const root = writeLedger(lines) + try { + let chunks = 0 + const path = join(root, "usage.jsonl") + const got = _internal.readLedgerTail(path, statSync(path), now, () => chunks++, "me@example.com") + const all = Math.ceil(statSync(path).size / 65536) + // the read stops a day into the file, so a tenth of it or so, never all + expect(chunks).toBeLessThan(all / 4) + expect(chunks).toBeGreaterThan(0) + expect(got.rows.filter((r) => r.provider === "workbuddy-ai").length).toBeLessThan(3) + expect(_internal.freeWindowOf(got.rows, "me@example.com", now)).toBeNull() + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +// an account used would otherwise be read whole when that account has no +// refusal and only its own rows to go on: those rows stop the read, at the +// tail or where the chain is pinned +test("the read of an account's own rows still stops", () => { + const now = at("2026-10-20T20:00:00+08:00") + const lines = [] + for (let i = 6000; i >= 1; i--) lines.push(JSON.stringify(row(new Date(now - i * 60_000).toISOString(), { in: 1 }))) + const root = writeLedger(lines) + try { + let chunks = 0 + const path = join(root, "usage.jsonl") + _internal.readLedgerTail(path, statSync(path), now, () => chunks++) + // 6000 rows is ~2300 hours of 1-minute rows; only the last 48h + a day + // of one-hour steps bear on the chain + expect(chunks).toBeLessThan(800) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +// Two refusals in one chain: the oldest names a window that ended long ago and +// whose reset is behind us, the newest names one still running. pinned walks +// the rows oldest to newest and overwrites, so the newest refusal wins — it is +// nearer to now and its reset is the tighter bound on where the chain can be +// read from. The old `reset < newest` guard is gone; this pins what replaced it. +test("of two refusals in the chain, the newest one pins the read", () => { + const now = at("2026-10-22T12:00:00+08:00") + const at8 = (h) => `${new Date(now - h * AN_HOUR).toISOString().slice(0, 19).replace("T", " ")} UTC+8` + const refusalAt = (h, reset) => row(new Date(now - h * AN_HOUR).toISOString(), { status: 429, err: `${TIMEOUT_BEFORE_RESET}${reset}, alternatively, you can switch to the other models to continue using it.` }) + // an old refusal whose reset lapsed 2 days ago, then a live one 6h back + const old = refusalAt(54, at8(30)) + const live = refusalAt(6, at8(-18)) + const rows = [old, ...spread(now - 54 * AN_HOUR + AN_HOUR, now - 7 * AN_HOUR), live].sort((a, b) => Date.parse(a.t) - Date.parse(b.t)) + expect(rows.at(-1)).toBe(live) + // pinned's contract: latest first + const got = _internal.pinned([...rows].reverse(), "me@example.com") + const liveReset = at(at8(-18).replace(" UTC+8", "+08:00")) + const oldReset = at(at8(30).replace(" UTC+8", "+08:00")) + expect(got).toBe(liveReset - 86400_000) + expect(got).not.toBe(oldReset - 86400_000) +}) + +// One unreadable row in the middle of the chain: pinned passes over it rather +// than ending the chain at it, so the bound is the same as the whole chain's. +// Swap `if (!Number.isFinite(t)) continue` back to `return Infinity` and this +// fails: the corrupt row becomes the bound, and the read would go back to the +// file's start instead of stopping where the clean chain stops. +test("a row whose time cannot be read is passed over", () => { + const now = at("2026-10-22T12:00:00+08:00") + // hourly for 100h, then nothing until 20h ago, then hourly: two runs a day + // or more apart, so the row after the second gap pins the chain + const clean = spread(now - 100 * AN_HOUR, now - 50 * AN_HOUR).concat(spread(now - 20 * AN_HOUR, now)) + const latestFirst = [...clean].sort((a, b) => Date.parse(b.t) - Date.parse(a.t)) + const bound = _internal.pinned(latestFirst, "me@example.com") + // a real bound, not the "no edge, read from the start" 0: walked oldest to + // newest, the first day-wide gap is the one before the 50h row, and that is + // where the chain can first be read from + expect(bound).not.toBe(0) + expect(bound).toBe(now - 50 * AN_HOUR - A_DAY) + // the same chain with one row in its middle carrying no readable t + const holey = latestFirst.map((r) => (Date.parse(r.t) === now - 60 * AN_HOUR ? { ...r, t: "not-a-time" } : r)) + expect(holey.some((r) => r.t === "not-a-time")).toBe(true) + // the same bound, not Infinity and not the 0 of a chain with no edge + expect(_internal.pinned(holey, "me@example.com")).toBe(bound) +}) diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 928bbab..9afb317 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -10,9 +10,9 @@ // those of its current desktop app (see SITES' app, cli and appName). import { createHash, randomBytes } from "node:crypto" -import { readFileSync } from "node:fs" +import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs" import { homedir } from "node:os" -import { join } from "node:path" +import { isAbsolute, join } from "node:path" import { gzipSync } from "node:zlib" const APP_VERSION = "2.0.0" // the version WorkBuddy's sign-in page is opened with @@ -1899,6 +1899,556 @@ function capacity(v) { // compact is a count as magpie says one: whole, else to two places. const compact = (n) => (Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/0+$/, "").replace(/\.$/, "")) +// The window WorkBuddy AI rate limits its free models by, which its credit +// meter does not show. +// +// A free account's usage() reports only the credits window, so a plan with +// 160 credits untouched reads 0% while chats to deepseek-v4.1-flash are +// already refused: the model has a token allowance of its own, counted +// apart from credits, and nothing the vendor answers with reports it. The +// refusal is the only place it appears, and only as a time: +// +// 429 usage exceeds frequency limit, but don't worry, your usage will +// reset at 2026-10-20 19:47:41 UTC+8, alternatively, you can switch to +// the other models to continue using it. +// +// Measured on a free plan over ten days (one account, deepseek-v4.1-flash +// only), counting in + cache_read + out: +// +// 10-15 15:40 → 100,183,315 429 10-18 19:52 → 92,792,962 429 +// 10-16 16:48 → 99,971,831 429 10-19 19:47 → 98,201,537 429 +// 10-14 15:38 → 71,687,717 lapsed +// +// so the cap is per account per 24 hours at about 1e8 tokens, the largest +// value that still answered being 100,183,315. Three things about it are +// easy to get wrong and were all checked: +// +// - cache_read counts. In + out alone is 20× smaller (0.75M–3.9M a +// window) and never comes near the cap. +// - the window is fixed, not sliding: peak trailing-24h over the same +// data is 172.85M, which a sliding window would have held to 1e8. +// - the reset a refusal names is the window's start + 24h exactly, and +// the start is the first request answered after the previous window +// ended — not the reset instant. Gaps of 6, 68, 80 and 182 minutes +// were seen between a reset and the next request, each opening the new +// window. +// +// deepseek-v4.1-flash-sg is the same model under its paid id (the product +// config's ModelRateLimitCap.lines[0] names it as paidId to this freeId, +// allowPaidSwitch: true) and draws on the same window: it was refused in +// the same windows, to the second, with about 0.01M tokens of its own. +// Both ids are named in models: magpie matches a plugin window's models +// against a model id exactly, folding only an @size suffix +// (internal/provider/plugin_usage.go, idSetOf), so one id alone leaves the +// other unrestricted. +// +// The window is read two ways, and a refusal wins: +// +// - the sum (in + cache_read + out) of this machine's rows, which holds +// until the account is first refused. The ledger is this machine's +// only, so an account also used on another machine or through another +// client reads short: 92.8M read as "93%" on one refused at 92,792,962, +// the rest of its spending being elsewhere. +// - a refusal whose named reset is still ahead, which makes the window +// full whatever the sum says. That is the one exact signal there is, +// and routing must not pass over it either. +// +// The ledger is magpie's own, in magpie's config folder (appdir.Config()): +// the folder the plugin host runs in, which is the portable data folder +// when magpie runs portable, $XDG_CONFIG_HOME/magpie when that is set, and +// ~/.config/magpie otherwise. No endpoint reports the window; a ledger that +// cannot be read yields no window rather than a made-up one. + +const FREE_WINDOW_CAP = 1e8 +const FREE_WINDOW_SPAN = 24 * 3600 * 1000 +// The lead: how far back of an edge the read goes on. A chain read from a row +// that opens a window needs the window the span makes of the rows above it, +// so the rows kept reach a day past the edge — the window opening at the +// request after it, minutes to hours into that day, whatever the first row +// after the edge falls on. +const FREE_WINDOW_LEAD = 86400 * 1000 +// A gap this long between two of this account's answered rows ends every +// window before it, so the later row opens one: the window holding the +// earlier row began at most 24h before it, and so ended 24h after it at the +// latest. This is one of the two edges the ledger itself spells out. +const FREE_WINDOW_GAP = FREE_WINDOW_SPAN +// the model the window is counted for; -sg shares it +const FREE_WINDOW_MODEL = "deepseek-v4.1-flash" +// both ids, so magpie's exact match finds the -sg one too +const FREE_WINDOW_MODELS = ["deepseek-v4.1-flash", "deepseek-v4.1-flash-sg"] +// the provider whose rows count +const FREE_WINDOW_PROVIDER = "workbuddy-ai" + +// windowOffset is the UTC offset a refusal spells out, in minutes, from +// "UTC+8", "UTC+08:00", "UTC-5" or "GMT+8". null when it spells out none, +// which is not the same as +08:00: an offset guessed wrong puts the reset +// hours from where it is, so a reset that cannot be placed is not used as +// an edge at all. +function windowOffset(text) { + const m = /\b(?:UTC|GMT)\s*([+-])\s*(\d{1,2})(?::?(\d{2}))?\b/i.exec(String(text ?? "")) + if (!m) return null + const min = Number(m[2]) * 60 + Number(m[3] ?? 0) + if (min > 14 * 60) return null + return m[1] === "-" ? -min : min +} + +// windowReset is the instant a refusal names, or NaN when it names none or +// names it in an offset that cannot be read. +function windowReset(text) { + const s = String(text ?? "") + const at = /reset at (\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/.exec(s) + if (!at) return NaN + const off = windowOffset(s) + if (off === null) return NaN + return Date.UTC(+at[1], +at[2] - 1, +at[3], +at[4], +at[5], +at[6]) - off * 60000 +} + +// 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. +// +// The window is a chain: it begins at the first request answered after the +// previous one ended, so where this window began depends on every window +// before it. A window ends at a refusal's reset when the ledger holds one, +// and otherwise a day after it began. readLedgerTail (which see) stops on +// both, so that these rows read the same as the whole ledger. +function freeWindowOf(rows, account, now = Date.now()) { + const mine = (Array.isArray(rows) ? rows : []).filter( + (r) => + r?.provider === FREE_WINDOW_PROVIDER && + r.providerAccount === account && + typeof r.model === "string" && + r.model.startsWith(FREE_WINDOW_MODEL) && + r.t, + ) + if (!mine.length) return null + + const at = (r) => { + const t = Date.parse(r.t) + return Number.isFinite(t) ? t : 0 + } + const counted = (r) => (r.in ?? 0) + (r.cache_read ?? 0) + (r.out ?? 0) + // two rows a day apart: the first of them opened a window that has ended by + // the second. Written as a function so that no minifier folds the + // subtraction into the comparison. + const apart = (a, b) => a - b >= FREE_WINDOW_SPAN + + // a refusal names the end of the window it refused in + const edges = [] + for (const r of mine) { + if (Number(r.status) !== 429) continue + const t = windowReset(r.err) + if (Number.isFinite(t)) edges.push(t) + } + edges.sort((a, b) => a - b) + + const answered = mine.filter((r) => Number(r.status) === 200 && at(r) > 0).sort((a, b) => at(a) - at(b)) + if (!answered.length) return null + + const head = (from) => { + let start = null + let used = 0 + let edge = 0 // the refusals already read + for (let i = from; i < answered.length; i++) { + const r = answered[i] + const t = at(r) + // every refusal this row's window ended at closes it + while (edge < edges.length && edges[edge] <= t) { + start = null + used = 0 + edge++ + } + if (start === null) start = t + else if (apart(t, start)) { + start = t + used = 0 + } + used += counted(r) + } + return start === null ? null : { start, used } + } + + // The rows may begin before the window now: readLedgerTail goes a day past + // the edge it stops at, so the run of rows that opens a window can start a + // day after the first row kept. That window opens at a row with no answered + // row of this account's within a day before it — where the chain is read + // from. Read from the first row kept, the chain would begin shifted, a day + // early: every window after it, the card with it. + let w = null + for (let i = 0; i < answered.length; i++) { + if (i && !apart(at(answered[i]), at(answered[i - 1]))) continue + const h = head(i) + if (h === null) continue + if (h.start + FREE_WINDOW_SPAN <= now) continue // lapsed before now + w = h + break + } + const start = w?.start + const used = w?.used + if (!(start > 0)) return null + + const end = start + FREE_WINDOW_SPAN + if (now >= end) return null // lapsed: nothing is exhausted, a new window opens on the next request + + const card = (amount, resetsAt, refused) => ({ + name: "Free model tokens", + used: Math.min(100, (100 * amount) / FREE_WINDOW_CAP), + amount, + limit: FREE_WINDOW_CAP, + unit: "tokens", + display: `${tokensShort(amount)} / 100M`, + resetsAt: new Date(resetsAt).toISOString(), + span: FREE_WINDOW_SPAN / 1000, + models: FREE_WINDOW_MODELS.slice(), + ...(refused ? { refused: true } : {}), + }) + + // A refusal still in force is exact: the account is spending this window + // from elsewhere too, so the sum undercounts it, and the refusal is the + // answer the vendor would give again. Its reset is the window's end, + // named by the vendor rather than derived from start. + let live = null + for (const r of mine) { + if (Number(r.status) !== 429) continue + const t = windowReset(r.err) + if (!Number.isFinite(t) || t <= now || t <= start) continue + if (live === null || t > live) live = t + } + if (live !== null) return card(FREE_WINDOW_CAP, live, true) + + return card(used, end, false) +} + +// tokensShort says a token count small: 11.9M, 812k. The credits card's +// compact() (2 decimals, credited to credits) reads a token count badly. +function tokensShort(n) { + if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M` + if (n >= 1e3) return `${Math.round(n / 1e3)}k` + return String(Math.round(n)) +} + +// ledgerParsed is the rows read last and what they were read for: the file's +// fingerprint, the account and the instant. A file that has not changed hands +// back the rows already parsed rather than reading and decoding them again. +// +// Reading the ledger whole was 48 ms on 2026-10-21 (10.3 MiB, 17925 lines: +// 6.4 ms to read, 32.8 ms to JSON.parse, 8 ms to find the window), spent +// synchronously on the plugin host's thread every time a panel opened or a +// card was asked about, which is what made the free-token window feel slow +// beside the credits, whose reading is a network call and so blocks nothing. +// A heavy ledger runs to hundreds of MiB, so the read starts at the end. +// +// The key carries the account because the rows are this account's: one +// account's read must not answer for another's. A read for an earlier instant +// keeps all the rows a read for a later one would — the bounds are only +// further back, and an edge is the same time in either — so the rows held +// over answer for the later one too: freeWindowOf is what decides with its +// own now. +let ledgerParsed = null + +// 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. +let ledgerBad = { key: "", count: 0 } + +// freeWindowLedger is the ledgers looked for, in magpie's own folder order +// (appdir.Config()): the plugin host runs in that folder — the portable +// data folder when magpie runs portable, $XDG_CONFIG_HOME/magpie when that +// is set, ~/.config/magpie otherwise — so its cwd answers first; the other +// two are named as well, for a plugin asked outside the host. The first +// readable ledger wins: a stale copy in a folder magpie does not use must +// not hide the live one. +// +// $XDG_CONFIG_HOME counts only when it is absolute, as appdir.rooted has it: +// an empty or relative value is not where magpie keeps its ledger. +function freeWindowLedger(cwd = process.cwd(), env = process.env, home = homedir()) { + const dirs = [cwd] + if (env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME)) dirs.push(join(env.XDG_CONFIG_HOME, "magpie")) + if (home) dirs.push(join(home, ".config", "magpie")) + return dirs.map((d) => join(d, "usage.jsonl")) +} + +// 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. +// +// The ledger is appended to a line at a time, so a read that lands while a +// call is being written can catch that line half-written. Only the last +// line can be torn that way (everything before it was written whole), and +// only it is passed over in silence. A whole line in the middle that won't +// decode is a real fault — a truncated file, a writer that lost a record — +// and is said aloud, because passing it over quietly is how a window goes +// missing with nothing to point at: on 2026-10-21 a restart caught the +// ledger mid-write, the one row holding the free window's start was +// dropped without a word, and the panel showed no window at all until the +// next read happened to succeed. +function freeWindowRows(account, now = Date.now(), cwd = process.cwd(), env = process.env, home = homedir()) { + if (!account) return null + let found = null + for (const path of freeWindowLedger(cwd, env, home)) { + try { + const st = statSync(path) + if (!st.size) continue + found = { path, st } + break + } catch {} + } + if (!found) return null + const { path, st } = found + // size and mtime both move when a call is appended, which is the only + // way this ledger is written; one rewritten in place (a rotation or a + // compaction) moves mtime even when its size lands the same. + const file = path + "|" + st.mtimeMs + ":" + st.size + const key = file + "|" + account + if (ledgerParsed?.key === key) return ledgerParsed.rows + let got + try { + got = readLedgerTail(path, st, now, undefined, account) + } 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 } + return got.rows +} + +// LEDGER_T is where a row's time sits: "t" is among the first keys +// usage.Record writes, within this many bytes of the line's start, so every +// line's time is read without decoding the line — most of a ledger's lines +// belong to another provider, or to this account and out of reach. +const LEDGER_T = /"t"\s*:\s*"([^"]{10,64})"/ + +// LEDGER_ACCOUNT finds the account a line was written under, before the line +// is decoded. usage.Record writes providerAccount second. +const LEDGER_ACCOUNT = /"providerAccount"\s*:\s*"([^"]{0,256})"/ + +// rowTime is the instant a line is written at, from that "t", or NaN. +function rowTime(line) { + const m = LEDGER_T.exec(line) + return m ? Date.parse(m[1]) : NaN +} + +// LEDGER_REPORTED finds what a client reported: POST /v1/magpie/usage/requests +// (#1874) appends a client's own calls to the same ledger, with the time the +// client gives them, and a past time is kept on purpose so history can be +// backfilled (docs/integrating.md). Such a row is written at the end of the +// file and dated anywhere, so it says nothing about where the file's own +// records have got to — magpie's index leaves it out of firstOwn for the same +// reason (log_index.go). It never carries providerAccount, being not in +// ingestFields, so it is never a row of this account either. +const LEDGER_REPORTED = /"source"\s*:\s*"reported"/ + +// rowReported is whether a line is one a client reported rather than one +// magpie wrote when it happened. +function rowReported(line) { + return LEDGER_REPORTED.test(line) +} + +// rowAccount is the account a line was written under, or null when the line +// names none (another record, or one cut short). +function rowAccount(line) { + const m = LEDGER_ACCOUNT.exec(line) + if (!m) return null + try { + return JSON.parse(`"${m[1]}"`) + } catch { + return null + } +} + +// ofAccount is whether a row belongs to the chain read for account: this +// account's own row of the free model, either id. A refusal of another +// account's, or of a paid model, says nothing about where this chain opens. +function ofAccount(row, account) { + return ( + row?.provider === FREE_WINDOW_PROVIDER && + row.providerAccount === account && + typeof row.model === "string" && + row.model.startsWith(FREE_WINDOW_MODEL) + ) +} + +// readLedgerTail decodes the ledger from its end backwards, and stops where +// the chain of account's own rows can still be read from. chunks is a test's +// way of counting reads; nothing else passes it. +// +// Why it cannot stop at 48h: the window is a chain — each one starts at the +// first request answered after the previous one ended — so where the window +// now began depends on every window before it. A first row that is not an +// edge opens the window in the middle of a real one and every window after +// it is shifted: 4% on an account two hours from its cap, or 100% on one +// still served, which routing would then pass over. So the read goes back +// until the rows it keeps read the window now as the whole ledger does: +// +// - a refusal of this account's, whose reset can be read: the window it +// named ended there, and the next request opened another; +// - a gap of 24h or more between two of this account's answered rows: the +// window holding the earlier one has ended by then, and the later one +// opens one; +// - and with neither, it reads to the file's start, where the chain has no +// earlier window to be shifted by. +// +// Each edge is passed by a day (FREE_WINDOW_LEAD), the window opening at the +// request after it, minutes to hours into the day. +// +// Two bounds keep that from being a whole file on every poll, and neither +// depends on how busy the account is: +// +// - the ledger is appended in time order, so a line whose time is under the +// edge — of whatever provider, of whatever account — ends the read; +// - a read that is past now - 24h with no answered free-model row of this +// account has nothing to report: the window has lapsed, and freeWindowOf +// says null. It stops there rather than going on to the edges. +// +// Every line's time is read from its "t" before the line is decoded, so a +// line of another provider or account costs one match and no JSON.parse. +// +// What is not covered: magpie's providerAccount is the account's label, and a +// label two accounts share gets its slot added to it (pluginLabels, +// plugin_accounts.go). The label then no longer equals the accountId rows are +// written under, no row is found for this account at all, and the card +// reports no free window. +function readLedgerTail(path, st, now, chunks, account) { + const CHUNK = 1 << 16 + const lapsed = now - FREE_WINDOW_SPAN // a read past this holds no window now + const fd = openSync(path, "r") + try { + // a ledger whose last byte ends a line has no line being written + let tornEnd = false + if (st.size > 0) { + const one = Buffer.allocUnsafe(1) + readSync(fd, one, 0, 1, st.size - 1) + tornEnd = one[0] !== 0x0a + } + const rev = [] // the rows kept, latest first + let bad = 0 + let pos = st.size + let carry = "" + let firstPass = true + let stop = false + let chain = [] // this account's own rows read, latest first + let reach = 0 // the row below which nothing is kept: 0 until an edge is found + let answered = false // whether an answered free-model row of it is read + + while (pos > 0 && !stop) { + const len = Math.min(CHUNK, pos) + pos -= len + const buf = Buffer.allocUnsafe(len) + readSync(fd, buf, 0, len, pos) + if (chunks) chunks(1) + const lines = (buf.toString("utf8") + carry).split("\n") + carry = lines.shift() // its first line is begun in an earlier chunk + for (let i = lines.length - 1; i >= 0 && !stop; i--) { + const line = lines[i] + if (!line.trim()) continue + const t = rowTime(line) + // Under an edge or the bound, by time alone: nothing below it can be + // kept, whatever wrote it — but a line a client reported is dated + // where the client's call happened, not where the file has got to. + const dated = Number.isFinite(t) && !rowReported(line) + if (dated && reach && t < reach) { + stop = true + break + } + // A day back with nothing of this account's answered and no edge in + // reach: no window is being spent now, and nothing below can open one + if (dated && !reach && !answered && t < lapsed) { + stop = true + break + } + // Another provider's or another account's line: nothing else to see + if (!line.includes(account) || rowAccount(line) !== account) continue + let row + try { + row = JSON.parse(line) + } catch { + // the last line may be a call still being written, and is passed + // over; anything before it is a fault worth saying + if (!(firstPass && tornEnd && i === lines.length - 1)) bad++ + continue + } + if (!ofAccount(row, account)) continue + rev.push(row) + chain.push(row) + if (Number(row.status) === 200) answered = true + if (!reach && Number(row.status) !== 429) reach = pinned(chain, account) + } + firstPass = false + } + // the file's first line, with no newline before it: kept only when the + // read ran to the file's start + if (!stop && pos === 0 && carry.trim() && carry.includes(account) && rowAccount(carry) === account) { + const t = rowTime(carry) + if (!reach || !Number.isFinite(t) || t >= reach) { + try { + const row = JSON.parse(carry) + if (ofAccount(row, account)) rev.push(row) + } catch { + bad++ + } + } + } + return { rows: rev.reverse(), bad } + } finally { + closeSync(fd) + } +} + +// pinned is where the chain of account's own rows (latest first) is read +// from: the time below which nothing is kept. 0 while the rows say nothing +// about it yet, and the read then goes to the file's start. +// +// A row whose time cannot be read is passed over rather than ending the +// chain there: one corrupt line used to cut it wherever it sat. +function pinned(rows, account) { + const at = (r) => Date.parse(r?.t) + const apart = (a, b) => a - b >= FREE_WINDOW_GAP + // A refusal names where a window ended, and the next request opened + // another. The loop walks oldest to newest and overwrites `denied`, so the + // one kept is the *newest* readable refusal in the chain, not the earliest: + // a later refusal is nearer to now, and its reset is the tighter bound on + // where the chain can be read from. A refusal whose reset has already been + // passed by a newer one therefore loses, which is what we want — the old + // `reset < newest` test that used to guard this is gone, the overwrite does + // 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 + if (Number.isFinite(reset)) denied = reset + } + if (denied !== null) return denied - FREE_WINDOW_LEAD + // A day's gap between two answered rows ended every window before it, and + // the day before the later row is where the span's reading of the rows + // above it begins. The rows come latest first, so each is compared with the + // one read before it — the row after it in time, `later`. + let later = null + for (let i = rows.length - 1; i >= 0; i--) { + const r = rows[i] + const t = at(r) + if (!Number.isFinite(t)) continue + if (Number(r.status) !== 200) continue + if (later === null) { + later = t + continue + } + if (apart(t, later)) return later - FREE_WINDOW_LEAD + later = t + } + // no edge among these rows: the read goes on to the file's start, which is + // the whole ledger — the only place a chain needs nothing before it + return 0 +} + +// _internal is where these are handed to a test: magpie's host calls every +// exported function of a plugin as one of its own factories (host.js, +// servers()), so freeWindowRows et al. must not be exports of the plugin. + // usageOf is the account's credits, from its resource summary: the plan's // credits used against what the cycle grants, as magpie's built-in said — // the count itself too (amount of limit, in credits), for magpie to say it @@ -2718,6 +3268,16 @@ function makePlugin(site) { } catch {} } await spareFree(site, a, out.windows) + // the free model's own window, which the credit meter above does + // not show: what actually refuses a chat long before 160 credits + // are spent. WorkBuddy AI alone; the China build has no such cap + // measured (see freeWindowOf) + if (site.ai) { + const account = a.accountId || a.user || a.uid || "" + const rows = freeWindowRows(account) + const w = rows && freeWindowOf(rows, account) + if (w) out.windows.push(w) + } return { ...out, signIn: said } } catch (e) { return { error: e?.message ?? String(e), signIn: "kept" } @@ -2849,4 +3409,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { idFor, replyAfterToolsOn, withDefaultEffort, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } +export const _internal = { idFor, replyAfterToolsOn, withDefaultEffort, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, 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, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 2c43403..9eac898 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.47", + "version": "0.1.48", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs", diff --git a/packages/workbuddy/usage.test.mjs b/packages/workbuddy/usage.test.mjs index 234be8a..a007653 100644 --- a/packages/workbuddy/usage.test.mjs +++ b/packages/workbuddy/usage.test.mjs @@ -537,3 +537,26 @@ test("a model list that can't be read leaves the credits counting every model", expect(w.used).toBe(100) expect(w.notModels).toBeUndefined() }) + +// #299: the free model's window, read from magpie's usage ledger, reaches +// the WorkBuddy AI card beside Credits; the China build's card has none +test("a WorkBuddy AI card carries the free model's window from the ledger", async () => { + const dir = join(home, ".config", "magpie") + mkdirSync(dir, { recursive: true }) + const ledger = join(dir, "usage.jsonl") + const t = new Date(Date.now() - 3600_000).toISOString() + writeFileSync(ledger, JSON.stringify({ provider: "workbuddy-ai", providerAccount: "me@example.com", model: "deepseek-v4.1-flash", t, status: 200, in: 30_000_000, cache_read: 0, out: 0 }) + "\n") + try { + serve({ "/billing/meter/get-user-resource-summary": () => + ok({ IsPaidUser: false, Packages: [{ CycleTotalCapacity: "160", CycleUsedCapacity: "0" }] }) }) + const auth = { type: "oauth", access: "ai-access", expires: later(), uid: "ai3", accountId: "me@example.com", domain: "www.codebuddy.ai" } + const out = await usageOf(WorkBuddyAIAuthPlugin, auth) + expect(out.windows.map((w) => w.name)).toEqual(["Credits", "Free model tokens"]) + expect(out.windows[1]).toMatchObject({ amount: 30_000_000, limit: 1e8, unit: "tokens" }) + serve({ "/billing/meter/get-user-resource-summary": () => + ok({ IsPaidUser: false, Packages: [{ CycleTotalCapacity: "160", CycleUsedCapacity: "0" }] }) }) + expect((await usageOf(WorkBuddyAuthPlugin, { ...auth, domain: "" })).windows.map((w) => w.name)).toEqual(["Credits"]) + } finally { + rmSync(ledger, { force: true }) + } +})