From 214530edadd3d0af4ddb47b2013d011598caf6a4 Mon Sep 17 00:00:00 2001 From: skygunner Date: Wed, 28 Oct 2026 02:34:58 +1000 Subject: [PATCH] cloudflare-workers-ai: read actual Neurons and keep the quota card toggles Workers AI usage now reads the day's actual Neurons from Cloudflare's GraphQL analytics, keeps the Used/Left toggle on the quota card, and stops the included free allowance from benching a Paid or unknown plan (`aside`). A 429 with code 3036 gets a Retry-After that runs to the next UTC midnight. Version 0.0.4; dist has 0.0.3, and npm has never had the package. What was run, at reviewed head 38ddeb132ee6c00698952303fbc4949a84287779: - `bun test packages/cloudflare-workers-ai` with a sandbox HOME/TMPDIR: 23/23 pass. - `bun scripts/check.mjs`: ok. - Merged with origin/main, the whole repo `bun test` with a sandbox HOME: 2900 pass, 3 skip, 0 fail across 245 files. - Broke code and timing by hand: - Removing the `!info.errors?.length` guard turns only the new partial-reply assertion red. - A preload that moves Date.now() 700ms forward on every call fails the old (bdc302a) Retry-After test ("26820 vs ~26819"). The new bracketed test passes 3 of 3 under that preload. - The earlier review at bdc302a covered the rest of the change. That includes nine mutations, each of which turns a test red. Not tried: - A real Paid account's billing and inference, as the author says too. - A fetch call that straddles exactly 00:00:00 UTC. The Retry-After bracket would fail there, but only inside a window a few milliseconds long. --- packages/cloudflare-workers-ai/README.ja.md | 12 +- packages/cloudflare-workers-ai/README.md | 13 +- .../cloudflare-workers-ai/README.zh-CN.md | 12 +- packages/cloudflare-workers-ai/package.json | 2 +- packages/cloudflare-workers-ai/src/index.mjs | 95 ++++++++- .../test/plugin.test.mjs | 200 +++++++++++++++++- 6 files changed, 309 insertions(+), 25 deletions(-) diff --git a/packages/cloudflare-workers-ai/README.ja.md b/packages/cloudflare-workers-ai/README.ja.md index 26e09ca..742e5ff 100644 --- a/packages/cloudflare-workers-ai/README.ja.md +++ b/packages/cloudflare-workers-ai/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) | [简体中文](README.zh-CN.md) | 日本語 -[![npm version](https://img.shields.io/badge/npm%20version-0.0.3-EA4335.svg)](https://www.npmjs.com/package/@magpie-community/opencode-cloudflare-workers-ai-auth) +[![npm version](https://img.shields.io/badge/npm%20version-0.0.4-EA4335.svg)](https://www.npmjs.com/package/@magpie-community/opencode-cloudflare-workers-ai-auth) [![License: MIT](https://img.shields.io/badge/License-MIT-FBBC05.svg)](https://opensource.org/licenses/MIT) [OpenCode](https://opencode.ai) 1.x と [magpie](https://usemagpie.ai) 向けのプロバイダー @@ -18,12 +18,15 @@ | 項目 | 在処 | |---|---| | Cloudflare Account ID | ダッシュボードの **Account home** → 右sidebar の 32 桁 hex | -| Cloudflare API トークン | ダッシュボード → アバター → **My Profile** → API Tokens → カスタムトークンを `Account → Workers AI → Edit` で作成(`magpie quota` でプラン名まで表示したい場合は `Account Settings → Read` も追加) | +| Cloudflare API トークン | ダッシュボード → アバター → **My Profile** → API Tokens → カスタムトークンを `Account → Workers AI → Edit` で作成(プラン名表示には `Account Settings → Read`、当日の使用済み Neurons 表示には `Account Analytics → Read` も追加) | | magpie | 0.1.1110 以降、または OpenCode 1.x | トークンに Zone の選択は不要。Free/Paid 両プランに **1 日 10,000 Neurons** の無料枠が つき、8 つのフロンティアモデルだけ Workers Paid または AI Gateway クレジットが必要です(下記の目印)。 +クォータカードは毎日の無料枠を数値と使用済み/残りの切り替え可能な割合で表示し、UTC 00:00 にリセットします。 +Paid または未確認のプランでは表示のみで、Free と確認できたプランだけ無料枠を使い切るとルーティングを停止します。 + ## magpie へのインストール ```sh @@ -116,12 +119,13 @@ https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1 | `Model … absent from the current catalog` | models.dev の cloudflare-workers-ai セクションにない ID — 一覧から選ぶ | | (Paid) モデルで 400 | プランが Free:Workers Paid か AI Gateway クレジットが必要 | | quota 行がプラン名の代償テキスト | トークンに `Account Settings → Read` がない — 表示だけの問題で Neurons 枠は出る | +| quota 行が 10,000 / 10,000 残りと表示するのにリクエストが used up your daily free allocation で失敗する | トークンに `Account Analytics → Read` がなく使用量を取得できないため magpie が枠を未使用として描画する — スコープを追加して更新 | ## 開発 ```sh node --check src/index.mjs # パース検査(元リポジトリのバグ) -node --test # 11 テスト、ネットワーク不要 +node --test # 23 テスト、ネットワーク不要 sh scripts/sandbox.sh login # magpie 0.1.1326 を使い捨て HOME で sh scripts/sandbox.sh test # サンドボックス内で provider test sh scripts/sandbox.sh json # サンドボックス内で plugin --json @@ -145,7 +149,7 @@ sh scripts/sandbox.sh json # サンドボックス内で plugin --json | | | |---|---| -| **バージョン** | 0.0.3 | +| **バージョン** | 0.0.4 | | **ライセンス** | [MIT](LICENSE) — Copyright (c) 2026 Guislabert | | **ランタイム** | Node.js >= 20、ESM のみ | | **作者** | [@Guislabert](https://github.com/Guislabert) | diff --git a/packages/cloudflare-workers-ai/README.md b/packages/cloudflare-workers-ai/README.md index dd2018d..28f675f 100644 --- a/packages/cloudflare-workers-ai/README.md +++ b/packages/cloudflare-workers-ai/README.md @@ -2,7 +2,7 @@ English | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) -[![npm version](https://img.shields.io/badge/npm%20version-0.0.3-EA4335.svg)](https://www.npmjs.com/package/@magpie-community/opencode-cloudflare-workers-ai-auth) +[![npm version](https://img.shields.io/badge/npm%20version-0.0.4-EA4335.svg)](https://www.npmjs.com/package/@magpie-community/opencode-cloudflare-workers-ai-auth) [![License: MIT](https://img.shields.io/badge/License-MIT-FBBC05.svg)](https://opensource.org/licenses/MIT) A provider plugin for [OpenCode](https://opencode.ai) 1.x and @@ -18,13 +18,17 @@ and a daily Neurons allowance row in `magpie quota`. | Item | Where to find it | |---|---| | Cloudflare Account ID | 32 hex characters, on the dashboard's **Account home** → right sidebar | -| Cloudflare API token | Dashboard → avatar → **My Profile** → API Tokens → create a **Custom Token** with `Account → Workers AI → Edit` (add `Account Settings → Read` if you also want the plan name in `magpie quota`) | +| Cloudflare API token | Dashboard → avatar → **My Profile** → API Tokens → create a **Custom Token** with `Account → Workers AI → Edit` (add `Account Settings → Read` for the plan name and `Account Analytics → Read` for today's actually-used Neurons in `magpie quota`) | | magpie | 0.1.1110 or later, or OpenCode 1.x | No zones need to be selected on the token. Free and Paid plans both get **10,000 Neurons/day** free; eight frontier models need Workers Paid or prepaid AI Gateway credits (flagged below). +The quota card shows the daily free allowance as a count and a Used / Left +percentage, resetting at 00:00 UTC. Paid or unconfirmed plans keep this window +informational; only a confirmed Free plan stops routing when it is spent. + ## Install in magpie ```sh @@ -123,12 +127,13 @@ https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1 | `Model … absent from the current catalog` | the model id isn't in models.dev's cloudflare-workers-ai section; pick a listed model | | 400 on a (Paid) model | your plan is Free and the model needs Workers Paid or AI Gateway credits | | Quota row shows the fallback plan text | the token lacks `Account Settings → Read`; the escalation is purely cosmetic — the Neurons window is still shown | +| Quota row shows 10,000 / 10,000 remaining but requests fail with `used up your daily free allocation` | the token lacks `Account Analytics → Read`, so the used amount is unknown and magpie renders the allowance as untouched — grant that scope and refresh | ## Development ```sh node --check src/index.mjs # parse guard (the upstream bug that started this fork) -node --test # 11 tests, no network needed +node --test # 23 tests, no network needed sh scripts/sandbox.sh login # magpie 0.1.1326 in a throwaway HOME sh scripts/sandbox.sh test # provider test inside that sandbox sh scripts/sandbox.sh json # plugin --json inside that sandbox @@ -152,7 +157,7 @@ magpie, agents and sign-ins are never touched. | | | |---|---| -| **Version** | 0.0.3 | +| **Version** | 0.0.4 | | **License** | [MIT](LICENSE) — Copyright (c) 2026 Guislabert | | **Runtime** | Node.js >= 20, ESM only | | **Author** | [@Guislabert](https://github.com/Guislabert) | diff --git a/packages/cloudflare-workers-ai/README.zh-CN.md b/packages/cloudflare-workers-ai/README.zh-CN.md index 7f165e5..2d1062d 100644 --- a/packages/cloudflare-workers-ai/README.zh-CN.md +++ b/packages/cloudflare-workers-ai/README.zh-CN.md @@ -2,7 +2,7 @@ [English](README.md) | 简体中文 | [日本語](README.ja.md) -[![npm version](https://img.shields.io/badge/npm%20version-0.0.3-EA4335.svg)](https://www.npmjs.com/package/@magpie-community/opencode-cloudflare-workers-ai-auth) +[![npm version](https://img.shields.io/badge/npm%20version-0.0.4-EA4335.svg)](https://www.npmjs.com/package/@magpie-community/opencode-cloudflare-workers-ai-auth) [![License: MIT](https://img.shields.io/badge/License-MIT-FBBC05.svg)](https://opensource.org/licenses/MIT) 面向 [OpenCode](https://opencode.ai) 1.x 和 [magpie](https://usemagpie.ai) 的供应商插件: @@ -17,12 +17,15 @@ | 项目 | 在哪里找 | |---|---| | Cloudflare Account ID | 控制台首页(Account home)右侧栏,32 位十六进制 | -| Cloudflare API Token | 控制台 → 头像 → **My Profile** → API Tokens → 创建 **Custom Token**,授权 `Account → Workers AI → Edit`(想让 `magpie quota` 显示套餐名,再加 `Account Settings → Read`) | +| Cloudflare API Token | 控制台 → 头像 → **My Profile** → API Tokens → 创建 **Custom Token**,授权 `Account → Workers AI → Edit`(想让 `magpie quota` 显示套餐名,加 `Account Settings → Read`;想显示当天实际已用 Neurons,再加 `Account Analytics → Read`) | | magpie | 0.1.1110 及以上,或 OpenCode 1.x | Token 不需要选择任何 Zone。Free 与 Paid 两个计划均含 **每日 10,000 Neurons** 免费额度; 有 8 个前沿模型需要 Workers Paid 或 AI Gateway 预充值(下文有标注)。 +额度卡片以数值和可切换的已用/剩余百分比显示每日免费额度,每天 UTC 00:00 重置。 +付费或尚未确认的套餐仅展示这个窗口;只有确认是 Free 的套餐才会在免费额度耗尽后停止路由。 + ## 在 magpie 中安装 ```sh @@ -116,12 +119,13 @@ https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1 | `Model … absent from the current catalog` | 模型 ID 不在 models.dev 的 cloudflare-workers-ai 分节里,请从列表中选择 | | (Paid) 模型返回 400 | 你的计划是 Free,该模型需要 Workers Paid 或 AI Gateway 预充值 | | quota 行显示套餐兜底文案 | token 缺 `Account Settings → Read`;仅影响显示,Neurons 窗口照常展示 | +| quota 行显示 10,000 / 10,000 全部剩余,但请求报 used up your daily free allocation | token 缺 `Account Analytics → Read`,已用量未知,magpie 把额度当成没用过 —— 授权后刷新即可 | ## 开发 ```sh node --check src/index.mjs # 语法防线(本 fork 起初修的核心 bug) -node --test # 11 项测试,无需联网 +node --test # 23 项测试,无需联网 sh scripts/sandbox.sh login # 在一个用完即弃的 HOME 里跑 magpie sh scripts/sandbox.sh test # 沙盒内 provider test sh scripts/sandbox.sh json # 沙盒内 plugin --json @@ -145,7 +149,7 @@ sh scripts/sandbox.sh json # 沙盒内 plugin --json | | | |---|---| -| **版本** | 0.0.3 | +| **版本** | 0.0.4 | | **许可证** | [MIT](LICENSE) — Copyright (c) 2026 Guislabert | | **运行时** | Node.js >= 20,仅 ESM | | **作者** | [@Guislabert](https://github.com/Guislabert) | diff --git a/packages/cloudflare-workers-ai/package.json b/packages/cloudflare-workers-ai/package.json index 6ccc283..3ef91db 100644 --- a/packages/cloudflare-workers-ai/package.json +++ b/packages/cloudflare-workers-ai/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cloudflare-workers-ai-auth", - "version": "0.0.3", + "version": "0.0.4", "private": false, "type": "module", "main": "./index.mjs", diff --git a/packages/cloudflare-workers-ai/src/index.mjs b/packages/cloudflare-workers-ai/src/index.mjs index 60105d2..306fc6f 100644 --- a/packages/cloudflare-workers-ai/src/index.mjs +++ b/packages/cloudflare-workers-ai/src/index.mjs @@ -21,6 +21,12 @@ const PAID_ONLY_MODELS = new Set([ ]); const FREE_ALLOCATION_NEURONS = 10000; // per day, both plans const DAY_MS = 24 * 60 * 60 * 1000; +const DAY_S = 86400; // magpie's UsageWindow.span unit is seconds, not ms +const SPENT_ALLOCATION_CODE = 3036; // "you have used up your daily free allocation" + +function nextUtcMidnight(now = Date.now()) { + return new Date((Math.floor(now / DAY_MS) + 1) * DAY_MS); +} function checkedURL(value) { const url = new URL(value); @@ -327,20 +333,46 @@ export async function CloudflareWorkersAIPlugin(_input, options = {}) { } } - return fetchImpl(targetURL, { + const resp = await fetchImpl(targetURL, { method: req.method, headers, body, signal: init?.signal ?? req.signal, redirect: "error", }); + if (resp.status !== 429) return resp; + // A spent daily free allocation is refused until 00:00 UTC, but + // Cloudflare's 429 says nothing of when (no Retry-After, no + // timestamp), so magpie would retry every 15 minutes until + // midnight. A 3036 is exactly that refusal — answer it with the + // real rest. Any other 429 is transient and keeps its own words: + // a day-long Retry-After on a plain rate limit would bench a + // working account for hours. + const text = await resp.text().catch(() => ""); + let spentAllocation = false; + try { + spentAllocation = (JSON.parse(text)?.errors ?? []).some( + (e) => e?.code === SPENT_ALLOCATION_CODE, + ); + } catch { + /* non-JSON body: pass through */ + } + if (!spentAllocation) { + return new Response(text, { status: resp.status, statusText: resp.statusText, headers: resp.headers }); + } + const headersOut = new Headers(resp.headers); + headersOut.set("Retry-After", String(Math.max(1, Math.ceil((nextUtcMidnight() - Date.now()) / 1000)))); + return new Response(text, { status: resp.status, statusText: resp.statusText, headers: headersOut }); }, }; }, async usage(getAuth, _provider) { - // Cloudflare publishes no REST for per-account Neurons (dashboard only); - // show the repeatable free-allocation window (10,000 Neurons/day, - // resets daily 00:00 UTC) and best-effort plan detection. + // Workers AI has no REST for per-account Neurons (dashboard only), but + // the GraphQL Analytics API does: sum today's totalNeurons so the quota + // row shows the real used amount instead of a fake full allowance. + // Falls back to the repeatable free-allocation window (10,000 + // Neurons/day, resets daily 00:00 UTC) when the token lacks the + // Analytics scope or the query fails. Plan detection stays best-effort. const auth = await getAuth?.(); const acct = auth?.metadata?.accountId || accountId; if (!acct || !/^[0-9a-f]{32}$/i.test(acct)) { @@ -348,6 +380,8 @@ export async function CloudflareWorkersAIPlugin(_input, options = {}) { return { plan: "Workers Free / Paid (confirm in the dashboard)", windows: [] }; } let plan = "Workers Free / Paid (confirm in the dashboard)"; + // Only a confirmed Free plan treats the included allowance as a hard cap. + let planIsFree = false; try { const res = await fetchImpl(`https://api.cloudflare.com/client/v4/accounts/${acct}`, { headers: { authorization: `Bearer ${auth?.key ?? apiKey}` }, @@ -357,24 +391,63 @@ export async function CloudflareWorkersAIPlugin(_input, options = {}) { if (res.ok) { const info = await res.json(); const planName = info?.result?.plan?.name ?? info?.result?.plan ?? ""; - if (/free/i.test(String(planName))) plan = "Workers Free"; - else if (String(planName)) plan = String(planName); + if (/free/i.test(String(planName))) { + plan = "Workers Free"; + planIsFree = true; + } else if (String(planName)) plan = String(planName); } } catch { /* token scope not enough or network issue — keep unknown */ } - const nextUtcMidnight = new Date(Math.floor(Date.now() / DAY_MS) * DAY_MS + DAY_MS); + const nextMidnight = nextUtcMidnight(); + let used = null; + try { + const res = await fetchImpl("https://api.cloudflare.com/client/v4/graphql", { + method: "POST", + headers: { + authorization: `Bearer ${auth?.key ?? apiKey}`, + "content-type": "application/json", + }, + body: JSON.stringify({ + query: + 'query { viewer { accounts(filter: {accountTag: "' + acct + + '"}) { aiInferenceAdaptiveGroups(limit: 100, filter: {datetimeHour_geq: "' + + new Date(nextMidnight.getTime() - DAY_MS).toISOString() + '", datetimeHour_lt: "' + nextMidnight.toISOString() + + '"}) { sum { totalNeurons } } } } }', + }), + redirect: "error", + signal: AbortSignal.timeout(15_000), + }); + if (res.ok) { + const info = await res.json(); + const rows = info?.data?.viewer?.accounts?.[0]?.aiInferenceAdaptiveGroups; + // An empty bucket list is a real zero (nothing ran today); a + // missing list or an error payload means we could not read usage. + if (Array.isArray(rows) && !info.errors?.length) { + used = rows.reduce((s, r) => s + (Number(r?.sum?.totalNeurons) || 0), 0); + } + } + } catch { + /* no Analytics scope, rate limit or network issue — keep unknown */ + } return { plan, windows: [ { name: "Neurons/day (free allowance)", - span: DAY_MS, - resetsAt: nextUtcMidnight.toISOString(), - amount: null, + span: DAY_S, + resetsAt: nextMidnight.toISOString(), + amount: used, + // Aside keeps Paid/unknown plans routable while showing the free allowance. + ...(used !== null + ? { used: Math.min(100, (100 * used) / FREE_ALLOCATION_NEURONS), aside: !planIsFree } + : {}), limit: FREE_ALLOCATION_NEURONS, unit: "neurons", - display: "≤10,000 Neurons/day; exact usage is on the Cloudflare dashboard (no public API)", + display: + used === null + ? "≤10,000 Neurons/day; exact usage is on the Cloudflare dashboard (grant Account Analytics → Read to see it here)" + : "", }, ], }; diff --git a/packages/cloudflare-workers-ai/test/plugin.test.mjs b/packages/cloudflare-workers-ai/test/plugin.test.mjs index 039bf9f..372c4a4 100644 --- a/packages/cloudflare-workers-ai/test/plugin.test.mjs +++ b/packages/cloudflare-workers-ai/test/plugin.test.mjs @@ -231,7 +231,7 @@ test("usage reports free-allocation window with next UTC midnight reset", async assert.equal(w.unit, "neurons"); assert.equal(new Date(w.resetsAt).getUTCHours(), 0); assert.equal(new Date(w.resetsAt).getUTCMinutes(), 0); - assert.equal(w.span, 86400_000); + assert.equal(w.span, 86400, "span is in seconds per the magpie plugin contract"); }); test("paid-only models are flagged (Paid) in config and provider.models", async () => { @@ -325,3 +325,201 @@ test("usage returns the fallback plan for an invalid accountId (no API call)", a assert.equal(u.windows.length, 0, "invalid Account ID must not reach the API path"); assert.equal(apiCalled, "", "no /accounts/ request was made"); }); + +function usageOpts(graphqlResponder, plan = "Workers Free") { + const seen = []; + const o = opts(); + o.fetchImpl = async (url, init) => { + if (typeof url === "string" && url.includes("models.dev")) { + return new Response(JSON.stringify(fakeCatalog())); + } + if (typeof url === "string" && url.endsWith("/graphql")) { + seen.push({ url, init, body: JSON.parse(init?.body ?? "{}") }); + return graphqlResponder(); + } + return new Response(JSON.stringify({ result: { plan: { name: plan } } }), { status: 200 }); + }; + return { o, seen }; +} + +test("usage sums today's totalNeurons from GraphQL Analytics into amount", async () => { + const { o, seen } = usageOpts(() => + new Response(JSON.stringify({ + data: { + viewer: { + accounts: [{ + aiInferenceAdaptiveGroups: [ + { sum: { totalNeurons: 6659.43 } }, + { sum: { totalNeurons: 3802.57 } }, + ], + }], + }, + }, + }), { status: 200 }) + ); + const plugin = await CloudflareWorkersAIPlugin({}, o); + const u = await plugin.auth.usage(async () => ({ + key: "tok", + metadata: { accountId: ACCOUNT_ID }, + })); + assert.equal(u.plan, "Workers Free"); + assert.equal(u.windows.length, 1); + const w = u.windows[0]; + assert.equal(w.amount, 10462, "bucket sums must land in amount"); + assert.equal(w.limit, 10000); + assert.equal(w.used, 100, "over the limit clamps to 100% used, which the router benches on"); + assert.equal(w.aside, false, "a confirmed Free plan stops routing at its daily limit"); + assert.equal(w.display, "", "known usage uses magpie's count and Used / Left toggle"); + const call = seen[0]; + assert.ok(call, "GraphQL Analytics endpoint was queried"); + assert.equal(new URL(call.url).pathname, "/client/v4/graphql"); + assert.equal(call.init.method, "POST"); + assert.equal(call.init.headers.authorization, "Bearer tok"); + const midnight = new Date(Math.floor(Date.now() / 86400_000) * 86400_000); + assert.ok( + call.body.query.includes(`datetimeHour_geq: "${midnight.toISOString()}"`), + "window starts at today's UTC midnight" + ); + assert.ok(call.body.query.includes(`accountTag: "${ACCOUNT_ID}"`)); +}); + +test("usage does not order an aggregate by an unselected dimension", async () => { + const { o, seen } = usageOpts(() => new Response(JSON.stringify({ data: null, errors: [] }))); + const plugin = await CloudflareWorkersAIPlugin({}, o); + await plugin.auth.usage(async () => ({ key: "tok", metadata: { accountId: ACCOUNT_ID } })); + assert.doesNotMatch(seen[0].body.query, /orderBy:/, + "Cloudflare rejects datetimeHour ordering when the query selects only sum.totalNeurons"); +}); + +test("usage keeps amount null when the token lacks Analytics scope", async () => { + const { o } = usageOpts(() => new Response("authentication error", { status: 403 })); + const plugin = await CloudflareWorkersAIPlugin({}, o); + const u = await plugin.auth.usage(async () => ({ + key: "tok", + metadata: { accountId: ACCOUNT_ID }, + })); + assert.equal(u.windows.length, 1, "window still shown"); + assert.equal(u.windows[0].amount, null, "unknown usage must stay null, not zero"); + assert.match(u.windows[0].display, /Account Analytics/); +}); + +test("usage treats a GraphQL error payload as unknown, and an empty day as zero", async () => { + const errPayload = usageOpts(() => + new Response(JSON.stringify({ errors: [{ code: 10000, message: "no access" }] }), { status: 200 }) + ); + const plugin = await CloudflareWorkersAIPlugin({}, errPayload.o); + const u = await plugin.auth.usage(async () => ({ key: "tok", metadata: { accountId: ACCOUNT_ID } })); + assert.equal(u.windows[0].amount, null, "errors payload must not read as zero"); + + const emptyDay = usageOpts(() => + new Response(JSON.stringify({ + data: { viewer: { accounts: [{ aiInferenceAdaptiveGroups: [] }] } }, + }), { status: 200 }) + ); + const p2 = await CloudflareWorkersAIPlugin({}, emptyDay.o); + const u2 = await p2.auth.usage(async () => ({ key: "tok", metadata: { accountId: ACCOUNT_ID } })); + assert.equal(u2.windows[0].amount, 0, "an empty bucket list is a real zero"); + assert.equal(u2.windows[0].used, 0, "an unused day is a numeric reading, not a text-only row"); + assert.equal(u2.windows[0].display, ""); + + const partial = usageOpts(() => + new Response(JSON.stringify({ + data: { viewer: { accounts: [{ aiInferenceAdaptiveGroups: [{ sum: { totalNeurons: 1234 } }] }] } }, + errors: [{ message: "some buckets timed out" }], + }), { status: 200 }) + ); + const p3 = await CloudflareWorkersAIPlugin({}, partial.o); + const u3 = await p3.auth.usage(async () => ({ key: "tok", metadata: { accountId: ACCOUNT_ID } })); + assert.equal(u3.windows[0].amount, null, "a partial reply — rows and errors together — is not a read"); +}); + +test("a full window does not bench an account whose plan is unknown", async () => { + // GET /accounts/{id} names no plan for this token, and the day is spent: + // the card gets a percentage, but the window is set aside from routing: + // past the allowance a Paid account is billed, not refused. + const o = opts(); + o.fetchImpl = async (url, init) => { + if (typeof url === "string" && url.includes("models.dev")) { + return new Response(JSON.stringify(fakeCatalog())); + } + if (typeof url === "string" && url.endsWith("/graphql")) { + return new Response(JSON.stringify({ + data: { viewer: { accounts: [{ aiInferenceAdaptiveGroups: [{ sum: { totalNeurons: 10462 } }] }] } }, + }), { status: 200 }); + } + return new Response(JSON.stringify({ result: {} }), { status: 200 }); // no plan in the answer + }; + const plugin = await CloudflareWorkersAIPlugin({}, o); + const u = await plugin.auth.usage(async () => ({ key: "tok", metadata: { accountId: ACCOUNT_ID } })); + assert.equal(u.plan, "Workers Free / Paid (confirm in the dashboard)"); + const w = u.windows[0]; + assert.equal(w.amount, 10462, "the card still sees the real usage"); + assert.equal(w.used, 100, "the card can switch between Used and Left"); + assert.equal(w.aside, true, "an unknown plan must not be benched on its free allowance"); + assert.equal(w.display, ""); +}); + +test("Paid plan shows the free allowance percentage without stopping paid usage", async () => { + const { o } = usageOpts(() => new Response(JSON.stringify({ + data: { viewer: { accounts: [{ aiInferenceAdaptiveGroups: [{ sum: { totalNeurons: 23821.83 } }] }] } }, + })), "Workers Paid"); + const plugin = await CloudflareWorkersAIPlugin({}, o); + const { windows: [w] } = await plugin.auth.usage(async () => ({ key: "tok", metadata: { accountId: ACCOUNT_ID } })); + assert.equal(w.amount, 23821.83, "the count includes usage above the free allocation"); + assert.equal(w.limit, 10000); + assert.equal(w.used, 100); + assert.equal(w.aside, true, "the included allowance is not a Paid plan's hard cap"); + assert.equal(w.display, ""); +}); + +function loaderOpts(statusResponder) { + const o = opts(); + o.fetchImpl = async (url) => { + if (typeof url === "string" && url.includes("models.dev")) { + return new Response(JSON.stringify(fakeCatalog())); + } + return statusResponder(url); + }; + return o; +} + +test("a 429 code 3036 comes back with Retry-After until next UTC midnight", async () => { + const spentBody = JSON.stringify({ + errors: [{ code: 3036, message: "you have used up your daily free allocation of 10,000 neurons" }], + }); + const plugin = await CloudflareWorkersAIPlugin({}, loaderOpts(() => new Response(spentBody, { status: 429 }))); + const r = await plugin.auth.loader(async () => ({ key: "tok", metadata: { accountId: ACCOUNT_ID } })); + // the plugin reads the clock inside fetch; sampling on both sides of the + // call bounds that read, so a whole-second boundary between them cannot + // push Retry-After past the window + const before = Date.now(); + const resp = await r.fetch(`${r.baseURL}/chat/completions`, { + method: "POST", + body: JSON.stringify({ model: "@cf/meta/llama-3-8b-instruct", messages: [] }), + }); + const after = Date.now(); + assert.equal(resp.status, 429); + assert.deepEqual(JSON.parse(await resp.text()), JSON.parse(spentBody), "body preserved verbatim"); + const retryAfter = Number(resp.headers.get("retry-after")); + const secondsToMidnight = (t) => Math.ceil(((Math.floor(t / 86400_000) + 1) * 86400_000 - t) / 1000); + assert.ok( + secondsToMidnight(after) <= retryAfter && retryAfter <= secondsToMidnight(before), + `Retry-After ${retryAfter} must be the seconds to next UTC midnight from a clock read inside fetch (${secondsToMidnight(after)}–${secondsToMidnight(before)})`, + ); +}); + +test("any other 429 keeps its own words: no Retry-After is added", async () => { + // a plain rate limit is transient — a day-long rest until UTC midnight + // would bench a working account for hours + const plugin = await CloudflareWorkersAIPlugin({}, loaderOpts(() => + new Response(JSON.stringify({ errors: [{ code: 700003, message: "rate limited" }] }), { status: 429 }) + )); + const r = await plugin.auth.loader(async () => ({ key: "tok", metadata: { accountId: ACCOUNT_ID } })); + const resp = await r.fetch(`${r.baseURL}/chat/completions`, { + method: "POST", + body: JSON.stringify({ model: "@cf/meta/llama-3-8b-instruct", messages: [] }), + }); + assert.equal(resp.status, 429); + assert.equal(resp.headers.get("retry-after"), null, "only a 3036 may name the midnight rest"); + assert.equal(JSON.parse(await resp.text()).errors[0].code, 700003, "body preserved"); +});