From 7ebab07c2aa89b9a2ce425862dd98abf01620372 Mon Sep 17 00:00:00 2001 From: sj1547139223 <146150939+sj1547139223@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:25:00 +0800 Subject: [PATCH] gumloop 0.1.0: API key sign-in, account models and credit estimates (#967) Gumloop as a provider for magpie and OpenCode: API key + user ID sign-in, the account's own model list (bare catalog ids mapped back to provider routes, per account), streaming and tool calls, a missing system prompt supplied for Muse and MiniMax M3.1 Flash, and a locally calibrated credit estimate (an estimate, not an invoice). The ledger is written only under magpie's config directory (kept in memory in OpenCode), a failed read is unknown and never written over, and updates go through a filesystem ticket lock (bakery) across plugin hosts. Only a 403 that names the key reads as an expired sign-in, and only Gumloop's assumed 403 credit_limit_exceeded reads as out of credits. The last change checks lock contention at least once after a stall, so an uncontended update that took more than 250 ms to publish its ticket is no longer dropped. Ran, at the reviewed head 2173d784 (WSL magpie-desktop, Bun 1.4.2, fresh HOME; Windows 11, Bun 1.4.2, fresh HOME and USERPROFILE): - bun test packages/gumloop: 87 pass, 0 fail (3x WSL, 2x Windows); the 200-charge overlap test 10x WSL and 5x Windows green; check.mjs exit 0. - Merged with origin/main 017cd73e: package 87 pass, check.mjs exit 0, root bun test 8294 pass, 0 fail. - A 300 ms stall injected before the contention loop in production (no test hook): the three charge tests stay green; with the loop back to `while` they all go red (the charge is dropped). Broken by hand, one at a time, each restored and touched: - loop back to `while`: 3 red, the new stall test among them; - no staleness check, no ticket-0 wait, no ledger .tmp cleanup, a 2000 ms wait, ENOENT counted as stale: each red, as in the earlier reviews; - the old hook-only deadline reset put back together with `while`: the new test stays green (the hook hid the bug), so the reset must stay out; - retryFs back to the shared deadline: green (a Windows sharing error after a stall; not reproducible on Linux). Not tried: Gumloop's real API, a real magpie or OpenCode session with the plugin. The npm first publish of the new package is the owner's. Co-authored-by: sj1547139223 <146150939+sj1547139223@users.noreply.github.com> --- README.md | 1 + packages/gumloop/LICENSE | 21 + packages/gumloop/README.md | 163 ++++++ packages/gumloop/compatibility.test.mjs | 374 +++++++++++++ packages/gumloop/gumloop.mjs | 518 ++++++++++++++++++ packages/gumloop/index.mjs | 646 +++++++++++++++++++++++ packages/gumloop/index.test.mjs | 435 ++++++++++++++++ packages/gumloop/opencode.mjs | 1 + packages/gumloop/opencode2.mjs | 596 +++++++++++++++++++++ packages/gumloop/package.json | 36 ++ packages/gumloop/regression.test.mjs | 662 ++++++++++++++++++++++++ registry.json | 2 + 12 files changed, 3455 insertions(+) create mode 100644 packages/gumloop/LICENSE create mode 100644 packages/gumloop/README.md create mode 100644 packages/gumloop/compatibility.test.mjs create mode 100644 packages/gumloop/gumloop.mjs create mode 100644 packages/gumloop/index.mjs create mode 100644 packages/gumloop/index.test.mjs create mode 100644 packages/gumloop/opencode.mjs create mode 100644 packages/gumloop/opencode2.mjs create mode 100644 packages/gumloop/package.json create mode 100644 packages/gumloop/regression.test.mjs diff --git a/README.md b/README.md index 5baea60..e6aa6b8 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ vendor service and makes its requests. The packages work in OpenCode and in | [factory](packages/factory) | Factory (Droid) subscription | `factory` | | [gcp-ai](packages/gcp-ai) | Google Cloud Vertex AI with your own gcloud / ADC login (needs `gcloud` and Chrome), plus the project's promotional credits | `gcp-ai` | | [grok](packages/grok) | Grok (SuperGrok / X Premium+), through the Grok Build CLI's sign-in | `grok` | +| [gumloop](packages/gumloop) | Gumloop API key and user ID, with account models and a local credit estimate | `gumloop` | | [inkstone](packages/inkstone) | (Unofficial) 书生·端砚 Token Plan: browser sign-in gives the ink-credit balance, the 5-hour and 7-day windows and the credit packs, and creates an `ink-*` API key to serve the plan's models for chat | `intern-inkstone` | | [joycode](packages/joycode) | JoyCode IDE credits with JD account browser sign-in, live models and credit multipliers (unofficial) | `joycode` | | [doubao-work](packages/doubao-work) | Doubao Work (豆包工作), whose agent runs in the cloud with no API, through the Doubao desktop app driven the way a person uses it (macOS, Windows) | `doubao-work` | diff --git a/packages/gumloop/LICENSE b/packages/gumloop/LICENSE new file mode 100644 index 0000000..e6bc674 --- /dev/null +++ b/packages/gumloop/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 magpie-community contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/gumloop/README.md b/packages/gumloop/README.md new file mode 100644 index 0000000..9103bf1 --- /dev/null +++ b/packages/gumloop/README.md @@ -0,0 +1,163 @@ +# gumloop + +Gumloop ([gumloop.com](https://www.gumloop.com)) with your API key, in +[OpenCode](https://opencode.ai) and [magpie](https://usemagpie.ai). Gumloop serves +an OpenAI-compatible chat completions API at `https://ws.gumloop.com/api/v1`; this +plugin signs every request with your key and user id, so agents reach its models +like any other provider, with magpie's multi-account fallback. + +**Provider id:** `gumloop` + +## Sign-in + +Gumloop → Settings → Connectors → **Gumloop API Key**: create a key, and copy the +**User ID** shown on the same page. `magpie plugin login gumloop` (or the sign-in +button in the app) asks for: + +| Prompt | Required | Used for | +| --- | --- | --- | +| API key | yes | `Authorization: Bearer ` | +| User ID | yes | `x-auth-key: ` | +| Account email | no | names the account in magpie | +| Credits left | no | starts the credit estimate (see below) | + +The key and user id are checked against `GET api.gumloop.com/api/v1/models` before +they are kept. They are stored as `{ "type": "api", "key", "metadata": { "userId", … } }` +in magpie's `plugin-auth.json` (permissions 600). A key Gumloop refuses marks the +account for sign-in again. + +## Models + +The models your account can use, listed per account from `GET /models`: active, +unrestricted chat models that call tools. Gumloop's own router (`gumloop-chew`), +image, voice, transcription and classifier models are left out. Context is the +model's short window where Gumloop gives one, since every call bills the whole +context. + +Model ids use the account catalog's names, such as `gumloop/glm-5.3`. +The plugin translates these to the chat endpoint's route IDs (for example, +`accounts/fireworks/models/glm-5p3`). Older aliases such as `glm-5p3` still work. + +MiniMax M3 is temporarily omitted: on 2026-11-11 Gumloop's route rejected even +minimal requests with `Extra inputs are not permitted, field: 'provider'`. +MiniMax M3.1 Flash is supported. Muse and MiniMax M3.1 Flash require a nonempty +system or developer message; if none is supplied, the plugin adds "You are a +helpful assistant." Existing nonempty instructions are preserved. + +Requests are rewritten the way Gumloop takes them: `max_completion_tokens` becomes +`max_tokens`, `reasoning_effort` becomes `reasoning.effort`, streams ask for their +usage, and a model's output cap is learned from its first refusal. Set +`{"cache1h": true}` in the plugin's options to opt into a 1-hour Anthropic prompt +cache TTL on Claude requests. + +## Credits + +Gumloop's API has no balance endpoint, so the usage card is an **estimate**: + +- each call is priced from its token usage at list price (OpenRouter's prices, + re-read every 12 hours; Fireworks-hosted models at the standard Fireworks + endpoint price, excluding spot tiers; Z.AI and Gemma use their provider + endpoints; built-in + prices when OpenRouter can't be reached), at $0.005 a credit, rounded up to a + whole credit per call, as Gumloop bills; +- the result is taken off the balance you gave, from when you gave it. + +Prices and rounding are estimates, not a reconciliation with Gumloop's invoice. +Provider discounts, routing changes and unavailable live long-context rates can +make the estimate differ. Models with no known price are counted as unpriced, +not as free calls. + +Spend on gumloop.com itself (flows, Gumball) shows only when you calibrate again. +A stream stopped mid-way never reports its usage; the card counts those so you +know to recalibrate. An out-of-credits refusal sets the estimate to 0 and sends the +request to the next account. + +Gumloop does not document its credit-limit error format and no live exhaustion +response has been captured. The plugin assumes HTTP 403 with a structured +`credit_limit_exceeded` code signals an exhausted Gumloop account; HTTP 402 +responses (such as an upstream provider's `"Insufficient credits"`) pass +through without zeroing the estimate. Other chat 403s check `GET /models` with +the same credentials: HTTP 200 keeps the sign-in, HTTP 401/403 marks it +expired, and a network failure or other status leaves the original refusal +unchanged. + +To calibrate, sign in again with the credits gumloop.com shows (bottom left), or +set them in the plugin's options, applied once per value: + +```sh +magpie plugin options gumloop '{"balance": {"": 7142}, "allowance": 20000}' +``` + +`balance` is a number for every account or an object keyed by user id or email. +Each distinct `options.balance` number is applied once; if you top up back to the +same number as before, sign in again with the balance prompt (which timestamps +each calibration) or pass a different number. +`allowance` (optional, same forms) is the plan's monthly credits; with it the card +shows used / allowance instead of what is left. + +In magpie, the estimate is kept in `gumloop-ledger.json` in magpie's config +directory. In OpenCode, it is kept in memory for the session so project folders +are never written to. + +Ledger updates use a filesystem ticket lock (Lamport's bakery algorithm) and +re-read the latest data before changing it. Each attempt has a unique +`gumloop-ledger.json.lock...json` record. A complete record is +published by atomic rename, first announcing ticket selection, then its ticket. +Contenders enter in ticket/name order and remove only their own records on +release. There is no reusable shared lock pathname that competing recoverers +could accidentally unlink after a new owner acquires it. + +After a host crash, the next update removes a dead owner's lock records, +unfinished lock `.tmp` files, and leftover `gumloop-ledger.json...tmp` +files immediately when `process.kill(pid, 0)` reports `ESRCH` (no such +process), or once a file's `mtime` is older than 30 seconds (`LOCK_STALE_MS`) +even if the OS has reused that PID for another live process. Unrecognized +`gumloop-ledger.json.lock.*` filenames are ignored. Normal process exit +attempts cleanup, but recovery does not depend on exit handlers running. This +requires a coherent local filesystem; network filesystems and simultaneous +hosts using the old lock protocol are not supported. + +Acquisition waits up to 250 ms in 5 ms intervals. Windows sharing errors +on reads, renames and cleanup are retried within bounded 250 ms deadlines; +the mutation callback itself is never retried. Waiting blocks the plugin host's +JavaScript thread. A timeout or unrecoverable filesystem error skips that +estimate update without failing the chat, so the estimate may be too high. +A host killed before its ledger rename may likewise lose its final update; +the previous complete ledger remains available and later requests recover. + +Short-lived hosts may terminate immediately after receiving a completion. +The plugin therefore finishes accounting before releasing terminal SSE frames +or a JSON response within the existing 4-million-character parsing limit. +Ordinary SSE content still streams as it arrives; response bytes are preserved. +Complete ordinary lines are released even when the next line is partial. +SSE accounting finishes at `[DONE]`, or EOF when that marker is absent. +The tap retains at most 256 KiB of incomplete SSE line or terminal-tail bytes. +If that limit is exceeded, it records an unbilled estimate once before releasing +the held bytes, then passes through the remaining stream with backpressure. +It does not charge a provisional usage value from an oversized terminal tail. +Oversized JSON retains the existing pass-through and unbilled-estimate behavior. + +## Install + +```sh +magpie plugin add ./packages/gumloop +magpie plugin login gumloop +magpie provider test gumloop +magpie quota +``` + +In OpenCode, add the package under `plugin` and sign in with `opencode auth login`. +The package includes separate OpenCode 1.x and 2.x entrypoints; email and balance +remain optional in both login flows. + +## Development + +```sh +bun test +bun scripts/check.mjs gumloop # in a magpie-community/plugins checkout +``` + +Thanks to [vwfactory-dsh](https://github.com/cjj66619/vwfactory-dsh), whose +Gumloop relay worked out the API, the request rewrites and the billing rules. + +MIT. Not affiliated with Gumloop. diff --git a/packages/gumloop/compatibility.test.mjs b/packages/gumloop/compatibility.test.mjs new file mode 100644 index 0000000..b60f5c2 --- /dev/null +++ b/packages/gumloop/compatibility.test.mjs @@ -0,0 +1,374 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { existsSync, mkdtempSync, readFileSync, rmSync, truncateSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { GumloopPlugin, _internal } from "./index.mjs" +import { MODEL_ROUTES, Store, fetchPrices, wireModel } from "./gumloop.mjs" +import * as legacy from "./opencode.mjs" +import modern, { fieldsOf } from "./opencode2.mjs" + +const json = (body, status = 200, headers = {}) => + new Response(typeof body === "string" ? body : JSON.stringify(body), { + status, + headers: { "content-type": "application/json", ...headers }, + }) +const auth = { type: "api", key: "mock-key-AAAAAAAAAAAAAAAA", metadata: { userId: "mock-user-1234" } } +const option = (value) => ({ value, status: "active", metadata: { capabilities: ["functions"] } }) + +const dirs = [] +function tempDir() { + const d = mkdtempSync(join(tmpdir(), "gumloop-compat-")) + dirs.push(d) + return d +} +afterEach(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) +}) + +describe("current Gumloop catalog", () => { + test("catalog refresh keeps wire routes and charges every supported catalog name", async () => { + const sent = [] + const p = _internal.createPlugin({ fetchImpl: async (url, init) => { + if (url.includes("api.gumloop.com")) return json({ model_groups: [{ options: Object.keys(MODEL_ROUTES).map(option) }] }) + if (url.includes("openrouter.ai")) return json({}, 503) + sent.push(JSON.parse(init.body).model) + return json({ choices: [], usage: { prompt_tokens: 20, completion_tokens: 4 } }) + } }) + const models = await p.provider.models({ models: {} }, { auth }) + expect(Object.keys(models)).toHaveLength(8) + expect(models["minimax-m3"]).toBeUndefined() + const cfg = {} + await p.config(cfg) + expect(cfg.provider.gumloop.models["minimax-m3"]).toBeUndefined() + const loaded = await p.auth.loader(async () => auth) + for (const id of Object.keys(models)) { + expect(models[id].cost.input).toBeGreaterThanOrEqual(0) + await (await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: id, messages: [{role:"user",content:"hi"}] }) })).text() + expect(sent.at(-1)).toBe(MODEL_ROUTES[id]) + } + const quota = await p.auth.usage(async () => auth) + expect(quota.windows[1].display).toBe("8 credits · 8 calls") + }) + + test("new models get priced even within the catalog price TTL", async () => { + let id = "gpt-6-sol" + let reads = 0 + const p = _internal.createPlugin({ fetchImpl: async (url) => { + if (url.includes("api.gumloop.com")) return json({model_groups:[{options:[option(id)]}]}) + reads++ + return json({data:[{id:"openai/gpt-future",pricing:{prompt:"0.000001",completion:"0.000002"}}]}) + } }) + await p.provider.models({models:{}}, {auth}) + id = "gpt-future" + const models = await p.provider.models({models:{}}, {auth}) + expect(models[id].cost).toMatchObject({input:1,output:2}) + expect(reads).toBe(2) + await p.provider.models({models:{}}, {auth}) + expect(reads).toBe(2) + }) + + test("unknown prices stay visibly unpriced", async () => { + const p = _internal.createPlugin({fetchImpl: async url => url.includes("api.gumloop.com") ? + json({model_groups:[{options:[option("unknown-model")]}]}) : url.includes("openrouter.ai") ? + json({data:[]}) : json({usage:{prompt_tokens:20,completion_tokens:4}})}) + await p.provider.models({models:{}},{auth}) + const loaded = await p.auth.loader(async()=>auth) + await (await loaded.fetch(`${loaded.baseURL}/chat/completions`,{method:"POST",body:JSON.stringify({model:"unknown-model"})})).text() + expect((await p.auth.usage(async()=>auth)).windows[1].display).toContain("1 unpriced") + }) +}) + +describe("provider prices", () => { + test("Fireworks uses its standard endpoint, not spot or another host", async () => { + const pricing = (prompt) => ({prompt,completion:"0.0000044"}) + const table = await fetchPrices(async url => url.endsWith("/endpoints") ? json({data:{endpoints:[ + {provider_name:"Fireworks",tag:"fireworks/spot",pricing:pricing("0.00000098")}, + {provider_name:"Wafer",tag:"wafer",pricing:pricing("0.0000000699")}, + {provider_name:"Fireworks",tag:"fireworks",pricing:pricing("0.0000014")}, + ]}}) : json({data:[{id:"z-ai/glm-5.3",pricing:pricing("0.0000000699")}]}), ["glm-5.3"]) + expect(table["glm-5.3"].p.slice(0,2)).toEqual([1.4,4.4]) + }) + test("missing provider endpoints leave route fallback intact", async () => { + const table = await fetchPrices(async url => url.endsWith("/endpoints") ? json({},503) : + json({data:[{id:"z-ai/glm-5.3",pricing:{prompt:"0.0000000699",completion:"0.0000014"}}]}),["glm-5.3"]) + expect(table["glm-5.3"]).toBeUndefined() + const store = new Store() + store.setPrices(table) + expect(store.price("glm-5.3").p.slice(0,2)).toEqual([1.4,4.4]) + expect(store.price("glm-5.3")).toEqual(store.price(wireModel("glm-5.3"))) + }) + test("Muse Wonder maps to OpenRouter's unversioned ID", async () => { + const table = await fetchPrices(async()=>json({data:[{id:"meta/muse-wonder",pricing:{prompt:"0.000004",completion:"0.00002"}}]}),["muse-wonder-1.0"]) + expect(table["muse-wonder-1.0"].p.slice(0,2)).toEqual([4,20]) + }) +}) + +describe("request and host compatibility", () => { + test("source errors and reader cancellation propagate upstream and report unbilled stops without an abort signal", async () => { + for (const withSignal of [false, true]) { + for (const mode of ["error", "cancel"]) { + let source + let upstreamCancelled = false + const calls = [] + const stream = new ReadableStream({ + start(c) { + source = c + c.enqueue(new TextEncoder().encode('data: {"choices":[{"delta":{"content":"hi"}}]}\n\n')) + }, + cancel() { + upstreamCancelled = true + }, + }) + const ac = new AbortController() + const tapped = _internal.tapUsage(stream, true, withSignal ? ac.signal : undefined, (...args) => calls.push(args)) + const reader = tapped.getReader() + await reader.read() + if (mode === "error") { + source.error(new Error("connection reset")) + await expect(reader.read()).rejects.toThrow("connection reset") + } else { + await reader.cancel() + } + await new Promise((resolve) => setTimeout(resolve, 0)) + if (mode === "cancel") expect(upstreamCancelled).toBe(true) + // Must already be recorded before any abort signal fires + expect(calls).toEqual([[undefined, true]]) + if (withSignal) { + ac.abort() + expect(calls).toEqual([[undefined, true]]) + } + } + } + }) + + test("Muse and MiniMax Flash get a nonempty system prompt only when needed and respect developer role", () => { + for (const model of ["meta/muse-spark-1.3", "meta/muse-wonder-1.0", "minimax/minimax-m3.1-flash"]) { + const normalize = (messages) => _internal.normalize({ model, messages }, { cache1h: true }).messages + expect(normalize([{ role: "user", content: "hi" }])[0]).toEqual({ role: "system", content: "You are a helpful assistant." }) + const fromBlank = normalize([{ role: "system", content: " " }, { role: "user", content: "hi" }]) + expect(fromBlank).toEqual([ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: "hi" }, + ]) + const existing = [{ role: "system", content: "Custom instruction" }, { role: "user", content: "hi" }] + expect(normalize([...existing])).toEqual(existing) + const dev = [{ role: "developer", content: "Follow repo rules" }, { role: "user", content: "hi" }] + expect(normalize([...dev])).toEqual(dev) + const blankDev = normalize([{ role: "developer", content: " " }, { role: "user", content: "hi" }]) + expect(blankDev).toEqual([ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: "hi" }, + ]) + const blocks = [{ role: "system", content: [{ type: "text", text: "Custom" }] }] + expect(normalize([...blocks])).toEqual(blocks) + } + expect(_internal.normalize({ model: "gpt-6-sol", messages: [] }, { cache1h: true }).messages).toEqual([]) + expect(_internal.normalize({ model: "gpt-6-sol", reasoning_effort: "none" }).reasoning).toEqual({ effort: "none" }) + }) + + test("OpenCode directory is never written to unless running in magpie", async () => { + const projectDir = tempDir() + const p1 = _internal.createPlugin({ + directory: projectDir, + options: { balance: 7000 }, + fetchImpl: async (url) => + url.includes("/models") ? json({ model_groups: [{ options: [option("gpt-6-sol")] }] }) : json({ usage: { prompt_tokens: 10, completion_tokens: 5 } }), + }) + const card = await p1.auth.usage(async () => auth) + expect(card.balance).toBe("7000 credits") + const loaded = await p1.auth.loader(async () => auth) + await (await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) })).text() + expect(existsSync(join(projectDir, "gumloop-ledger.json"))).toBe(false) + + const p2 = await GumloopPlugin({ directory: projectDir }, { balance: 7000 }) + await p2.auth.loader(async () => auth) + expect(existsSync(join(projectDir, "gumloop-ledger.json"))).toBe(false) + + const magpieDir = tempDir() + const p3 = await GumloopPlugin({ directory: magpieDir, magpie: {} }, { balance: 7000 }) + await p3.auth.loader(async () => auth) + expect(existsSync(join(magpieDir, "gumloop-ledger.json"))).toBe(true) + }) + + test("corrupt or truncated ledger is never overwritten or re-anchored", async () => { + const dir = tempDir() + const file = join(dir, "gumloop-ledger.json") + let t = 1_800_000_000_000 + const make = () => + _internal.createPlugin({ + directory: dir, + magpie: true, + now: () => t, + options: { balance: 7000 }, + fetchImpl: async (url) => + url.includes("api.gumloop.com") + ? json({ model_groups: [{ options: [option("gpt-6-sol")] }] }) + : url.includes("openrouter.ai") + ? json({ data: [] }) + : json({ choices: [], usage: { prompt_tokens: 100, completion_tokens: 50 } }), + }) + const p1 = make() + const l1 = await p1.auth.loader(async () => auth) + await (await l1.fetch(`${l1.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) })).text() + expect((await p1.auth.usage(async () => auth)).balance).toBe("6999 credits") + + // Truncate the ledger on disk to 40 bytes (corrupt JSON) + truncateSync(file, 40) + const truncatedBytes = readFileSync(file, "utf8") + expect(truncatedBytes.length).toBe(40) + + t += 60_000 + // In the same process, the last good in-memory copy is kept and disk is not overwritten + await (await l1.fetch(`${l1.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) })).text() + expect(readFileSync(file, "utf8")).toBe(truncatedBytes) + expect((await p1.auth.usage(async () => auth)).balance).toBe("6999 credits") + + // In a new process reading the truncated file, neither calibrate nor charge overwrites it + const p2 = make() + const l2 = await p2.auth.loader(async () => auth) + await (await l2.fetch(`${l2.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) })).text() + expect(readFileSync(file, "utf8")).toBe(truncatedBytes) + }) + + test("unrelated 403s, upstream 400s and rate-limit 429s do not expire the key or zero the balance", async () => { + let chatResp = json({ error: { message: "You are not authorized to use claude-opus-5-5 on your current plan" } }, 403) + const p = _internal.createPlugin({ + options: { balance: 5000 }, + fetchImpl: async (url) => { + if (url.includes("api.gumloop.com/api/v1/models")) return json({ model_groups: [{ options: [option("gpt-6-sol")] }] }) + if (url.includes("openrouter.ai")) return json({ data: [] }) + return chatResp + }, + }) + const loaded = await p.auth.loader(async () => auth) + + // Plan 403 keeps status 403 and does not mark sign-in expired + const rPlan = await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "claude-opus-5-5", messages: [] }) }) + expect(rPlan.status).toBe(403) + expect(rPlan.headers.get("x-magpie-sign-in")).toBe("kept") + + // Upstream Anthropic 400 credit error passes through as 400 and keeps balance intact + chatResp = json({ error: { message: "anthropic: Your credit balance is too low to access the Anthropic API." } }, 400) + const rUp = await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "claude-sonnet-5-5", messages: [] }) }) + expect(rUp.status).toBe(400) + expect((await p.auth.usage(async () => auth)).balance).toBe("5000 credits") + + // Rate-limit 429 with tier_limit passes through and keeps balance intact + chatResp = json({ error: { code: "tier_limit", message: "Rate limit reached for tier_limit" } }, 429) + const rRate = await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) }) + expect(rRate.status).toBe(429) + expect((await p.auth.usage(async () => auth)).balance).toBe("5000 credits") + + // Upstream OpenRouter-style 402 passes through as 402 and keeps balance intact + chatResp = json({ error: { code: 402, message: "Insufficient credits" } }, 402) + const r402 = await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) }) + expect(r402.status).toBe(402) + expect((await p.auth.usage(async () => auth)).balance).toBe("5000 credits") + + // Assumed credit_limit_exceeded 403 becomes 429 naming HTTP 403 and zeroes estimate + chatResp = json({ error: { code: "credit_limit_exceeded", message: "You have reached your credit limit." } }, 403) + const rCred = await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) }) + expect(rCred.status).toBe(429) + expect(await rCred.text()).toContain("from HTTP 403") + expect((await p.auth.usage(async () => auth)).balance).toBe("0 credits") + }) + + test("per-account aliases stay isolated across accounts", async () => { + const authA = { type: "api", key: "mock-key-AAAAAAAAAAAAAAAA", metadata: { userId: "user-A" } } + const authB = { type: "api", key: "mock-key-BBBBBBBBBBBBBBBB", metadata: { userId: "user-B" } } + const sent = [] + const p = _internal.createPlugin({ + fetchImpl: async (url, init) => { + const h = new Headers(init?.headers) + if (url.includes("api.gumloop.com/api/v1/models")) { + const uid = h.get("x-auth-key") + return json({ model_groups: [{ options: [option(uid === "user-A" ? "vendorA/foo" : "vendorB/foo")] }] }) + } + if (url.includes("openrouter.ai")) return json({ data: [] }) + const body = JSON.parse(init.body) + sent.push({ uid: h.get("x-auth-key"), model: body.model }) + return json({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 5 } }) + }, + }) + await p.provider.models({ models: {} }, { auth: authA }) + await p.provider.models({ models: {} }, { auth: authB }) + const loadA = await p.auth.loader(async () => authA) + const loadB = await p.auth.loader(async () => authB) + await (await loadA.fetch(`${loadA.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "foo", messages: [] }) })).text() + await (await loadB.fetch(`${loadB.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "foo", messages: [] }) })).text() + expect(sent).toEqual([ + { uid: "user-A", model: "vendorA/foo" }, + { uid: "user-B", model: "vendorB/foo" }, + ]) + }) + + test("streams with application/octet-stream are charged and oversized JSON replies count as unbilled", async () => { + let mode = "octet" + const p = _internal.createPlugin({ + fetchImpl: async (url) => { + if (url.includes("api.gumloop.com")) return json({ model_groups: [{ options: [option("gpt-6-sol")] }] }) + if (url.includes("openrouter.ai")) return json({ data: [] }) + if (mode === "octet") { + return new Response('data: {"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5}}\n\ndata: [DONE]\n\n', { + status: 200, + headers: { "content-type": "application/octet-stream" }, + }) + } + return new Response(`{"padding":"${"x".repeat(4_100_000)}","usage":{"prompt_tokens":10,"completion_tokens":5}}`, { + status: 200, + headers: { "content-type": "application/json" }, + }) + }, + }) + const loaded = await p.auth.loader(async () => auth) + await (await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", stream: true, messages: [] }) })).text() + let quota = await p.auth.usage(async () => auth) + expect(quota.windows[1].display).toBe("1 credits · 1 calls") + + mode = "huge-json" + await (await loaded.fetch(`${loaded.baseURL}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) })).text() + quota = await p.auth.usage(async () => auth) + expect(quota.windows[1].display).toContain("1 stopped without usage") + }) + + test("OpenRouter failures back off instead of refetching on every usage read", async () => { + let orCalls = 0 + let t = 1_800_000_000_000 + const p = _internal.createPlugin({ + now: () => t, + fetchImpl: async (url) => { + if (url.includes("api.gumloop.com")) return json({ model_groups: [{ options: [option("gpt-6-sol")] }] }) + if (url.includes("openrouter.ai")) { + orCalls++ + return json({}, 503) + } + return json({}) + }, + }) + for (let i = 0; i < 5; i++) await p.auth.usage(async () => auth) + expect(orCalls).toBe(1) + t += 6 * 60 * 1000 + await p.auth.usage(async () => auth) + expect(orCalls).toBe(2) + }) + + test("late anchor after more than 500 calls still counts every call made since the anchor timestamp", () => { + let t = 100 + const s = new Store(undefined, () => t) + for (let i = 1; i <= 600; i++) { + t = i + s.change("u", (a) => Store.spend(a, 1, i)) + } + expect(s.anchor("u", 1000, "login:50", 50)).toBe(true) + expect(s.remaining("u")).toBe(450) + }) + + test("OpenCode entrypoints expose plugins and keep optional fields optional", async () => { + expect(Object.keys(legacy)).toEqual(["GumloopPlugin"]) + expect(modern.id).toBe("@magpie-community/opencode-gumloop-auth") + expect(typeof modern.setup).toBe("function") + const p = await legacy.GumloopPlugin() + const fields = fieldsOf(p.auth.methods[0].prompts) + expect(fields.filter((f) => f.required).map((f) => f.key)).toEqual(["key", "userId"]) + }) +}) diff --git a/packages/gumloop/gumloop.mjs b/packages/gumloop/gumloop.mjs new file mode 100644 index 0000000..a1e2344 --- /dev/null +++ b/packages/gumloop/gumloop.mjs @@ -0,0 +1,518 @@ +// Gumloop's API: what an account can use, what a call costs, and what this +// plugin has spent. Nothing here signs in or holds a key; index.mjs does. +import { randomUUID } from "node:crypto" +import { mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs" +import { basename, dirname, join } from "node:path" + +export const API = "https://api.gumloop.com/api/v1" +export const WS = "https://ws.gumloop.com/api/v1" +export const OPENROUTER = "https://openrouter.ai/api/v1" + +// Gumloop bills $0.005 per credit and rounds every call up to a whole credit. +export const USD_PER_CREDIT = 0.005 +export const PRICES_TTL = 12 * 60 * 60 * 1000 +export const PRICES_RETRY_TTL = 5 * 60 * 1000 +// A credit-limit refusal keeps the account shown as out of credits this long. +export const EXHAUSTED_FOR = 12 * 60 * 60 * 1000 + +// USD per million tokens [input, output, cacheRead, cacheWrite], used until +// (or when) OpenRouter's list cannot be read. cacheWrite null = billed as input. +// From vwfactory-dsh (2026-10), supplemented with OpenRouter provider rates +// checked on 2026-11-11. These are estimates, not a Gumloop balance API. +export const FALLBACK_PRICES = { + "claude-fable-5-1": [10, 50, 0.25, 12.5], + "claude-fable-5": [10, 50, 1, 12.5], + "claude-opus-5": [5, 25, 0.5, 6.25], + "claude-sonnet-5": [2, 10, 0.2, 2.5], + "claude-haiku-4-5": [1, 5, 0.1, 1.25], + "claude-opus-5-5": [4, 20, 0.2, 5], + "claude-sonnet-5-5": [2, 10, 0.1, 2.5], + "claude-haiku-5-5": [0.1, 0.5, 0.01, 0.125], + "gpt-6-astra": [10, 50, 1, 12.5], + "gpt-6.1-sol": [2, 10, 0.1, 2.5], + "gpt-6.1-terra": [1, 5, 0.05, 1.25], + "gpt-6-sol": [2, 10, 0.2, 2.5], + "gpt-6-luna": [0.1, 0.5, 0.01, 0.125], + "grok-4.7": [2, 6, 0.5, null], + "grok-4.6": [2, 6, 0.5, null], + "meta/muse-spark-1.3": [1.25, 4.25, 0.15, null], + "meta/muse-wonder-1.0": [4, 20, 0.2, null], + "minimax/minimax-m3.1-flash": [0.15, 0.6, 0.015, null], + "accounts/fireworks/models/glm-5p3": [1.4, 4.4, 0.26, null], + "z-ai/glm-5.3-flash": [0.15, 0.5, 0.03, null], + "accounts/fireworks/routers/kimi-k3-us": [3, 15, 0.3, null], + "accounts/fireworks/models/kimi-k2p7-code": [0.95, 4, 0.19, null], + "gemini-4-argon": [2, 10, 0.1, 0.1875], + "gemini-3.1-pro-preview": [2, 12, 0.2, 0.375], + "gemini-3.8-flash": [0.825, 4.125, 0.0825, 0.04166666667], + "gemini-3.7-flash": [0.75, 3.75, 0.075, 0.04166666667], + "google/gemma-4-26b-a4b-it": [0.15, 0.6, null, null], + "accounts/fireworks/models/deepseek-v4p1-flash": [0.3, 1.2, 0.006, null], + "accounts/fireworks/models/deepseek-v4-pro-0813": [1.32, 3.96, 0.044, null], + "accounts/fireworks/models/minimax-m3": [0.3, 1.2, 0.06, null], +} + +// /models uses catalog names; /chat/completions still requires these routes. +// Verified against both Gumloop endpoints on 2026-11-11. +export const MODEL_ROUTES = { + "glm-5.3": "accounts/fireworks/models/glm-5p3", + "glm-5.3-flash": "z-ai/glm-5.3-flash", + "kimi-k3": "accounts/fireworks/routers/kimi-k3-us", + "deepseek-v4.1-flash": "accounts/fireworks/models/deepseek-v4p1-flash", + "gemma-4-26b-a4b-it": "google/gemma-4-26b-a4b-it", + "muse-spark-1.3": "meta/muse-spark-1.3", + "muse-wonder-1.0": "meta/muse-wonder-1.0", + "minimax-m3": "accounts/fireworks/models/minimax-m3", + "minimax-m3.1-flash": "minimax/minimax-m3.1-flash", +} +export const wireModel = (id) => Object.hasOwn(MODEL_ROUTES, id) ? MODEL_ROUTES[id] : id +// Gumloop currently injects an unsupported `provider` field for this route. +// Keep it out of offered models until the upstream route is repaired. +export const availableModel = (id) => wireModel(id) !== "accounts/fireworks/models/minimax-m3" + +const VENDORS = [ + [/^claude-/, "anthropic", "Anthropic"], + [/^(gpt-|o\d)/, "openai", "OpenAI"], + [/^(gemini-|gemma-)/, "google", "Google"], + [/^grok-/, "x-ai", "xAI"], + [/^deepseek/, "deepseek", "DeepSeek"], + [/^glm-/, "z-ai", "Z.AI"], + [/^kimi-/, "moonshotai", "Moonshot AI"], + [/^minimax-/, "minimax", "Minimax"], + [/^qwen/, "qwen", "Alibaba"], + [/^muse-/, "meta", "Meta"], +] + +export const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v) + +export function gumloopHeaders(key, userId) { + return { authorization: `Bearer ${key}`, "x-auth-key": userId } +} + +// parseModels reads GET /models ({model_groups: [{groupLabel, options: [...]}]}) +// into the chat models an agent can drive: active, not restricted, able to +// call tools, and not an image, voice, transcription or classifier model. +// gumloop-chew is Gumloop's own router, which bills unpredictably. +export function parseModels(body) { + if (!isObj(body) || !Array.isArray(body.model_groups)) throw new Error("Gumloop sent no model list") + const out = [] + for (const g of body.model_groups) { + for (const o of Array.isArray(g?.options) ? g.options : []) { + if (!isObj(o) || typeof o.value !== "string" || !o.value) continue + const caps = Array.isArray(o.metadata?.capabilities) ? o.metadata.capabilities : [] + if (o.status !== "active" || o.restricted || o.is_classifier_model || o.is_image_generation || o.is_voice || o.is_transcription) continue + if (!caps.includes("functions") || o.value === "gumloop-chew") continue + if (!availableModel(o.value)) continue + out.push({ + id: o.value, + name: typeof o.label === "string" && o.label ? o.label : o.value, + vision: caps.includes("vision"), + reasoning: caps.includes("reasoning") || /^claude-(opus|fable)/.test(o.value), + // Every call bills the whole context, so the short window keeps one + // long conversation from spending thousands of credits per turn. + context: Number(o.metadata?.short_context_window) || Number(o.metadata?.context_window) || 0, + }) + } + } + if (!out.length) throw new Error("Gumloop listed no usable chat models") + return out +} + +// priceRef maps a Gumloop model id to the OpenRouter ids that may price it. +// Fireworks-hosted ones ("accounts/fireworks/models/glm-5p3") are priced at +// Fireworks' endpoint, which is what Gumloop pays, not OpenRouter's cheapest. +export function priceRef(id) { + id = wireModel(id) + const fireworks = /^accounts\/fireworks\//.test(id) + let bare = id.replace(/^accounts\/fireworks\/(models|routers)\//, "") + if (bare.includes("/")) { + const provider = bare.startsWith("z-ai/") ? "Z.AI" : bare.startsWith("google/gemma-") ? "Google Vertex" : undefined + return { orIds: [...new Set([bare, bare.replace(/-\d+(\.\d+)*$/, "")])], fireworks: false, provider } + } + bare = bare.replace(/(\d)p(\d)/g, "$1.$2").replace(/-us$/, "") + const dotted = bare.replace(/(\d)-(\d)/g, "$1.$2") + const v = VENDORS.find(([re]) => re.test(bare)) + const orIds = v ? [`${v[1]}/${dotted}`, `${v[1]}/${bare}`] : [dotted, bare] + return { orIds: [...new Set(orIds)], fireworks, vendorName: v?.[2], provider: fireworks ? "Fireworks" : undefined } +} + +function perMillion(p) { + const n = (x) => (x === undefined || x === null || x === "" ? null : Number((Number(x) * 1e6).toPrecision(10))) + const out = [n(p.prompt), n(p.completion), n(p.input_cache_read), n(p.input_cache_write)] + return out[0] === null || out[1] === null || out.some((x) => x !== null && (!Number.isFinite(x) || x < 0)) ? undefined : out +} + +// priceEntry reads one OpenRouter pricing block, with its long-context tier. +export function priceEntry(pricing) { + if (!isObj(pricing)) return undefined + const base = perMillion(pricing) + if (!base) return undefined + const entry = { p: base } + const ov = Array.isArray(pricing.overrides) ? pricing.overrides.find((o) => Number(o?.min_prompt_tokens) > 0) : undefined + const long = ov ? perMillion({ ...pricing, ...ov }) : undefined + if (long) Object.assign(entry, { longAt: Number(ov.min_prompt_tokens), long }) + return entry +} + +// fetchPrices prices the given Gumloop ids from OpenRouter's public list. +export async function fetchPrices(fetchImpl, ids) { + const r = await fetchImpl(`${OPENROUTER}/models`, { signal: AbortSignal.timeout(30000) }) + if (!r.ok) throw new Error(`OpenRouter price list: HTTP ${r.status}`) + const data = (await r.json())?.data ?? [] + const byId = new Map(data.filter((m) => typeof m?.id === "string").map((m) => [m.id, m])) + const endpointCache = new Map() + const getEndpoints = (orId) => { + if (!endpointCache.has(orId)) { + endpointCache.set( + orId, + (async () => { + const er = await fetchImpl(`${OPENROUTER}/models/${orId}/endpoints`, { signal: AbortSignal.timeout(20000) }) + return er.ok ? ((await er.json())?.data?.endpoints ?? []) : [] + })().catch(() => []), + ) + } + return endpointCache.get(orId) + } + const rows = await Promise.all( + ids.map(async (id) => { + const ref = priceRef(id) + const orId = ref.orIds.find((x) => byId.has(x)) + if (!orId) return undefined + let entry + if (ref.provider) { + const eps = await getEndpoints(orId) + const ep = eps.find( + (e) => + e?.provider_name === ref.provider && + priceEntry(e.pricing) && + (ref.provider !== "Fireworks" || !e.tag || e.tag === "fireworks"), + ) + if (ep) entry = priceEntry(ep.pricing) + // Keep the known route's fallback, not another host's headline price. + if (!entry) return undefined + } + entry ??= priceEntry(byId.get(orId).pricing) + return entry ? [id, { ...entry, ref: orId }] : undefined + }), + ) + return Object.fromEntries(rows.filter(Boolean)) +} + +// usageCost prices one completion from its OpenAI-style usage block. +export function usageCost(entry, usage) { + const prompt = Number(usage?.prompt_tokens) || 0 + const out = Number(usage?.completion_tokens) || 0 + const det = isObj(usage?.prompt_tokens_details) ? usage.prompt_tokens_details : {} + const read = Number(det.cached_tokens) || 0 + const write = Number(det.cache_write_tokens ?? det.cache_creation_tokens) || 0 + const fresh = Math.max(0, prompt - read - write) + const [pin, pout, pread, pwrite] = entry.long && prompt >= entry.longAt ? entry.long : entry.p + const usd = (fresh * pin + read * (pread ?? pin) + write * (pwrite ?? pin) + out * pout) / 1e6 + return { usd, prompt, out, read, write } +} + +export const creditsFor = (usd) => (usd > 0 ? Math.ceil(usd / USD_PER_CREDIT - 1e-9) : 0) + +export function monthKey(t) { + const d = new Date(t) + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}` +} + +// Store keeps the ledger (calibrated balance and spend per account) and the +// price table in one JSON file in magpie's config directory. Every terminal +// `magpie` command runs its own plugin host beside the app's, so each change +// locks and re-reads the file first rather than trusting what this process holds. +let seq = 0 +export const LOCK_WAIT_MS = 250 +export const LOCK_STALE_MS = 30_000 +const lockWait = new Int32Array(new SharedArrayBuffer(4)) +const ownedLocks = new Set() +// Windows can temporarily reject opening/deleting a name being renamed or +// replacing a file another process is reading. Retry the filesystem operation, +// never the caller's mutation, within a monotonic deadline. +function retryFs(fn, deadline = performance.now() + LOCK_WAIT_MS) { + while (true) { + try { + return fn() + } catch (e) { + const remaining = deadline - performance.now() + if (!["EPERM", "EACCES", "EBUSY"].includes(e?.code) || remaining <= 0) throw e + Atomics.wait(lockWait, 0, 0, Math.min(5, remaining)) + } + } +} +const remove = (path, deadline) => { + try { + retryFs(() => unlinkSync(path), deadline) + } catch (e) { + if (e?.code !== "ENOENT") throw e + } +} +process.once("exit", () => { + for (const path of ownedLocks) { + try { remove(path) } catch {} + } +}) + +// Lamport's bakery lock, with one never-reused participant name per attempt. +// Publishing ticket 0 announces "choosing"; contenders then take max(ticket)+1 +// and wait for earlier (ticket, name) pairs. Atomic rename publishes complete +// records, so a crash while writing a temporary file cannot leave a partial +// participant. Local filesystem directory listings/renames must be coherent. +// +// There is deliberately no shared lock pathname to unlink. A dead owner's +// unique files can be removed by any number of recoverers without touching a +// later acquisition. ESRCH from kill(pid, 0) recovers immediately; otherwise a +// record older than LOCK_STALE_MS recovers even when the OS reused its PID. +function ledgerLock(file, onChoosing = undefined) { + const directory = dirname(file) + const base = basename(file) + const prefix = `${base}.lock.` + const tmpPrefix = `${base}.` + const name = `${process.pid}.${randomUUID()}` + const participant = join(directory, `${prefix}${name}.json`) + const temporary = join(directory, `${prefix}${name}.tmp`) + const deadline = performance.now() + LOCK_WAIT_MS + const release = () => { + for (const path of [participant, temporary]) { + try { + remove(path) + ownedLocks.delete(path) + } catch {} // normal exit or another process can retry cleanup + } + } + const publish = (ticket) => { + writeFileSync(temporary, JSON.stringify({ pid: process.pid, name, ticket }), { flag: "wx" }) + // Fully written before publication. + retryFs(() => renameSync(temporary, participant)) + } + const isAlive = (pid, alive) => { + if (!alive.has(pid)) { + try { + process.kill(pid, 0) + alive.set(pid, true) + } catch (e) { + alive.set(pid, e?.code !== "ESRCH") + } + } + return alive.get(pid) + } + const isStale = (path) => { + try { + return Date.now() - statSync(path).mtimeMs > LOCK_STALE_MS + } catch { + return false + } + } + const peers = () => { + const out = [] + const alive = new Map() + for (const entry of readdirSync(directory)) { + if (!entry.startsWith(prefix)) { + if (entry.startsWith(tmpPrefix)) { + const tmpMatch = /^([1-9]\d*)\.\d+\.tmp$/.exec(entry.slice(tmpPrefix.length)) + const pid = tmpMatch ? Number(tmpMatch[1]) : NaN + const path = join(directory, entry) + if (Number.isSafeInteger(pid) && (!isAlive(pid, alive) || isStale(path))) { + try { remove(path) } catch {} + } + } + continue + } + const match = /^([1-9]\d*)\.([a-f0-9-]{36})\.(json|tmp)$/.exec(entry.slice(prefix.length)) + const pid = match ? Number(match[1]) : NaN + if (!match || !Number.isSafeInteger(pid)) continue + const path = join(directory, entry) + if (path === participant || path === temporary) continue + if (!isAlive(pid, alive) || isStale(path)) { + remove(path) + continue + } + if (match[3] === "tmp") continue + let record + try { + record = JSON.parse(retryFs(() => readFileSync(path, "utf8"))) + } catch (e) { + if (e?.code === "ENOENT") continue // owner released after the listing + throw e + } + const peerName = `${match[1]}.${match[2]}` + if (record?.pid !== pid || record.name !== peerName || !Number.isSafeInteger(record.ticket) || record.ticket < 0) { + remove(path) + continue + } + out.push(record) + } + return out + } + try { + mkdirSync(directory, { recursive: true }) + ownedLocks.add(participant) + ownedLocks.add(temporary) + publish(0) + const ticket = Math.max(0, ...peers().map((p) => p.ticket)) + 1 + if (!Number.isSafeInteger(ticket)) throw new Error("Ledger lock ticket overflow") + onChoosing?.() + publish(ticket) + // The deadline bounds only the wait for a peer. A stalled host (GC, disk, + // antivirus) must still get one check, or an uncontended update is lost. + for (let first = true; first || performance.now() < deadline; first = false) { + const blocked = peers().some((p) => p.ticket === 0 || (p.ticket > 0 && (p.ticket < ticket || (p.ticket === ticket && p.name < name)))) + if (!blocked) return release + Atomics.wait(lockWait, 0, 0, Math.min(5, Math.max(0, deadline - performance.now()))) + } + } catch {} // estimates must not fail chat on an acquisition/filesystem error + release() + return undefined +} + +export class Store { + constructor(file, now = Date.now, onChoosing = undefined) { + this.file = file + this.now = now + this.onChoosing = onChoosing + this.mem = { accounts: {} } + this.readable = true + } + + withLock(fn) { + if (!this.file) return fn() + const release = ledgerLock(this.file, this.onChoosing) + if (!release) return undefined + // A callback runs exactly once; its error propagates after release. + try { + return fn() + } finally { + release() + } + } + + read() { + if (!this.file) { + if (!isObj(this.mem)) this.mem = {} + if (!isObj(this.mem.accounts)) this.mem.accounts = {} + this.readable = true + return this.mem + } + try { + const parsed = JSON.parse(retryFs(() => readFileSync(this.file, "utf8"))) + if (!isObj(parsed)) throw new Error("invalid ledger root") + if (!isObj(parsed.accounts)) parsed.accounts = {} + this.mem = parsed + this.readable = true + return parsed + } catch (e) { + if (e?.code === "ENOENT") { + const fresh = { accounts: {} } + this.mem = fresh + this.readable = true + return fresh + } + // Keep the last good in-memory copy on partial reads, corrupt JSON or + // permission errors so the next write never wipes the ledger. + this.readable = false + if (!isObj(this.mem)) this.mem = {} + if (!isObj(this.mem.accounts)) this.mem.accounts = {} + return structuredClone(this.mem) + } + } + + write(d) { + if (!this.file) { + this.mem = d + return + } + if (!this.readable) return + try { + mkdirSync(dirname(this.file), { recursive: true }) + const tmp = `${this.file}.${process.pid}.${++seq}.tmp` + writeFileSync(tmp, JSON.stringify(d, null, 2)) + retryFs(() => renameSync(tmp, this.file)) + this.mem = d + } catch { + // the ledger is an estimate; losing one write must not fail a request + } + } + + static account(d, uid, now) { + const a = isObj(d.accounts[uid]) ? d.accounts[uid] : (d.accounts[uid] = {}) + if (typeof a.spent !== "number") a.spent = 0 + if (!Array.isArray(a.applied)) a.applied = [] + const key = monthKey(now) + if (!isObj(a.month) || a.month.key !== key) a.month = { key, credits: 0, calls: 0, usd: 0 } + return a + } + + change(uid, fn) { + return this.withLock(() => { + const d = this.read() + if (this.file && !this.readable) return undefined + const a = Store.account(d, uid, this.now()) + const result = fn(a, d) + this.write(d) + return result + }) + } + + account(uid) { + return Store.account(this.read(), uid, this.now()) + } + + // anchor sets the balance read off gumloop.com at time `at`. Each source (a + // sign-in, an options value) is applied once, so a reload doesn't erase what + // was spent since. A balance may be applied after calls were made past `at` + // (magpie reads usage after the first requests), so those still count. + anchor(uid, balance, source, at = this.now()) { + const b = Number(balance) + if (!Number.isFinite(b) || b < 0) return false + return this.withLock(() => { + const d = this.read() + if (this.file && !this.readable) return false + const a = Store.account(d, uid, this.now()) + if (a.applied.includes(source)) return false + a.anchor = { balance: Math.round(b), at } + a.charges = (a.charges ?? []).filter(([t]) => t > at) + a.spent = a.charges.reduce((s, [, c]) => s + c, 0) + // an out-of-credits refusal after the balance was read still stands + if (!(a.exhaustedAt > at)) delete a.exhaustedAt + delete a.unbilledStops + a.applied = [...a.applied, source].slice(-20) + this.write(d) + return true + }) + } + + // spend counts credits against the balance, remembering when for anchor. + static spend(a, credits, at) { + a.spent += credits + a.charges = [...(a.charges ?? []), [at, credits]] + } + + remaining(uid) { + const a = this.account(uid) + return a.anchor ? Math.max(0, Math.floor(a.anchor.balance - a.spent + 1e-9)) : undefined + } + + prices() { + const p = this.read().prices + return isObj(p) && isObj(p.table) ? p : { at: 0, table: {} } + } + + setPrices(table, ids = Object.keys(table)) { + this.withLock(() => { + const d = this.read() + if (this.file && !this.readable) return + d.prices = { at: this.now(), table, ids, version: 2 } + this.write(d) + }) + } + + // price is the live entry for a model, else the built-in one. + price(model) { + model = wireModel(model) + const live = this.prices().table[model] + if (live?.p) return live + const fb = FALLBACK_PRICES[model] + return fb ? { p: fb } : undefined + } +} diff --git a/packages/gumloop/index.mjs b/packages/gumloop/index.mjs new file mode 100644 index 0000000..2c84fd7 --- /dev/null +++ b/packages/gumloop/index.mjs @@ -0,0 +1,646 @@ +// Gumloop (gumloop.com) for OpenCode and magpie. +// +// Gumloop serves an OpenAI-compatible chat completions API at +// https://ws.gumloop.com/api/v1. Every request carries the account's API key +// (Authorization: Bearer) and its user id (x-auth-key); both are on Gumloop's +// Settings → Connectors → Gumloop API Key page. GET api.gumloop.com/api/v1/models +// lists the models an account may use. +// +// Gumloop publishes no balance endpoint, so this plugin prices each call +// itself (OpenRouter's list prices, $0.005 a credit, every call rounded up to a +// whole credit) and takes it off a balance the user reads off gumloop.com. +// Spend on gumloop.com itself shows only at the next calibration. + +import { join } from "node:path" +import { + API as DEFAULT_API, + WS as DEFAULT_WS, + OPENROUTER as DEFAULT_OPENROUTER, + EXHAUSTED_FOR, + FALLBACK_PRICES, + PRICES_RETRY_TTL, + PRICES_TTL, + Store, + availableModel, + creditsFor, + fetchPrices, + gumloopHeaders, + isObj, + parseModels, + usageCost, + wireModel, +} from "./gumloop.mjs" + +const ID = "gumloop" +const NPM = "@ai-sdk/openai-compatible" +const EFFORTS = Object.fromEntries(["low", "medium", "high"].map((e) => [e, { reasoningEffort: e }])) + +// Gumloop documents no credit-exhaustion response shape, and none has been +// captured live. Assume only HTTP 403 with a structured credit_limit_exceeded +// code means the Gumloop account itself is out of credits; HTTP 402 is passed +// through untouched so an upstream provider's 402 (such as OpenRouter's +// "Insufficient credits") does not zero the user's Gumloop balance estimate. +function isCreditRefusal(status, text) { + if (status !== 403) return false + try { + const d = JSON.parse(text) + const code = d?.error?.code ?? d?.error?.type ?? d?.code ?? (typeof d?.error === "string" ? d.error : "") + if (code === "credit_limit_exceeded") return true + } catch {} + return false +} + +// aliasesFor gives every Gumloop id a slash-free name agents can type +// (gumloop/glm-5p3 for accounts/fireworks/models/glm-5p3): the last path part +// when no other id shares it, else the id with its slashes doubled into dashes. +function aliasesFor(ids) { + const tail = (id) => id.slice(id.lastIndexOf("/") + 1) + const count = new Map() + for (const id of ids) count.set(tail(id), (count.get(tail(id)) ?? 0) + 1) + return new Map(ids.map((id) => [id, count.get(tail(id)) === 1 ? tail(id) : id.replace(/\//g, "--")])) +} + +const pretty = (id) => id.slice(id.lastIndexOf("/") + 1).replace(/[-_]+/g, " ").trim() + +// costOf turns a price entry into the per-million rates magpie shows. +function costOf(entry) { + if (!entry?.p) return undefined + const [input, output, cache_read, cache_write] = entry.p + return { + input, + output, + ...(cache_read != null && { cache_read }), + ...(cache_write != null && { cache_write }), + } +} + +// row is one model in both the config hook's shape (top-level fields) and the +// models hook's (capabilities). +function row(m, alias, entry) { + const image = !!m.vision + const cost = costOf(entry) + return { + id: alias, + name: m.name, + limit: { context: m.context || 0, output: 0 }, + reasoning: !!m.reasoning, + tool_call: true, + modalities: { input: image ? ["text", "image"] : ["text"], output: ["text"] }, + capabilities: { + reasoning: !!m.reasoning, + toolcall: true, + attachment: image, + input: { text: true, image }, + output: { text: true }, + }, + ...(m.reasoning ? { variants: EFFORTS } : {}), + ...(cost ? { cost } : {}), + } +} + +// normalize rewrites a chat completions body the way Gumloop takes it. +function normalize(body, { cache1h } = {}) { + // These upstream routes reject the empty system prompt Gumloop otherwise + // supplies. Preserve every nonempty caller instruction (system or developer). + if (/^(meta\/muse-|minimax\/minimax-m3\.1-flash$)/.test(String(body.model)) && Array.isArray(body.messages)) { + const isSystem = (role) => role === "system" || role === "developer" + const nonempty = (content) => + typeof content === "string" + ? !!content.trim() + : Array.isArray(content) && content.some((p) => typeof p?.text === "string" && p.text.trim()) + body.messages = body.messages.filter((m) => !isSystem(m.role) || nonempty(m.content)) + if (!body.messages.some((m) => isSystem(m.role))) { + body.messages.unshift({ role: "system", content: "You are a helpful assistant." }) + } + } + if (body.stream === true) body.stream_options = { ...(isObj(body.stream_options) ? body.stream_options : {}), include_usage: true } + else delete body.stream_options + if (body.max_completion_tokens !== undefined) { + if (body.max_tokens === undefined) body.max_tokens = body.max_completion_tokens + delete body.max_completion_tokens + } + delete body.store + if (typeof body.reasoning_effort === "string") { + if (!isObj(body.reasoning)) body.reasoning = { effort: body.reasoning_effort } + delete body.reasoning_effort + } + // Optional 1-hour Anthropic prompt cache TTL (opt-in via options.cache1h). + if (cache1h && /^claude-/.test(String(body.model)) && body.cache_control === undefined) { + body.cache_control = { type: "ephemeral", ttl: "1h" } + } + return body +} + +// tapUsage passes a response body through unchanged and reports the usage +// block it carried (SSE or JSON) once it ends, or that it was cut short. +// Hold terminal SSE frames (and bounded JSON bodies) until accounting finishes: +// short-lived hosts can terminate us as soon as they see a complete response. +function tapUsage(stream, isSse, signal, done) { + const dec = new TextDecoder() + let buf = "" + let usage + let tooBig = false + let finished = false + let terminal = false + let pending = [] + // SSE offsets are bytes, not decoded string offsets: retain only the + // incomplete line or terminal tail, and forward original bytes unchanged. + const sseBuffer = isSse ? new Uint8Array(256 * 1024) : undefined + let sseSize = 0 + let lineStart = 0 + const emit = (ctl) => { + for (const chunk of pending) ctl.enqueue(chunk) + pending = [] + } + const aborted = () => finish(true) + const finish = (cut) => { + if (finished) return + finished = true + signal?.removeEventListener("abort", aborted) + done(usage, cut || (tooBig && !usage)) + } + const take = (o) => { + if (isObj(o?.usage)) usage = o.usage + if (isSse && (isObj(o?.usage) || o?.choices?.some((c) => c.finish_reason != null))) terminal = true + } + const line = (l) => { + const t = l.trim() + if (!t.startsWith("data:")) return + const d = t.slice(5).trim() + if (d === "[DONE]") { + terminal = true + // The protocol is complete even if the connection remains open. Do + // accounting before releasing any bytes from this parsed chunk. + finish(false) + return + } + if (!d.includes('"usage"') && !d.includes('"finish_reason"')) return + try { + take(JSON.parse(d)) + } catch {} + } + const sseChunk = (chunk, ctl) => { + let offset = 0 + while (offset < chunk.byteLength) { + if (tooBig || sseSize === sseBuffer.length) { + // A malformed/oversized line or terminal tail must not drain an + // unbounded source. Record the incomplete estimate before releasing + // any held terminal bytes, then use ordinary stream backpressure. + if (!tooBig) { + tooBig = true + usage = undefined + finish(true) + ctl.enqueue(sseBuffer.slice(0, sseSize)) + sseSize = lineStart = 0 + } + ctl.enqueue(chunk.subarray(offset)) + return + } + const end = Math.min(chunk.byteLength, offset + sseBuffer.length - sseSize) + const scanFrom = sseSize + sseBuffer.set(chunk.subarray(offset, end), sseSize) + sseSize += end - offset + offset = end + let safe = 0 + for (let i = scanFrom; i < sseSize; i++) { + if (sseBuffer[i] !== 10) continue + line(dec.decode(sseBuffer.subarray(lineStart, i + 1))) + lineStart = i + 1 + if (!terminal || finished) safe = lineStart + } + if (safe) { + ctl.enqueue(sseBuffer.slice(0, safe)) + sseBuffer.copyWithin(0, safe, sseSize) + sseSize -= safe + lineStart -= safe + } + } + } + signal?.addEventListener("abort", aborted, { once: true }) + if (signal?.aborted) aborted() + const tap = new TransformStream({ + transform(chunk, ctl) { + if (isSse) return sseChunk(chunk, ctl) + pending.push(chunk) + const s = dec.decode(chunk, { stream: true }) + if (!tooBig) { + buf += s + if (buf.length > 4e6) { + tooBig = true + buf = "" + } + } + // Oversized JSON keeps the existing pass-through/unbilled behavior. + if (tooBig) emit(ctl) + }, + flush(ctl) { + if (isSse) { + if (sseSize > lineStart) line(dec.decode(sseBuffer.subarray(lineStart, sseSize))) + } else { + buf += dec.decode() + try { + take(JSON.parse(buf)) + } catch {} + } + buf = "" + finish(false) + if (isSse) { + if (sseSize) ctl.enqueue(sseBuffer.slice(0, sseSize)) + sseSize = lineStart = 0 + } else emit(ctl) + }, + }) + // Unlike pipeThrough, observing pipeTo also catches source failures and + // consumer cancellation. The readable still propagates the original error. + stream.pipeTo(tap.writable).catch(() => finish(true)) + return tap.readable +} + +const errorJson = (status, message, type, headers = {}) => + new Response(JSON.stringify({ error: { message, type } }), { + status, + headers: { "content-type": "application/json", ...headers }, + }) + +// lookup reads a per-account option: a number for every account, or an +// object keyed by user id or email. +function lookup(opt, who) { + if (typeof opt === "number") return opt + if (!isObj(opt)) return undefined + for (const k of who) if (k && opt[k] !== undefined) return opt[k] + return undefined +} + +// creditsOf reads a balance as gumloop.com shows it ("7,142", "7 142.5"): +// a whole number of credits, or undefined for anything else. +function creditsOf(v) { + const s = String(v ?? "").trim().replace(/[,\s_]/g, "") + return /^\d+(\.\d+)?$/.test(s) ? Math.floor(Number(s)) : undefined +} + +function createPlugin({ directory, magpie, options = {}, fetchImpl = globalThis.fetch, now = Date.now, env = process.env } = {}) { + const API = env.GUMLOOP_API_BASE || DEFAULT_API + const WS = env.GUMLOOP_WS_BASE || DEFAULT_WS + const OPENROUTER = env.GUMLOOP_OPENROUTER_BASE || DEFAULT_OPENROUTER + // In magpie, `directory` is magpie's config dir (`input.magpie` is present). + // In OpenCode, `directory` is the user's project tree and must not be written to. + const ledgerPath = magpie && directory ? join(directory, "gumloop-ledger.json") : undefined + const store = new Store(ledgerPath, now) + const cache1h = options.cache1h === true + // alias -> Gumloop id: built-in defaults plus one map per account. + const defaultIds = new Map() + const knownIds = new Set(Object.keys(FALLBACK_PRICES)) + for (const [id, alias] of aliasesFor(Object.keys(FALLBACK_PRICES))) defaultIds.set(alias, id) + const accountIds = new Map() + const maxOut = new Map() + let pricing + let pricesFailedAt = 0 + + const credOf = (auth) => { + if (auth?.type !== "api" || !auth.key) return undefined + const userId = typeof auth.metadata?.userId === "string" ? auth.metadata.userId : "" + return userId ? { key: auth.key, userId, email: auth.metadata?.email } : undefined + } + + const getModels = (cred) => + fetchImpl(`${API}/models`, { + headers: { ...gumloopHeaders(cred.key, cred.userId), accept: "application/json" }, + signal: AbortSignal.timeout(30000), + redirect: "error", + }) + + // refreshPrices re-reads OpenRouter's list at most every PRICES_TTL; a + // failure backs off for PRICES_RETRY_TTL and keeps the existing table. + function refreshPrices() { + const ids = [...knownIds] + const cached = store.prices() + if (cached.version === 2 && now() - cached.at < PRICES_TTL && ids.every((id) => cached.ids?.includes(id))) return Promise.resolve() + if (pricesFailedAt && now() - pricesFailedAt < PRICES_RETRY_TTL) return Promise.resolve() + pricing ??= (async () => { + const table = await fetchPrices((u, i) => fetchImpl(u.replace(DEFAULT_OPENROUTER, OPENROUTER), i), ids) + pricesFailedAt = 0 + store.setPrices(table, ids) + })() + .catch(() => { + pricesFailedAt = now() + }) + .finally(() => { + pricing = undefined + }) + return pricing + } + + // calibrate applies a balance given at sign-in, or in the plugin's + // options, once per value. + function calibrate(cred, auth) { + const md = auth.metadata ?? {} + if (md.balance !== undefined && md.balanceAt) store.anchor(cred.userId, md.balance, `login:${md.balanceAt}`, Number(md.balanceAt)) + const opt = lookup(options.balance, [cred.userId, cred.email]) + if (opt !== undefined) store.anchor(cred.userId, opt, `options:${opt}`) + } + + function charge(uid, model, usage, cut) { + store.change(uid, (a) => { + if (!usage) { + // Gumloop bills the tokens a stopped stream produced, but its usage + // block never came: tell the user the estimate is off. + if (cut) a.unbilledStops = (a.unbilledStops ?? 0) + 1 + return + } + const entry = store.price(model) + const rec = { at: now(), model } + if (entry) { + const c = usageCost(entry, usage) + rec.credits = creditsFor(c.usd) + Object.assign(rec, { in: c.prompt, out: c.out, cacheRead: c.read, cacheWrite: c.write }) + Store.spend(a, rec.credits, rec.at) + a.month.credits += rec.credits + a.month.usd = Math.round((a.month.usd + c.usd) * 1e6) / 1e6 + } else { + rec.unpriced = true + a.unpriced = (a.unpriced ?? 0) + 1 + } + a.month.calls += 1 + a.last = rec + delete a.exhaustedAt + }) + } + + async function send(cred, url, init, body, signal) { + const headers = new Headers(init?.headers) + for (const [k, v] of Object.entries(gumloopHeaders(cred.key, cred.userId))) headers.set(k, v) + headers.set("content-type", "application/json") + headers.delete("content-length") + return fetchImpl(url, { ...init, headers, body: JSON.stringify(body), signal }) + } + + async function request(cred, input, init) { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url + const raw = init?.body + let body + try { + const text = typeof raw === "string" ? raw : raw instanceof Uint8Array || raw instanceof ArrayBuffer ? new TextDecoder().decode(raw) : undefined + body = text === undefined ? undefined : JSON.parse(text) + } catch {} + if (!isObj(body)) { + const headers = new Headers(init?.headers) + for (const [k, v] of Object.entries(gumloopHeaders(cred.key, cred.userId))) headers.set(k, v) + return fetchImpl(url, { ...init, headers }) + } + const perAccount = accountIds.get(cred.userId) + const model = wireModel(perAccount?.get(body.model) ?? defaultIds.get(body.model) ?? body.model) + body.model = model + const streamRequested = body.stream === true + normalize(body, { cache1h }) + const cap = maxOut.get(model) + if (cap && typeof body.max_tokens === "number" && body.max_tokens > cap) body.max_tokens = cap + + let res = await send(cred, url, init, body, init?.signal) + // A model with a lower output cap refuses a generous max_tokens + // ("max_tokens: 256000 > 128000"): learn the cap and ask once more. + if (res.status === 400 && typeof body.max_tokens === "number") { + const m = /max_tokens:?\s*(\d+)\s*>\s*(\d+)/.exec(await res.clone().text().catch(() => "")) + const limit = m ? Number(m[2]) : 0 + if (limit > 0 && limit < body.max_tokens) { + maxOut.set(model, limit) + body.max_tokens = limit + await res.body?.cancel().catch(() => {}) + res = await send(cred, url, init, body, init?.signal) + } + } + + if (!res.ok) { + const text = await res.clone().text().catch(() => "") + if (isCreditRefusal(res.status, text)) { + store.change(cred.userId, (a) => { + a.exhaustedAt = now() + }) + await res.body?.cancel().catch(() => {}) + // 429 so magpie moves the request to the next account; the sign-in is fine. + return errorJson( + 429, + `Gumloop: out of credits (from HTTP ${res.status}: ${text.slice(0, 300) || res.statusText || "credit_limit_exceeded"})`, + "insufficient_quota", + { "x-magpie-sign-in": "kept" }, + ) + } + if (res.status === 403) { + // A provider's "Invalid API key" can refer to Gumloop's upstream + // credentials. Only Gumloop's own /models check decides our sign-in. + let signIn + try { + const check = await getModels(cred) + await check.body?.cancel().catch(() => {}) + if (check.status === 200) signIn = "kept" + else if (check.status === 401 || check.status === 403) signIn = "expired" + } catch {} + if (signIn) { + const headers = new Headers(res.headers) + headers.set("x-magpie-sign-in", signIn) + return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) + } + } + return res + } + + if (!res.body) return res + const ct = res.headers.get("content-type") ?? "" + const headers = new Headers(res.headers) + headers.delete("content-length") + headers.delete("content-encoding") + const tapped = tapUsage(res.body, ct.includes("text/event-stream") || streamRequested, init?.signal, (usage, cut) => { + try { + charge(cred.userId, model, usage, cut) + } catch {} + }) + return new Response(tapped, { status: res.status, statusText: res.statusText, headers }) + } + + return { + config: async (cfg) => { + cfg.provider ??= {} + const ids = Object.keys(FALLBACK_PRICES).filter(availableModel) + const aliases = aliasesFor(ids) + cfg.provider[ID] ??= { + name: "Gumloop", + npm: NPM, // chat completions + api: WS, + models: Object.fromEntries( + ids.map((id) => { + const alias = aliases.get(id) + const m = { id, name: pretty(id), reasoning: /^claude-(opus|fable)/.test(id) } + return [alias, row(m, alias, { p: FALLBACK_PRICES[id] })] + }), + ), + } + }, + + auth: { + provider: ID, + methods: [ + { + type: "api", + label: "Gumloop API key", + // magpie asks for an API method's key itself and doesn't hand it to + // authorize; keyless has it skip that, so the key prompt below is + // the only one and authorize can check it with the user id. + keyless: true, + prompts: [ + { + type: "password", + key: "key", + message: "API key (Gumloop → Settings → Connectors → Gumloop API Key)", + validate: (v) => (/^[A-Za-z0-9_-]{16,128}$/.test(String(v ?? "").trim()) ? undefined : "That doesn't look like a Gumloop API key"), + }, + { + type: "text", + key: "userId", + message: "User ID (on the same page)", + validate: (v) => (/^[A-Za-z0-9_-]{8,128}$/.test(String(v ?? "").trim()) ? undefined : "That doesn't look like a Gumloop user id"), + }, + { + type: "text", + key: "email", + required: false, + message: "Account email (optional; names the account in magpie)", + }, + { + type: "text", + key: "balance", + required: false, + message: "Credits left, as gumloop.com shows them (optional; starts the estimate)", + validate: (v) => (!String(v ?? "").trim() || creditsOf(v) !== undefined ? undefined : "A number of credits, such as 7142"), + }, + ], + async authorize(inputs) { + const key = String(inputs?.key ?? "").trim() + const userId = String(inputs?.userId ?? "").trim() + const email = String(inputs?.email ?? "").trim() + const balance = creditsOf(inputs?.balance) + if (!key || !userId) return { type: "failed", error: "Gumloop needs both the API key and the user id" } + let res + try { + res = await getModels({ key, userId }) + } catch (e) { + return { type: "failed", error: `Gumloop unreachable: ${e?.cause?.code || e?.message || "network error"}` } + } + if (res.status === 401 || res.status === 403) { + return { type: "failed", error: `Gumloop refused the API key or user id (HTTP ${res.status})` } + } + if (!res.ok) return { type: "failed", error: `Gumloop answered HTTP ${res.status}` } + // magpie keeps the prompts' answers as the account's metadata, the + // key among them; key: undefined drops it there (it is kept once, as + // the account's key). + const metadata = { key: undefined, userId, ...(email && { email }), ...(balance !== undefined && { balance, balanceAt: now() }) } + return { type: "success", key, metadata } + }, + }, + ], + + async loader(getAuth) { + const auth = await getAuth() + const cred = credOf(auth) + if (!cred) return {} + calibrate(cred, auth) + return { + baseURL: WS, + apiKey: cred.key, + headers: { "x-auth-key": cred.userId }, + fetch: (input, init) => request(cred, input, init), + } + }, + + async usage(getAuth) { + const auth = await getAuth() + const cred = credOf(auth) + if (!cred) return {} + calibrate(cred, auth) + let res + try { + res = await getModels(cred) + } catch (e) { + return { error: `Gumloop unreachable: ${e?.cause?.code || e?.message || "network error"}`, windows: [] } + } + await res.body?.cancel().catch(() => {}) + if (res.status === 401 || res.status === 403) { + return { error: `Gumloop refused this key (HTTP ${res.status}); sign in again`, signIn: "expired", windows: [] } + } + await refreshPrices() + + const a = store.account(cred.userId) + const exhausted = a.exhaustedAt && now() - a.exhaustedAt < EXHAUSTED_FOR + const est = store.remaining(cred.userId) + const left = exhausted ? 0 : est + const allowance = Number(lookup(options.allowance, [cred.userId, cred.email])) || 0 + const windows = [] + if (left === undefined) { + windows.push({ name: "Credits", display: "Not calibrated: sign in again with the credits gumloop.com shows" }) + } else if (allowance > 0) { + windows.push({ + name: "Credits", + amount: Math.max(0, allowance - left), + limit: allowance, + unit: "credits", + display: `${left} / ${allowance} credits left (estimate)`, + }) + } else { + windows.push({ name: "Credits", balance: left, unit: "credits", display: `${left} credits left (estimate)` }) + } + const notes = [ + `${a.month.credits} credits · ${a.month.calls} calls`, + a.unbilledStops ? `${a.unbilledStops} stopped without usage` : "", + a.unpriced ? `${a.unpriced} unpriced` : "", + ].filter(Boolean) + windows.push({ name: "This month via magpie", amount: a.month.credits, unit: "credits", display: notes.join(" · "), aside: true }) + return { + plan: "Gumloop", + user: cred.email || `user …${cred.userId.slice(-4)}`, + ...(left !== undefined && { balance: `${left} credits` }), + ...(!res.ok && { error: `Gumloop answered HTTP ${res.status}` }), + windows, + } + }, + }, + + provider: { + id: ID, + async models(provider, { auth } = {}) { + const cred = credOf(auth) + if (!cred) return provider.models + let res + try { + res = await getModels(cred) + } catch { + return provider.models + } + if (res.status === 401 || res.status === 403) { + throw Object.assign(new Error(`Gumloop refused this key (HTTP ${res.status}); sign in again`), { signIn: "expired" }) + } + if (!res.ok) return provider.models + let list + try { + list = parseModels(await res.json()) + } catch (e) { + // the host keeps the previous list + throw new Error(e?.message || "Gumloop sent no model list") + } + const aliases = aliasesFor(list.map((m) => m.id)) + const acctMap = new Map() + for (const [id, alias] of aliases) { + const wire = wireModel(id) + acctMap.set(alias, wire) + knownIds.add(wire) + } + accountIds.set(cred.userId, acctMap) + await refreshPrices() + return Object.fromEntries(list.map((m) => [aliases.get(m.id), row(m, aliases.get(m.id), store.price(m.id))])) + }, + }, + } +} + +// The plugin is the only exported function; magpie calls every exported +// function as a plugin, so tests reach the internals through this object. +export const GumloopPlugin = async (input, options) => + createPlugin({ directory: input?.directory, magpie: input?.magpie, options: options ?? {} }) +export const _internal = { createPlugin, aliasesFor, normalize, tapUsage, row, costOf, lookup, isCreditRefusal } diff --git a/packages/gumloop/index.test.mjs b/packages/gumloop/index.test.mjs new file mode 100644 index 0000000..45ecefd --- /dev/null +++ b/packages/gumloop/index.test.mjs @@ -0,0 +1,435 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { mkdtempSync, rmSync, readFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { GumloopPlugin, _internal } from "./index.mjs" +import { FALLBACK_PRICES, Store, creditsFor, parseModels, priceRef, usageCost } from "./gumloop.mjs" + +const { createPlugin, aliasesFor, normalize } = _internal + +const KEY = "glkey-AAAAAAAAAAAAAAAAAAAA" +const USER = "userAAAA1111" +const auth = { type: "api", key: KEY, metadata: { userId: USER, email: "ada@example.com" } } +const env = { GUMLOOP_API_BASE: "https://gl.test/api", GUMLOOP_WS_BASE: "https://gl.test/ws", GUMLOOP_OPENROUTER_BASE: "https://or.test/v1" } + +const json = (status, body, headers = {}) => + new Response(body === undefined ? null : typeof body === "string" ? body : JSON.stringify(body), { + status, + headers: { "content-type": "application/json", ...headers }, + }) +const sse = (frames) => + new Response(frames.map((f) => (typeof f === "string" ? f : `data: ${JSON.stringify(f)}\n\n`)).join(""), { + status: 200, + headers: { "content-type": "text/event-stream" }, + }) + +const opt = (value, extra = {}) => ({ + value, + label: value.toUpperCase(), + status: "active", + restricted: false, + metadata: { capabilities: ["functions", "vision"], context_window: 1000000 }, + ...extra, +}) +const MODELS = { + model_groups: [ + { groupLabel: "Auto", options: [opt("gumloop-chew")] }, + { + groupLabel: "Anthropic", + options: [ + opt("claude-sonnet-5-5", { metadata: { capabilities: ["functions", "vision"], context_window: 1000000, short_context_window: 300000 } }), + opt("claude-opus-5-5"), + opt("claude-opus-4-8", { status: "hidden" }), + ], + }, + { groupLabel: "OpenAI", options: [opt("gpt-6-sol", { metadata: { capabilities: ["functions", "reasoning"], context_window: 272000 } })] }, + { groupLabel: "Fireworks", options: [opt("accounts/fireworks/models/glm-5p3", { metadata: { capabilities: ["functions", "reasoning"] } })] }, + { groupLabel: "Other", options: [opt("typesafe/jev-1", { metadata: { capabilities: ["decisions"] } }), opt("x/classifier", { is_classifier_model: true })] }, + ], +} +const BIG_USAGE = { prompt_tokens: 100000, completion_tokens: 5000, prompt_tokens_details: { cached_tokens: 60000, cache_write_tokens: 20000 } } + +// fake routes requests by URL; `chat` answers /ws/chat/completions. +function fake(chat = () => json(200, { choices: [], usage: { prompt_tokens: 10, completion_tokens: 5 } })) { + const calls = [] + const fetchImpl = async (input, init = {}) => { + const url = String(input) + const headers = new Headers(init.headers) + const call = { url, headers, body: typeof init.body === "string" ? JSON.parse(init.body) : undefined } + calls.push(call) + if (url.startsWith("https://gl.test/api/models")) { + if (headers.get("authorization") !== `Bearer ${KEY}` || headers.get("x-auth-key") !== USER) return json(403, { error: "forbidden" }) + return json(200, MODELS) + } + if (url.startsWith("https://gl.test/ws/chat/completions")) return chat(call, calls) + if (url === "https://or.test/v1/models") { + return json(200, { + data: [ + { id: "anthropic/claude-sonnet-5.5", pricing: { prompt: "0.000003", completion: "0.000015", input_cache_read: "0.0000003", input_cache_write: "0.00000375" } }, + { id: "z-ai/glm-5.3", pricing: { prompt: "0.000000079", completion: "0.0000048" } }, + ], + }) + } + if (url === "https://or.test/v1/models/z-ai/glm-5.3/endpoints") { + return json(200, { + data: { + endpoints: [ + { provider_name: "Wafer", pricing: { prompt: "0.000000079", completion: "0.0000048" } }, + { provider_name: "Fireworks", pricing: { prompt: "0.0000014", completion: "0.0000044", input_cache_read: "0.00000026" } }, + ], + }, + }) + } + return json(404, {}) + } + return { calls, fetchImpl } +} + +const dirs = [] +function tempDir() { + const d = mkdtempSync(join(tmpdir(), "gumloop-test-")) + dirs.push(d) + return d +} +function plugin(f, extra = {}) { + const directory = tempDir() + let t = extra.t ?? 1_800_000_000_000 + const p = createPlugin({ directory, magpie: true, fetchImpl: f.fetchImpl, env, now: () => t, ...extra }) + return Object.assign(p, { directory, tick: (ms) => (t += ms) }) +} +afterEach(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) +}) + +async function chatOnce(p, body, signal) { + const loaded = await p.auth.loader(async () => auth) + const res = await loaded.fetch("https://gl.test/ws/chat/completions", { + method: "POST", + headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json", "content-length": "999" }, + body: JSON.stringify(body), + signal, + }) + const text = await res.text() + return { res, text } +} + +describe("config", () => { + test("declares gumloop with slash-free model ids and keeps a configured provider", async () => { + const p = plugin(fake()) + const mine = { provider: { gumloop: { name: "Mine" } } } + await p.config(mine) + expect(mine.provider.gumloop.name).toBe("Mine") + const cfg = {} + await p.config(cfg) + const g = cfg.provider.gumloop + expect(g.npm).toBe("@ai-sdk/openai-compatible") + expect(g.api).toBe("https://gl.test/ws") + expect(Object.keys(g.models).every((k) => !k.includes("/"))).toBe(true) + expect(g.models["glm-5p3"].cost.input).toBe(1.4) + expect(g.models["claude-opus-5-5"].variants.high).toEqual({ reasoningEffort: "high" }) + }) + test("the exported plugin loads without a network", async () => { + const hooks = await GumloopPlugin({ directory: tempDir() }, undefined) + expect(hooks.auth.provider).toBe("gumloop") + expect(hooks.auth.methods[0].type).toBe("api") + }) +}) + +describe("sign-in", () => { + test("checks the key and user id against /models and keeps them", async () => { + const f = fake() + const p = plugin(f) + const m = p.auth.methods[0] + expect(m.prompts.map((q) => q.key)).toEqual(["key", "userId", "email", "balance"]) + const ok = await m.authorize({ key: ` ${KEY} `, userId: USER, email: "ada@example.com", balance: "7,142" }) + expect(m.keyless).toBe(true) + expect(ok.type).toBe("success") + expect(ok.key).toBe(KEY) + // magpie merges the prompts' answers into the metadata: the key must not ride along + expect(JSON.parse(JSON.stringify({ ...{ key: KEY, userId: USER }, ...ok.metadata }))).toEqual({ + userId: USER, + email: "ada@example.com", + balance: 7142, + balanceAt: 1_800_000_000_000, + }) + expect(f.calls[0].headers.get("x-auth-key")).toBe(USER) + const bad = await m.authorize({ key: "glkey-ZZZZZZZZZZZZZZZZZZZZ", userId: USER }) + expect(bad.type).toBe("failed") + expect(bad.error).toContain("403") + expect((await m.authorize({ key: KEY })).type).toBe("failed") + }) + test("prompts validate the formats", () => { + const [key, user, , balance] = plugin(fake()).auth.methods[0].prompts + expect(key.validate("short")).toBeString() + expect(key.validate(KEY)).toBeUndefined() + expect(user.validate(USER)).toBeUndefined() + expect(balance.validate("")).toBeUndefined() + expect(balance.validate("7,142")).toBeUndefined() + expect(balance.validate("12.5")).toBeUndefined() + expect(balance.validate("lots")).toBeString() + expect(balance.validate("-3")).toBeString() + }) +}) + +describe("loader and requests", () => { + test("loads nothing without a complete sign-in", async () => { + const p = plugin(fake()) + expect(await p.auth.loader(async () => undefined)).toEqual({}) + expect(await p.auth.loader(async () => ({ type: "api", key: KEY }))).toEqual({}) + }) + test("signs the request, maps the alias back and rewrites the body for Gumloop", async () => { + const f = fake((call) => json(200, { model: call.body.model, choices: [], usage: { prompt_tokens: 10, completion_tokens: 5 } })) + const p = plugin(f) + const loaded = await p.auth.loader(async () => auth) + expect(loaded.baseURL).toBe("https://gl.test/ws") + expect(loaded.apiKey).toBe(KEY) + const { res } = await chatOnce(p, { + model: "claude-sonnet-5-5", + stream: false, + stream_options: { include_usage: true }, + max_completion_tokens: 50, + store: true, + reasoning_effort: "high", + messages: [{ role: "user", content: "hi" }], + }) + expect(res.status).toBe(200) + const up = f.calls.find((c) => c.url.includes("/ws/")) + expect(up.headers.get("authorization")).toBe(`Bearer ${KEY}`) + expect(up.headers.get("x-auth-key")).toBe(USER) + expect(up.headers.get("content-length")).toBeNull() + expect(up.body).toMatchObject({ max_tokens: 50, reasoning: { effort: "high" } }) + expect(up.body.cache_control).toBeUndefined() + expect(up.body.max_completion_tokens).toBeUndefined() + expect(up.body.store).toBeUndefined() + expect(up.body.stream_options).toBeUndefined() + + await chatOnce(p, { model: "glm-5p3", stream: true, messages: [] }) + const glm = f.calls.filter((c) => c.url.includes("/ws/")).pop() + expect(glm.body.model).toBe("accounts/fireworks/models/glm-5p3") + expect(glm.body.cache_control).toBeUndefined() + expect(glm.body.stream_options).toEqual({ include_usage: true }) + }) + test("the 1-hour cache is opt-in and preserves caller cache_control", () => { + expect(normalize({ model: "claude-opus-5-5" }).cache_control).toBeUndefined() + expect(normalize({ model: "claude-opus-5-5" }, { cache1h: false }).cache_control).toBeUndefined() + expect(normalize({ model: "claude-opus-5-5" }, { cache1h: true }).cache_control).toEqual({ type: "ephemeral", ttl: "1h" }) + expect(normalize({ model: "claude-opus-5-5", cache_control: { type: "x" } }, { cache1h: true }).cache_control).toEqual({ type: "x" }) + }) + test("learns a model's output cap from a 400 and retries once", async () => { + const f = fake((call) => + call.body.max_tokens > 128000 + ? json(400, { error: { message: `max_tokens: ${call.body.max_tokens} > 128000, which is the maximum` } }) + : json(200, { choices: [], usage: { prompt_tokens: 1, completion_tokens: 1 } }), + ) + const p = plugin(f) + const first = await chatOnce(p, { model: "claude-sonnet-5-5", max_tokens: 256000, messages: [] }) + expect(first.res.status).toBe(200) + const chats = () => f.calls.filter((c) => c.url.includes("/ws/")) + expect(chats().map((c) => c.body.max_tokens)).toEqual([256000, 128000]) + await chatOnce(p, { model: "claude-sonnet-5-5", max_tokens: 256000, messages: [] }) + expect(chats().pop().body.max_tokens).toBe(128000) + expect(chats().length).toBe(3) + }) + test("an out-of-credits answer becomes a 429 that keeps the sign-in and zeroes the estimate", async () => { + // Assumed Gumloop credit-exhaustion shape (no live exhaustion response has been captured). + const f = fake(() => json(403, { error: "credit_limit_exceeded", message: "You have reached your credit limit." })) + const p = plugin(f) + const { res, text } = await chatOnce(p, { model: "claude-sonnet-5-5", messages: [] }) + expect(res.status).toBe(429) + expect(res.headers.get("x-magpie-sign-in")).toBe("kept") + expect(text).toContain("out of credits") + // a balance read before the refusal doesn't undo it + const card = await p.auth.usage(async () => ({ ...auth, metadata: { ...auth.metadata, balance: 500, balanceAt: 1 } })) + expect(card.windows[0]).toMatchObject({ balance: 0 }) + // a newer one does + p.tick(1000) + const later = await p.auth.usage(async () => ({ ...auth, metadata: { ...auth.metadata, balance: 800, balanceAt: 1_800_000_000_500 } })) + expect(later.windows[0]).toMatchObject({ balance: 800 }) + // upstream HTTP 402 passes through without zeroing the balance + const p402 = plugin(fake(() => json(402, { error: { message: "Insufficient credits" } }))) + const r402 = await chatOnce(p402, { model: "claude-sonnet-5-5", messages: [] }) + expect(r402.res.status).toBe(402) + const card402 = await p402.auth.usage(async () => ({ ...auth, metadata: { ...auth.metadata, balance: 500, balanceAt: 1 } })) + expect(card402.windows[0]).toMatchObject({ balance: 500 }) + }) + test("a refused key marks the account expired; other errors pass through", async () => { + const f = fake(() => json(403, { error: "Invalid API key" })) + const refused = { + fetchImpl: (url, init) => String(url).startsWith("https://gl.test/api/models") + ? json(403, { error: "Invalid API key" }) + : f.fetchImpl(url, init), + } + const { res } = await chatOnce(plugin(refused), { model: "gpt-6-sol", messages: [] }) + expect(res.status).toBe(403) + expect(res.headers.get("x-magpie-sign-in")).toBe("expired") + const g = fake(() => json(500, { error: "boom" })) + const other = await chatOnce(plugin(g), { model: "gpt-6-sol", messages: [] }) + expect(other.res.status).toBe(500) + expect(other.res.headers.get("x-magpie-sign-in")).toBeNull() + }) +}) + +describe("credit estimate", () => { + test("charges a stream's usage (cache reads and writes, rounded up) and a tiny call one credit", async () => { + const f = fake((call) => + call.body.stream + ? sse([ + { id: "c1", model: call.body.model, choices: [{ index: 0, delta: { content: "Hi" } }] }, + { id: "c1", choices: [], usage: BIG_USAGE }, + "data: [DONE]\n\n", + ]) + : json(200, { choices: [], usage: { prompt_tokens: 10, completion_tokens: 5 } }), + ) + const p = plugin(f) + const metaAuth = { ...auth, metadata: { ...auth.metadata, balance: 7142, balanceAt: 42 } } + const loaded = await p.auth.loader(async () => metaAuth) + // calibrate from the sign-in before spending + await p.auth.usage(async () => metaAuth) + const r = await loaded.fetch("https://gl.test/ws/chat/completions", { method: "POST", body: JSON.stringify({ model: "claude-sonnet-5-5", stream: true, messages: [] }) }) + const text = await r.text() + expect(text).toContain('"content":"Hi"') + expect(text).toContain("[DONE]") + await (await loaded.fetch("https://gl.test/ws/chat/completions", { method: "POST", body: JSON.stringify({ model: "claude-sonnet-5-5", messages: [] }) })).text() + + const ledger = JSON.parse(readFileSync(join(p.directory, "gumloop-ledger.json"), "utf8")).accounts[USER] + // the usage check read OpenRouter's sonnet price [3,15,0.3,3.75]: + // 20k*3 + 60k*0.3 + 20k*3.75 + 5k*15 = $0.228 -> 46 credits; the tiny call -> 1 + expect(ledger.month).toMatchObject({ credits: 47, calls: 2 }) + expect(ledger.spent).toBe(47) + expect(ledger.last).toMatchObject({ credits: 1, in: 10, out: 5 }) + const card = await p.auth.usage(async () => metaAuth) + expect(card.balance).toBe("7095 credits") + expect(card.windows[0]).toMatchObject({ name: "Credits", balance: 7095, unit: "credits" }) + expect(card.windows[1]).toMatchObject({ aside: true, amount: 47 }) + // the same sign-in balance isn't applied twice + expect(JSON.parse(readFileSync(join(p.directory, "gumloop-ledger.json"), "utf8")).accounts[USER].spent).toBe(47) + }) + test("built-in prices stand in when OpenRouter can't be read", async () => { + const f = fake((call) => sse([{ choices: [], usage: BIG_USAGE }, "data: [DONE]\n\n"])) + const p = plugin({ fetchImpl: (u, i) => (String(u).startsWith("https://or.test") ? json(503, "") : f.fetchImpl(u, i)) }) + await p.auth.usage(async () => auth) + const loaded = await p.auth.loader(async () => auth) + await (await loaded.fetch("https://gl.test/ws/chat/completions", { method: "POST", body: JSON.stringify({ model: "claude-sonnet-5-5", stream: true }) })).text() + // built-in sonnet [2,10,0.1,2.5]: 20k*2 + 60k*0.1 + 20k*2.5 + 5k*10 = $0.146 -> 30 credits + expect(JSON.parse(readFileSync(join(p.directory, "gumloop-ledger.json"), "utf8")).accounts[USER].spent).toBe(30) + }) + test("an allowance option turns the balance into a used/limit window", async () => { + const p = plugin(fake(), { options: { balance: { [USER]: 15000 }, allowance: 20000 } }) + const card = await p.auth.usage(async () => auth) + expect(card.windows[0]).toMatchObject({ amount: 5000, limit: 20000, unit: "credits" }) + expect(card.user).toBe("ada@example.com") + }) + test("says the estimate isn't calibrated until a balance is given", async () => { + const card = await plugin(fake()).auth.usage(async () => auth) + expect(card.windows[0].display).toContain("Not calibrated") + expect(card.windows[0].used).toBeUndefined() + expect(card.balance).toBeUndefined() + }) + test("a stopped stream with no usage is counted as unbilled", async () => { + let cancelled = false + const f = fake(() => { + const body = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({ choices: [{ delta: { content: "a" } }] })}\n\n`)) + }, + cancel() { + cancelled = true + }, + }) + return new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } }) + }) + const p = plugin(f) + const loaded = await p.auth.loader(async () => auth) + const res = await loaded.fetch("https://gl.test/ws/chat/completions", { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", stream: true }) }) + const reader = res.body.getReader() + await reader.read() + await reader.cancel() + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(cancelled).toBe(true) + const card = await p.auth.usage(async () => auth) + expect(card.windows[1].display).toContain("1 stopped without usage") + }) + test("a refused key on the usage check marks the account", async () => { + const card = await plugin(fake()).auth.usage(async () => ({ type: "api", key: "glkey-ZZZZZZZZZZZZZZZZZZZZ", metadata: { userId: USER } })) + expect(card.signIn).toBe("expired") + }) +}) + +describe("provider.models", () => { + test("lists the account's chat models with aliases, limits and live prices", async () => { + const f = fake() + const p = plugin(f) + const models = await p.provider.models({ models: {} }, { auth }) + expect(Object.keys(models)).toEqual(["claude-sonnet-5-5", "claude-opus-5-5", "gpt-6-sol", "glm-5p3"]) + expect(models["claude-sonnet-5-5"].limit.context).toBe(300000) + expect(models["claude-sonnet-5-5"].capabilities.input.image).toBe(true) + expect(models["gpt-6-sol"].capabilities.input.image).toBe(false) + expect(models["claude-opus-5-5"].reasoning).toBe(true) + // OpenRouter's live list replaces the built-in sonnet price + expect(models["claude-sonnet-5-5"].cost.input).toBe(3) + // Fireworks-hosted models are priced at Fireworks' endpoint, not the cheapest host + expect(models["glm-5p3"].cost).toMatchObject({ input: 1.4, output: 4.4, cache_read: 0.26 }) + // prices are cached for 12 hours + const n = f.calls.filter((c) => c.url.startsWith("https://or.test")).length + await p.provider.models({ models: {} }, { auth }) + expect(f.calls.filter((c) => c.url.startsWith("https://or.test")).length).toBe(n) + }) + test("keeps the previous list on errors and marks a refused key", async () => { + const kept = { models: { x: { name: "kept" } } } + expect(await plugin(fake()).provider.models(kept, {})).toBe(kept.models) + const down = plugin({ fetchImpl: async () => { throw new Error("offline") } }) + expect(await down.provider.models(kept, { auth })).toBe(kept.models) + const err = plugin({ fetchImpl: async () => json(502, "") }) + expect(await err.provider.models(kept, { auth })).toBe(kept.models) + const refused = plugin({ fetchImpl: async () => json(401, {}) }) + await expect(refused.provider.models(kept, { auth })).rejects.toMatchObject({ signIn: "expired" }) + const junk = plugin({ fetchImpl: async () => json(200, { nope: 1 }) }) + await expect(junk.provider.models(kept, { auth })).rejects.toThrow("no model list") + }) +}) + +describe("helpers", () => { + test("parseModels drops routers, hidden, classifier and tool-less models", () => { + expect(parseModels(MODELS).map((m) => m.id)).toEqual(["claude-sonnet-5-5", "claude-opus-5-5", "gpt-6-sol", "accounts/fireworks/models/glm-5p3"]) + expect(() => parseModels({ model_groups: [] })).toThrow() + }) + test("aliases are the last path part unless two ids share it", () => { + const a = aliasesFor(["a/x/glm", "b/glm", "claude-opus-5-5"]) + expect(a.get("a/x/glm")).toBe("a--x--glm") + expect(a.get("b/glm")).toBe("b--glm") + expect(a.get("claude-opus-5-5")).toBe("claude-opus-5-5") + }) + test("priceRef finds OpenRouter ids", () => { + expect(priceRef("claude-sonnet-5-5").orIds).toContain("anthropic/claude-sonnet-5.5") + expect(priceRef("accounts/fireworks/models/glm-5p3")).toMatchObject({ fireworks: true, orIds: ["z-ai/glm-5.3"] }) + expect(priceRef("google/gemma-4-26b-a4b-it").orIds[0]).toBe("google/gemma-4-26b-a4b-it") + }) + test("usageCost uses the long-context tier past its threshold", () => { + const entry = { p: [1, 2, 0.1, null], longAt: 1000, long: [2, 4, 0.2, null] } + expect(usageCost(entry, { prompt_tokens: 999, completion_tokens: 0 }).usd).toBeCloseTo(999 / 1e6) + expect(usageCost(entry, { prompt_tokens: 1000, completion_tokens: 0 }).usd).toBeCloseTo(2000 / 1e6) + }) + test("credits round every call up", () => { + expect(creditsFor(0)).toBe(0) + expect(creditsFor(0.0001)).toBe(1) + expect(creditsFor(0.005)).toBe(1) + expect(creditsFor(0.0051)).toBe(2) + }) + test("the store anchors each source once and survives a missing file", () => { + const s = new Store(undefined, () => 5) + expect(s.anchor("u", 100, "a")).toBe(true) + s.change("u", (a) => (a.spent += 10)) + expect(s.anchor("u", 100, "a")).toBe(false) + expect(s.remaining("u")).toBe(90) + expect(s.price("claude-opus-5-5").p).toEqual(FALLBACK_PRICES["claude-opus-5-5"]) + }) + test("a balance applied late still counts the calls made after it was read", () => { + const s = new Store(undefined, () => 50) + s.change("u", (a) => { + Store.spend(a, 7, 10) + Store.spend(a, 3, 30) + }) + expect(s.anchor("u", 100, "login:20", 20)).toBe(true) + expect(s.remaining("u")).toBe(97) + }) +}) diff --git a/packages/gumloop/opencode.mjs b/packages/gumloop/opencode.mjs new file mode 100644 index 0000000..035a321 --- /dev/null +++ b/packages/gumloop/opencode.mjs @@ -0,0 +1 @@ +export { GumloopPlugin } from "./index.mjs" diff --git a/packages/gumloop/opencode2.mjs b/packages/gumloop/opencode2.mjs new file mode 100644 index 0000000..364ea8a --- /dev/null +++ b/packages/gumloop/opencode2.mjs @@ -0,0 +1,596 @@ +// The OpenCode 2.x face of a package whose plugins are written for +// OpenCode 1.x (and magpie's plugin host). +// +// OpenCode 2.x loads a package's `exports["."]` and wants its default to be +// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions +// (plugins#657). This file is that default. It runs each 1.x plugin the +// package's opencode.mjs exports and hands 2.x what the plugin's hooks say: +// +// auth.methods → the integration's sign-in methods +// config() → the provider, its package, base URL and models +// provider.models → the signed-in account's own model list +// auth.loader → each request's base URL, key, headers and fetch +// +// What 2.x has no place for is left out: chat.headers and chat.params +// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin, +// tools and events. +// +// scripts/opencode2.mjs is the one copy that is edited. Every package that +// has it carries the same bytes as packages//opencode2.mjs, and +// scripts/check.mjs fails when a copy differs. + +import { readFileSync } from "node:fs" +import * as v1 from "./opencode.mjs" + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + +// The key the SDK is made with: the account's own goes on each request in +// its place (see wrapFetch), so a key read when the SDK was made can't go +// out after the account changed. +const PLACEHOLDER = "opencode2-v1-key" + +// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from +// swapping @ai-sdk/* for its native providers, which never call the sdk +// hook below; openai-compatible's is the one 2.x ships, the others are AI +// SDK v6's dist-tag, the line 2.x's bridge runs. +export function packageOf(npm) { + const name = npm || "@ai-sdk/openai-compatible" + if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41" + if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6` + return `aisdk:${name}` +} + +// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read +// them: a default {server} is the one plugin, else every function export +// and every {server} object. +export function pluginsOf(mod) { + const d = mod?.default + if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d)) + return typeof d.server === "function" ? [d.server] : [] + const out = [] + for (const value of Object.values(mod ?? {})) { + const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null + if (fn && !out.includes(fn)) out.push(fn) + } + return out +} + +const int = (n, fallback = 0) => { + const v = Math.trunc(Number(n)) + return Number.isFinite(v) && v >= 0 ? v : fallback +} +const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0) +const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}) +const json = (v) => { + try { + return JSON.parse(JSON.stringify(v ?? null)) + } catch { + return null + } +} +const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string")) +const nonEmpty = (o) => (Object.keys(o).length ? o : undefined) + +// connKey names a connection the way 2.x does. +const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`) + +// ---- sign-in ------------------------------------------------------------ + +// fields is a 1.x method's prompts as a 2.x form. +export function fieldsOf(prompts) { + const out = [] + for (const p of prompts ?? []) { + if (!p?.key) continue + const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) } + if (p.placeholder) f.placeholder = String(p.placeholder) + if (p.type === "select" && Array.isArray(p.options)) + f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) + // a prompt shown only when another answer says so can't be required, and + // neither can one whose own validate() accepts an empty answer (the + // browser sign-in's optional API key) + if (!p.condition && p.required !== false) f.required = true + out.push(f) + } + return out.length ? out : undefined +} + +// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes +// auth.json: the result without its type and provider. +function v1Saved(r) { + const { type: _t, provider: _p, ...rest } = r + if ("key" in r) return { type: "api", ...rest } + return { type: "oauth", ...rest } +} + +// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for +// both kinds, the 1.x auth kept whole in its metadata. No refresh is +// registered, so 2.x hands the credential over as it is and the plugin's +// own loader renews it, as it does on 1.x. +export function credentialOf(methodID, r) { + if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed") + const saved = json(v1Saved(r)) + if (saved.type === "api") + return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } } + return { + type: "oauth", + methodID, + access: String(saved.access ?? ""), + refresh: String(saved.refresh ?? ""), + expires: int(saved.expires), + metadata: { v1: saved }, + } +} + +// authOfValue is the 1.x auth a 2.x credential stands for. +export function authOfValue(value) { + if (!value) return null + if (value.type === "oauth") { + const v1 = record(value.metadata).v1 + if (v1 && typeof v1 === "object") return v1 + return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires } + } + if (value.type === "key") { + const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {} + return { type: "api", key: value.key, ...meta } + } + return null +} + +const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""]) + +// ---- models ------------------------------------------------------------- + +const MODALITIES = ["text", "audio", "image", "video", "pdf"] + +// internalOf is a config model as 1.x hands it to provider.models: what +// fromModelsDevModel makes of it, with the config's own variants. +export function internalOf(providerID, conf, key, m) { + const mods = record(m.modalities) + const has = (list, k) => Array.isArray(list) && list.includes(k) + const cost = record(m.cost) + return { + ...m, + id: key, + providerID, + name: m.name ?? key, + api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" }, + status: m.status ?? "active", + headers: m.headers ?? {}, + options: m.options ?? {}, + cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } }, + limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) }, + capabilities: { + temperature: m.temperature ?? false, + reasoning: m.reasoning ?? false, + attachment: m.attachment ?? false, + toolcall: m.tool_call ?? true, + input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])), + output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])), + interleaved: m.interleaved ?? false, + }, + release_date: m.release_date ?? "", + variants: record(m.variants), + } +} + +// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info. +export function modelOf(providerID, provider, key, m) { + const caps = record(m.capabilities) + const listFrom = (obj, list) => { + if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k]) + if (Array.isArray(list)) return list.map(String) + return ["text"] + } + const input = listFrom(caps.input, m.modalities?.input) + const output = listFrom(caps.output, m.modalities?.output) + const c = record(m.cost) + const cache = record(c.cache) + const npm = m.api?.npm ?? m.provider?.npm + const url = m.api?.url ?? m.provider?.api + const settings = { ...record(json(m.options)) } + if (url && url !== provider.baseURL) settings.baseURL = url + const variants = Object.entries(record(m.variants)) + .filter(([, v]) => !record(v).disabled) + .map(([id, v]) => { + const { disabled: _d, ...rest } = record(json(v)) + return nonEmpty(rest) ? { id, settings: rest } : { id } + }) + const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active" + const out = { + id: key, + modelID: String(m.api?.id ?? m.id ?? key), + providerID, + name: String(m.name ?? key), + capabilities: { + tools: caps.toolcall ?? m.tool_call ?? true, + input: input.length ? input : ["text"], + output: output.length ? output : ["text"], + ...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}), + }, + variants, + time: { released: Date.parse(m.release_date ?? "") || 0 }, + cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }], + status, + enabled: true, + limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 }, + } + if (m.limit?.input) out.limit.input = int(m.limit.input) + if (npm && npm !== provider.npm) out.package = packageOf(npm) + if (nonEmpty(settings)) out.settings = settings + const headers = strings(m.headers) + if (nonEmpty(headers)) out.headers = headers + return out +} + +// ---- requests ----------------------------------------------------------- + +const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input)) + +// wrapFetch sends a request the SDK made from the provider's settings the +// way 1.x would have sent it with the loader's options: the loader's base +// URL in place of the configured one, the account's key in place of the +// placeholder, the loader's headers added, through the loader's fetch. +export function wrapFetch(next, base, options) { + return async (input, init = {}) => { + const o = await options() + let url = urlOf(input) + const from = String(base ?? "").replace(/\/+$/, "") + const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : "" + if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length) + const req = input instanceof Request ? input : null + const headers = new Headers(init.headers ?? req?.headers ?? undefined) + for (const [k, v] of [...headers.entries()]) { + if (!v.includes(PLACEHOLDER)) continue + if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key)) + else headers.delete(k) + } + for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v) + const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch + if (req && init.body === undefined) { + const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text() + return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal }) + } + return send(url, { ...init, headers }) + } +} + +// ---- one plugin --------------------------------------------------------- + +async function setupPlugin(ctx, fn, live) { + const directory = ctx?.location?.directory ?? process.cwd() + // the active account each provider was last read for, and the renewed + // auth a plugin saved for it (2.x has no way for a plugin to write a + // credential back, so it is kept in the plugin's storage, under the + // credential it renews and the token it was renewed from) + const current = new Map() + const saved = new Map() + const signingIn = new Map() + const storeKey = (id, key) => `v1auth/${id}/${key}` + + const client = { + auth: { + async set(arg) { + const id = arg?.path?.id + const body = json(arg?.body) + const cur = id && current.get(id) + // a sign-in's own saves belong to the credential it is about to + // make, not the one that was active when it started + if (!cur || !body || signingIn.get(id) > 0) return { data: true } + const entry = { fp: cur.fp, auth: body } + saved.set(storeKey(id, cur.key), entry) + await Promise.resolve() + .then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry)) + .catch(() => {}) + return { data: true } + }, + async get() { + return { data: undefined } + }, + }, + app: { log: async () => ({ data: true }) }, + } + + const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {} + const cfg = { provider: {} } + try { + await hooks.config?.(cfg) + } catch {} + const auth = hooks.auth + const authID = auth?.provider ? String(auth.provider) : undefined + const providers = record(cfg.provider) + + // getAuth reads the active account: the credential 2.x holds, or what the + // plugin last saved renewing it. + const getAuth = async (id) => { + const connection = await ctx.integration.connection.active(id).catch(() => undefined) + if (!connection) { + current.delete(id) + return undefined + } + const value = await ctx.integration.connection.resolve(connection).catch(() => undefined) + const base = authOfValue(value) + if (!base) { + current.delete(id) + return undefined + } + const key = connKey(connection) + const fp = fingerprint(base) + // ours: a credential one of this plugin's own sign-ins made + const ours = value?.type === "oauth" && !!record(value.metadata).v1 + current.set(id, { key, fp, ours }) + const sk = storeKey(id, key) + let entry = saved.get(sk) + if (!entry) { + entry = await Promise.resolve() + .then(() => ctx.storage?.get?.(sk)) + .catch(() => undefined) + if (entry) saved.set(sk, entry) + } + return entry && entry.fp === fp && entry.auth ? entry.auth : base + } + + // the sign-in methods + if (authID && Array.isArray(auth.methods) && auth.methods.length) { + const label = (c) => { + const a = authOfValue(c) + const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account + return typeof name === "string" && name ? name : undefined + } + const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1) + const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1)) + const title = record(providers[authID]).name + // 2.x runs a transform again on every reload, from nothing + await ctx.integration.transform((editor) => { + let keyed = false + // the integration 2.x makes for an id it doesn't know is named by the + // id; the provider's own name reads better in the sign-in list + if (typeof title === "string" && title) + try { + editor.update?.(authID, (i) => { + if (i && (!i.name || i.name === authID)) i.name = title + }) + } catch {} + auth.methods.forEach((m, i) => { + if (!m) return + const methodID = `v1-${i}` + const form = fieldsOf(m.prompts) + if (m.type === "api" && typeof m.authorize !== "function") { + if (keyed) return + keyed = true + editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } }) + return + } + if (typeof m.authorize !== "function") return + editor.method.update({ + integrationID: authID, + method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) }, + async authorize(answer) { + begin() + let ended = false + const done = () => { + if (!ended) end() + ended = true + } + try { + const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)])) + const r = await m.authorize(inputs) + if (m.type === "api") { + done() + return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) } + } + if (r?.method === "code") + return { + url: String(r.url ?? ""), + instructions: String(r.instructions ?? ""), + mode: "code", + callback: async (code) => { + try { + return credentialOf(methodID, await r.callback(code)) + } finally { + done() + } + }, + } + const callback = Promise.resolve() + .then(() => r.callback()) + .then((res) => credentialOf(methodID, res)) + .finally(done) + callback.catch(() => {}) + return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback } + } catch (e) { + done() + throw e + } + }, + label, + }) + }) + }) + } + + // the loader's options for the account signed in now, read again when + // the account changes + let loaded = null + const loaderOptions = async (id) => { + if (id !== authID || typeof auth?.loader !== "function") { + const a = authID === id ? await getAuth(id) : undefined + return { key: a?.type === "api" ? a.key : undefined } + } + const a = await getAuth(id) + if (!a) return {} + const fp = current.get(id)?.key + "\0" + fingerprint(a) + if (loaded?.fp !== fp) { + const p = Promise.resolve() + .then(() => auth.loader(() => getAuth(id), providerOf(id))) + .then((o) => record(o)) + loaded = { fp, p } + p.catch(() => { + if (loaded?.fp === fp) loaded = null + }) + } + const o = await loaded.p + const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined + return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch } + } + + // the providers, with the list the account's own read last gave each + const source = new Map() + // providerOf is a provider as 1.x hands it to provider.models and + // auth.loader + const providerOf = (id) => { + const conf = record(providers[id]) + const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))])) + return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models } + } + const listed = new Set() + for (const [id, conf0] of Object.entries(providers)) { + const conf = record(conf0) + // a provider entry that only names the sign-in (no package, no models) + // is not a provider of models + if (!conf.npm && !Object.keys(record(conf.models)).length) continue + const options = record(conf.options) + const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options + // with no base URL the config leaves it to the loader: a name that + // can't resolve stands in for it, and each request swaps in the + // loader's (wrapFetch) + const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid` + const npm = conf.npm ?? "@ai-sdk/openai-compatible" + const info = { + id, + ...(id === authID ? { integrationID: id } : {}), + name: String(conf.name ?? id), + activation: "auto", + package: packageOf(npm), + settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) }, + } + const headers = { ...strings(conf.headers), ...strings(optHeaders) } + if (nonEmpty(headers)) info.headers = headers + const prov = { baseURL, npm } + const fromConfig = () => + Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m)))) + listed.add(id) + await ctx.provider.transform((editor) => { + const s = source.get(id) + editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection }) + }) + source.set(id, { conf, prov, models: null, connection: undefined }) + } + + // each request: the placeholder key, and the fetch that swaps in the + // account's. A provider the package doesn't list (one 2.x has built in + // that the plugin only signs in to) is left to 2.x unless the plugin's + // loader serves it and one of the plugin's own sign-ins is active. + const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : [] + for (const id of new Set([...listed, ...own])) { + const base = source.get(id)?.prov.baseURL + await ctx.aisdk.hook( + "sdk", + async (evt) => { + const opts = evt.options + if (!opts || opts.__opencode2) return + if (!listed.has(id)) { + await getAuth(id) + if (!current.get(id)?.ours) return + } + opts.__opencode2 = true + opts.apiKey = PLACEHOLDER + opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id)) + }, + { providerID: id }, + ) + } + + // refresh reads the account's own list after a sign-in or a switch + const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined + let refreshing = null + let again = false + // the account the list was last read for: a credential.updated that + // leaves it as it was reads nothing again + let readFor = null + const stateOf = async () => { + const c = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = c ? await getAuth(authID) : undefined + return connKey(c) + "\0" + (a ? fingerprint(a) : "") + } + const refresh = () => { + if (refreshing) { + again = true + return refreshing + } + refreshing = (async () => { + try { + if (!authID || !source.has(authID)) return + const s = source.get(authID) + const connection = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = connection ? await getAuth(authID) : undefined + readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + if (!a || listID !== authID || typeof hooks.provider?.models !== "function") { + if (s.connection || s.models) { + s.connection = undefined + s.models = null + await ctx.provider.reload() + } + return + } + const provider = providerOf(authID) + let got + try { + got = await hooks.provider.models(provider, { auth: a }) + } catch { + got = null + } + if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) { + again = true + return + } + s.connection = connection + s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null + await ctx.provider.reload() + await ctx.model?.reload?.() + } finally { + refreshing = null + if (again && live.on) { + again = false + void refresh() + } + } + })() + return refreshing + } + + if (authID && ctx.event?.subscribe) + void (async () => { + try { + // a switch names the integration; an update (a sign-in, a removal) + // names nothing, so it reads again only when this account changed + const types = ["credential.switched", "credential.updated"] + for await (const event of ctx.event.subscribe({ types })) { + if (!live.on) return + if (event?.type === "credential.switched" && event?.data?.integrationID === authID) { + loaded = null + await refresh() + } else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) { + await refresh() + } + } + } catch {} + })() + void refresh() +} + +export async function setup(ctx, mod = v1) { + const live = { on: true } + for (const fn of pluginsOf(mod)) { + try { + await setupPlugin(ctx, fn, live) + } catch (e) { + // one plugin failing to start leaves the package's others working + console.error(`${pkg.name}: ${e?.message ?? e}`) + } + } + return () => { + live.on = false + } +} + +export default { id: pkg.name, setup: (ctx) => setup(ctx) } diff --git a/packages/gumloop/package.json b/packages/gumloop/package.json new file mode 100644 index 0000000..2e4c526 --- /dev/null +++ b/packages/gumloop/package.json @@ -0,0 +1,36 @@ +{ + "name": "@magpie-community/opencode-gumloop-auth", + "version": "0.1.0", + "description": "Gumloop (gumloop.com) with your API key and user id in OpenCode and magpie: per-account models, and a credit estimate Gumloop's API doesn't give", + "homepage": "https://www.gumloop.com/", + "type": "module", + "main": "./opencode.mjs", + "exports": { ".": "./opencode2.mjs" }, + "files": [ + "index.mjs", + "gumloop.mjs", + "opencode.mjs", + "opencode2.mjs", + "README.md", + "LICENSE" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "magpie", + "gumloop" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/magpie-community/plugins", + "directory": "packages/gumloop" + }, + "scripts": { + "test": "bun test" + }, + "magpie": { + "icon": "https://www.gumloop.com/favicon.ico", + "maxConcurrency": 4 + } +} diff --git a/packages/gumloop/regression.test.mjs b/packages/gumloop/regression.test.mjs new file mode 100644 index 0000000..0994c2f --- /dev/null +++ b/packages/gumloop/regression.test.mjs @@ -0,0 +1,662 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { spawn } from "node:child_process" +import { once } from "node:events" +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { createInterface } from "node:readline" +import { GumloopPlugin, _internal } from "./index.mjs" +import { LOCK_STALE_MS, LOCK_WAIT_MS, Store } from "./gumloop.mjs" + +const auth = { type: "api", key: "mock-regression-key", metadata: { userId: "regression-user" } } +const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }) +const dirs = [] +function tempDir() { + const dir = mkdtempSync(join(tmpdir(), "gumloop-regression-")) + dirs.push(dir) + return dir +} +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) +}) +const fake = async (url) => url.includes("openrouter.ai") + ? json({ data: [] }) + : url.includes("/models") + ? json({ model_groups: [] }) + : json({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 5 } }) +async function chat(plugin) { + const loaded = await plugin.auth.loader(async () => auth) + const res = await loaded.fetch(`${loaded.baseURL}/chat/completions`, { + method: "POST", + body: JSON.stringify({ model: "gpt-6-sol", messages: [] }), + }) + const body = await res.text() + return { res, body } +} + +async function holdLock(directory, runtime = process.execPath, phase = "held") { + // Pause real lock code at precise crash windows, without changing the + // filesystem operations. The uninstrumented concurrency tests stay below. + let source = readFileSync(new URL("./gumloop.mjs", import.meta.url), "utf8") + const pause = 'process.stdout.write("ready\\n"); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);' + if (phase === "partial") { + source = source.replace("// Fully written before publication.", `writeFileSync(temporary, '{"pid":'); ${pause}`) + } else if (phase === "choosing") { + source = source.replace("publish(0)", `publish(0); ${pause}`) + } + const module = phase === "held" ? new URL("./gumloop.mjs", import.meta.url).href + : `data:text/javascript;base64,${Buffer.from(source).toString("base64")}` + const script = ` + const { Store } = await import(${JSON.stringify(module)}); + new Store(${JSON.stringify(join(directory, "gumloop-ledger.json"))}).withLock(() => { ${pause} }); + ` + const child = spawn(runtime, ["--input-type=module", "--eval", script], { stdio: ["ignore", "pipe", "pipe"] }) + const lines = createInterface({ input: child.stdout }) + const done = once(child, "exit") + let errors = "" + child.stderr.on("data", (chunk) => { errors += chunk }) + const stop = async () => { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL") + await done + lines.close() + } + try { + const ready = await Promise.race([ + once(lines, "line").then(([line]) => line), + done.then(() => { throw new Error(`Lock child exited before ready: ${errors}`) }), + ]) + expect(ready).toBe("ready") + return { child, stop } + } catch (e) { + await stop() + throw e + } +} + +describe("exclusive ledger updates", () => { + test("a live old owner bounds waiting; after forced death the next chat recovers", async () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + const store = new Store(file) + store.anchor(auth.metadata.userId, 5000, "initial") + const before = readFileSync(file) + const owner = await holdLock(directory) + const lock = join(directory, readdirSync(directory).find((name) => name.includes(".lock.") && name.endsWith(".json"))) + let callbacks = 0 + const start = performance.now() + try { + expect(store.change(auth.metadata.userId, () => callbacks++)).toBeUndefined() + expect(store.anchor(auth.metadata.userId, 1, "blocked")).toBeUndefined() + store.setPrices({ "gpt-6-sol": { p: [99, 99] } }) + const p = _internal.createPlugin({ directory, magpie: true, fetchImpl: fake }) + expect((await chat(p)).res.status).toBe(200) + expect(callbacks).toBe(0) + expect(readFileSync(file)).toEqual(before) + expect(existsSync(lock)).toBe(true) + expect(performance.now() - start).toBeGreaterThanOrEqual(900) + expect(performance.now() - start).toBeLessThan(4000) + } finally { + await owner.stop() + } + expect(() => process.kill(owner.child.pid, 0)).toThrow() + const recovered = _internal.createPlugin({ directory, magpie: true, fetchImpl: fake }) + expect((await chat(recovered)).res.status).toBe(200) + expect(store.remaining(auth.metadata.userId)).toBe(4999) + expect(store.account(auth.metadata.userId).month).toMatchObject({ calls: 1, credits: 1 }) + expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) + }, 15000) + + test("a leftover lock record with a live foreign PID blocks at most LOCK_WAIT_MS while fresh and is removed once older than LOCK_STALE_MS", async () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + const store = new Store(file) + store.anchor(auth.metadata.userId, 5000, "initial") + const uuid = "00000000-0000-4000-8000-000000000001" + const lockPath = join(directory, `gumloop-ledger.json.lock.${process.ppid}.${uuid}.json`) + writeFileSync(lockPath, JSON.stringify({ pid: process.ppid, name: `${process.ppid}.${uuid}`, ticket: 3 })) + + const p = _internal.createPlugin({ directory, magpie: true, fetchImpl: fake }) + const t0 = performance.now() + expect((await chat(p)).res.status).toBe(200) + expect(performance.now() - t0).toBeGreaterThanOrEqual(LOCK_WAIT_MS - 50) + expect(performance.now() - t0).toBeLessThan(800) + expect(store.remaining(auth.metadata.userId)).toBe(5000) + expect(existsSync(lockPath)).toBe(true) + + const old = new Date(Date.now() - LOCK_STALE_MS - 2000) + utimesSync(lockPath, old, old) + const t1 = performance.now() + expect((await chat(p)).res.status).toBe(200) + expect(performance.now() - t1).toBeLessThan(200) + expect(existsSync(lockPath)).toBe(false) + expect(store.remaining(auth.metadata.userId)).toBe(4999) + expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) + }) + + test("ignores stray lock filenames and cleans up stale or dead-PID ledger .tmp files", async () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + const store = new Store(file) + store.anchor(auth.metadata.userId, 5000, "initial") + const strayLock = join(directory, "gumloop-ledger.json.lock.bak") + const deadTmp = join(directory, "gumloop-ledger.json.99999999.1.tmp") + const staleLiveTmp = join(directory, `gumloop-ledger.json.${process.ppid}.2.tmp`) + writeFileSync(strayLock, "unexpected") + writeFileSync(deadTmp, "{}") + writeFileSync(staleLiveTmp, "{}") + const old = new Date(Date.now() - LOCK_STALE_MS - 2000) + utimesSync(strayLock, old, old) + utimesSync(staleLiveTmp, old, old) + + const p = _internal.createPlugin({ directory, magpie: true, fetchImpl: fake }) + expect((await chat(p)).res.status).toBe(200) + expect(store.remaining(auth.metadata.userId)).toBe(4999) + expect(existsSync(strayLock)).toBe(true) + expect(existsSync(deadTmp)).toBe(false) + expect(existsSync(staleLiveTmp)).toBe(false) + }) + + test("a host stalled longer than LOCK_WAIT_MS still completes an uncontended update", () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + new Store(file).anchor("u", 100, "initial") + const stall = new Int32Array(new SharedArrayBuffer(4)) + // No peer exists; the pause stands in for a GC, disk or antivirus stall + // between taking the deadline and the first contention check. + const store = new Store(file, Date.now, () => Atomics.wait(stall, 0, 0, LOCK_WAIT_MS + 100)) + let ran = false + expect(store.change("u", (a) => { + ran = true + a.spent += 1 + return a.spent + })).toBe(1) + expect(ran).toBe(true) + expect(store.remaining("u")).toBe(99) + expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) + }) + + test("an advanced injected Store clock does not treat a fresh live lock record as stale", () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + new Store(file).anchor("u", 100, "initial") + const uuid = "00000000-0000-4000-8000-000000000002" + const lockPath = join(directory, `gumloop-ledger.json.lock.${process.ppid}.${uuid}.json`) + writeFileSync(lockPath, JSON.stringify({ pid: process.ppid, name: `${process.ppid}.${uuid}`, ticket: 1 })) + const futureStore = new Store(file, () => Date.now() + LOCK_STALE_MS + 60_000) + let ran = false + expect(futureStore.change("u", () => { ran = true })).toBeUndefined() + expect(ran).toBe(false) + expect(existsSync(lockPath)).toBe(true) + }) + + test("waits for a peer in ticket 0 (choosing) state before entering critical section", () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + new Store(file).anchor("u", 100, "initial") + let enteredA = false + let enteredB = false + let choosingRan = false + const storeB = new Store(file) + const storeA = new Store(file, Date.now, () => { + choosingRan = true + // At this instant storeA has published ticket 0 on disk and chosen ticket 1, + // but has not yet published ticket 1. storeB sees storeA with ticket 0, + // picks ticket 1, and must wait on storeA's ticket 0 rather than entering. + expect(storeB.change("u", (a) => { + enteredB = true + a.spent += 10 + })).toBeUndefined() + }) + expect(storeA.change("u", (a) => { + enteredA = true + a.spent += 1 + return a.spent + })).toBe(1) + expect(choosingRan).toBe(true) + expect(enteredA).toBe(true) + expect(enteredB).toBe(false) + expect(storeB.remaining("u")).toBe(99) + }) + + for (const runtime of ["node", process.execPath]) { + for (const phase of ["held", "partial", "choosing"]) { + test(`${runtime === "node" ? "Node" : "Bun"} crash at ${phase} recovers without manual cleanup`, async () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + new Store(file).anchor(auth.metadata.userId, 5000, "initial", 1) + const before = readFileSync(file) + const owner = await holdLock(directory, runtime, phase) + await owner.stop() + let missing = false + try { process.kill(owner.child.pid, 0) } catch (e) { missing = e.code === "ESRCH" } + expect(missing).toBe(true) + expect(readFileSync(file)).toEqual(before) + const start = performance.now() + expect((await chat(_internal.createPlugin({ directory, magpie: true, fetchImpl: fake }))).res.status).toBe(200) + const store = new Store(file) + expect(store.remaining(auth.metadata.userId)).toBe(4999) + expect(store.account(auth.metadata.userId).month).toMatchObject({ calls: 1, credits: 1 }) + expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) + expect(performance.now() - start).toBeLessThan(2000) + }, 15000) + } + } + + test("a throwing callback runs once, preserves disk and releases its lock", () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + const store = new Store(file) + store.anchor("u", 100, "initial") + const before = readFileSync(file) + let calls = 0 + expect(() => store.change("u", (a) => { + calls++ + a.spent += 9 + throw new Error("callback failed") + })).toThrow("callback failed") + expect(calls).toBe(1) + expect(readFileSync(file)).toEqual(before) + expect(existsSync(`${file}.lock`)).toBe(false) + store.change("u", (a) => a.spent++) + expect(store.remaining("u")).toBe(99) + expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) + }) + + test("an acquisition filesystem error skips the callback and preserves existing bytes", () => { + const file = join(tempDir(), "not-a-directory") + writeFileSync(file, "keep") + const store = new Store(join(file, "ledger.json")) + let calls = 0 + expect(store.change("u", () => calls++)).toBeUndefined() + expect(calls).toBe(0) + expect(readFileSync(file, "utf8")).toBe("keep") + }) + + for (const [name, runtime] of [["Node", "node"], ["Bun", process.execPath]]) { + test(`${name}: two independent overlapping processes preserve all 200 chat charges`, async () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + new Store(file).anchor(auth.metadata.userId, 5000, "initial", 1) + // Both contenders encounter the same abandoned owner. Recovery must + // never unlink a new contender's record when another recoverer wins. + const abandoned = await holdLock(directory, runtime) + await abandoned.stop() + // No store instrumentation: each child uses the real response tap and + // filesystem store. The stdin barrier starts both fresh hosts together. + const source = ` + import { once } from "node:events"; + const { _internal } = await import(${JSON.stringify(new URL("./index.mjs", import.meta.url).href)}); + const p = _internal.createPlugin({ + directory: ${JSON.stringify(directory)}, magpie: true, + fetchImpl: async () => new Response(JSON.stringify({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 5 } })) + }); + const loaded = await p.auth.loader(async () => (${JSON.stringify(auth)})); + console.log(JSON.stringify({ ready: true })); + await once(process.stdin, "data"); + const start = Date.now(); + let successful = 0; + for (let i = 0; i < 100; i++) { + const res = await loaded.fetch(loaded.baseURL + "/chat/completions", { + method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) + }); + await res.text(); + if (res.status === 200) successful++; + await new Promise(resolve => setTimeout(resolve, 1)); + } + console.log(JSON.stringify({ start, end: Date.now(), successful })); + process.stdin.destroy(); + ` + const children = [0, 1].map(() => { + const child = spawn(runtime, ["--input-type=module", "--eval", source], { stdio: ["pipe", "pipe", "pipe"] }) + const lines = createInterface({ input: child.stdout }) + const ready = once(lines, "line") + const done = once(child, "exit") + let stderr = "" + child.stderr.on("data", (chunk) => { stderr += chunk }) + return { child, lines, ready, done, stderr: () => stderr } + }) + try { + const results = await Promise.all(children.map(async (c) => { + expect(JSON.parse((await c.ready)[0])).toEqual({ ready: true }) + const result = once(c.lines, "line") + return { c, result } + })) + for (const { c } of results) c.child.stdin.end("go\n") + const totals = await Promise.all(results.map(async ({ c, result }) => { + const value = JSON.parse((await result)[0]) + expect((await c.done)[0]).toBe(0) + expect(c.stderr()).toBe("") + return value + })) + expect(totals.map((v) => v.successful)).toEqual([100, 100]) + expect(Math.max(...totals.map((v) => v.start))).toBeLessThan(Math.min(...totals.map((v) => v.end))) + const account = JSON.parse(readFileSync(file, "utf8")).accounts[auth.metadata.userId] + expect(account.month).toMatchObject({ calls: 200, credits: 200 }) + expect(account.spent).toBe(200) + expect(account.charges).toHaveLength(200) + expect(new Store(file).remaining(auth.metadata.userId)).toBe(4800) + expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) + } finally { + for (const { child, lines } of children) { + if (child.exitCode === null) { + child.kill() + await once(child, "exit") + } + lines.close() + } + } + }, 15000) + } +}) + +describe("short-lived hosts finish accounting before terminal response bytes", () => { + for (const sse of [false, true]) { + test(`${sse ? "SSE" : "JSON"} terminal response is not visible before the last usage is charged`, async () => { + const first = { prompt_tokens: 10, completion_tokens: 1 } + const last = { prompt_tokens: 10, completion_tokens: 5 } + const text = sse + ? `data: {"choices":[{"delta":{"content":"Hi"}}]}\n\ndata: {"choices":[{"finish_reason":"stop"}]}\n\ndata: ${JSON.stringify({ usage: first })}\n\ndata: ${JSON.stringify({ usage: last })}\n\ndata: [DONE]\n\n` + : JSON.stringify({ choices: [], usage: last }) + let charged + let calls = 0 + const source = new ReadableStream({ + start(controller) { + // Split inside terminal frames and UTF-8-independent ASCII bytes. + for (let i = 0; i < text.length; i += 7) controller.enqueue(new TextEncoder().encode(text.slice(i, i + 7))) + controller.close() + }, + }) + const reader = _internal.tapUsage(source, sse, undefined, (usage) => { + calls++ + charged = usage + }).getReader() + let received = "" + while (true) { + const { value, done } = await reader.read() + if (done) break + received += new TextDecoder().decode(value) + if (sse ? received.includes('"finish_reason":"stop"}]}\n') : received.endsWith("}")) { + expect(charged).toEqual(last) + expect(calls).toBe(1) + } + } + expect(received).toBe(text) + expect(charged).toEqual(last) + expect(calls).toBe(1) + }) + } +}) + +describe("SSE byte boundaries and backpressure", () => { + const encode = (text) => new TextEncoder().encode(text) + const frame = 'data: {"choices":[{"delta":{"content":"hello"}}]}\n\n' + const settle = () => new Promise((resolve) => setTimeout(resolve, 10)) + async function readSoon(reader) { + let timer + try { + return await Promise.race([ + reader.read(), + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("SSE first read stalled")), 1000) }), + ]) + } finally { + clearTimeout(timer) + } + } + + test("DONE accounts before a combined content/terminal chunk is visible without waiting for EOF", async () => { + const usage = { prompt_tokens: 10, completion_tokens: 5 } + const text = frame + 'data: {"choices":[{"finish_reason":"stop"}]}\n\n' + + `data: ${JSON.stringify({ usage })}\n\ndata: [DONE]\n\n` + let upstream + const calls = [] + const source = new ReadableStream({ + start(controller) { upstream = controller; controller.enqueue(encode(text)) }, + }) + const reader = _internal.tapUsage(source, true, undefined, (...args) => calls.push(args)).getReader() + try { + expect((await readSoon(reader)).value).toEqual(encode(text)) + expect(calls).toEqual([[usage, false]]) + upstream.close() + expect((await readSoon(reader)).done).toBe(true) + expect(calls).toEqual([[usage, false]]) + } finally { + await reader.cancel() + } + }) + + test("101 cross-event chunks deliver complete frames while the source remains open", async () => { + let upstream + let pulls = 0 + let produced = 0 + const calls = [] + const source = new ReadableStream({ + start(controller) { upstream = controller }, + pull(controller) { + pulls++ + if (produced < 101) controller.enqueue(encode((produced++ === 0 ? frame : frame.slice(1)) + "d")) + }, + }) + const reader = _internal.tapUsage(source, true, undefined, (...args) => calls.push(args)).getReader() + const received = [] + try { + const first = await readSoon(reader) + expect(new TextDecoder().decode(first.value)).toBe(frame) + received.push(first.value) + await settle() + expect(pulls).toBeLessThanOrEqual(4) + const idlePulls = pulls + await settle() + expect(pulls).toBe(idlePulls) + for (let i = 1; i < 101; i++) received.push((await readSoon(reader)).value) + expect(calls).toEqual([]) + upstream.close() + while (true) { + const result = await readSoon(reader) + if (result.done) break + received.push(result.value) + } + expect(Buffer.concat(received)).toEqual(Buffer.from(frame.repeat(101) + "d")) + expect(calls).toEqual([[undefined, false]]) + } finally { + await reader.cancel() + } + }) + + test("a 10 MiB content source delivers immediately and cancellation does not drain it", async () => { + const large = frame.replace("hello", "x".repeat(65535)) + let pulls = 0 + let cancelled = 0 + let reason + const calls = [] + const source = new ReadableStream({ + pull(controller) { + if (pulls < 160) controller.enqueue(encode((pulls++ === 0 ? large : large.slice(1)) + "d")) + }, + cancel(value) { cancelled++; reason = value }, + }) + const reader = _internal.tapUsage(source, true, undefined, (...args) => calls.push(args)).getReader() + try { + expect(large.length * 160).toBeGreaterThan(10 * 1024 * 1024) + expect((await readSoon(reader)).value).toEqual(encode(large)) + await settle() + expect(pulls).toBeLessThanOrEqual(4) + await reader.cancel("consumer stopped") + await settle() + expect(cancelled).toBe(1) + expect(reason).toBe("consumer stopped") + const stoppedAt = pulls + await settle() + expect(pulls).toBe(stoppedAt) + expect(calls).toEqual([[undefined, true]]) + } finally { + await reader.cancel() + } + }) + + test("split UTF-8, LF, CRLF and an unterminated EOF frame preserve exact bytes", async () => { + const usage = { prompt_tokens: 10, completion_tokens: 5 } + const terminal = 'data: {"choices":[{"finish_reason":"stop"}]}\r\n\r\n' + const bytes = encode( + frame.replace("hello", "你好🙂é").replaceAll("\n", "\r\n") + + frame + terminal + `data: ${JSON.stringify({ usage })}\n\ndata: [DONE]`, + ) + let offset = 0 + let calls = 0 + let charged + const source = new ReadableStream({ + pull(controller) { + if (offset < bytes.length) controller.enqueue(bytes.slice(offset, ++offset)) + else controller.close() + }, + }) + const reader = _internal.tapUsage(source, true, undefined, (value) => { calls++; charged = value }).getReader() + const received = [] + try { + while (true) { + const result = await readSoon(reader) + if (result.done) break + received.push(result.value) + if (Buffer.concat(received).includes(Buffer.from(terminal))) { + expect(charged).toEqual(usage) + expect(calls).toBe(1) + } + } + expect(Buffer.concat(received)).toEqual(Buffer.from(bytes)) + expect(charged).toEqual(usage) + expect(calls).toBe(1) + } finally { + await reader.cancel() + } + }) + + for (const terminal of [false, true]) { + test(`${terminal ? "terminal tail" : "unterminated line"} overflow is bounded and preserves bytes`, async () => { + const prefix = terminal + ? 'data: {"choices":[{"finish_reason":"stop"}]}\n\ndata: {"usage":{"prompt_tokens":10,"completion_tokens":1}}\n\n' + : "data: " + const part = terminal ? ":" + "x".repeat(8190) + "\n" : "x".repeat(8192) + let pulls = 0 + const calls = [] + const source = new ReadableStream({ + pull(controller) { + if (pulls < 100) controller.enqueue(encode((pulls++ === 0 ? prefix : "") + part)) + else controller.close() + }, + }) + const reader = _internal.tapUsage(source, true, undefined, (...args) => calls.push(args)).getReader() + const received = [] + try { + const first = await readSoon(reader) + expect(first.value.byteLength).toBe(256 * 1024) + received.push(first.value) + expect(calls).toEqual([[undefined, true]]) + await settle() + expect(pulls).toBeLessThanOrEqual(36) + const idlePulls = pulls + await settle() + expect(pulls).toBe(idlePulls) + while (true) { + const result = await readSoon(reader) + if (result.done) break + received.push(result.value) + } + expect(Buffer.concat(received)).toEqual(Buffer.from(prefix + part.repeat(100))) + expect(calls).toEqual([[undefined, true]]) + } finally { + await reader.cancel() + } + }) + } +}) + +describe("OpenCode project ledger isolation", () => { + for (const [name, bytes] of [ + ["valid", '{ "accounts": { "regression-user": { "spent": 99 } }, "project": true }\n'], + ["corrupt", '{"accounts": broken'], + ]) { + test(`existing ${name} project ledger is untouched by calibration, chat and prices`, async () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + writeFileSync(file, bytes) + const p = await GumloopPlugin({ directory }, { balance: 7000 }) + await p.auth.loader(async () => auth) + expect(readFileSync(file, "utf8")).toBe(bytes) + const local = _internal.createPlugin({ directory, options: { balance: 7000 }, fetchImpl: fake }) + expect((await chat(local)).res.status).toBe(200) + expect((await local.auth.usage(async () => auth)).balance).toBe("6999 credits") + expect(readFileSync(file, "utf8")).toBe(bytes) + expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) + }) + } + test("Magpie persists calibration and chat charges and reloads them", async () => { + const directory = tempDir() + const p = await GumloopPlugin({ directory, magpie: {} }, { balance: 7000 }) + await p.auth.loader(async () => auth) + const local = _internal.createPlugin({ directory, magpie: true, fetchImpl: fake }) + expect((await chat(local)).res.status).toBe(200) + const store = new Store(join(directory, "gumloop-ledger.json")) + expect(store.remaining(auth.metadata.userId)).toBe(6999) + expect(store.account(auth.metadata.userId).month.calls).toBe(1) + }) +}) + +describe("structured credit refusals", () => { + const cases = [ + [403, { error: { code: "provider_error", message: "upstream credit_limit_exceeded" } }, false], + [403, { error: { message: "credit_limit_exceeded" } }, false], + [403, { message: "credit_limit_exceeded" }, false], + [403, "provider failed: credit_limit_exceeded", false], + [403, { error: null }, false], + [403, null, false], + [400, { error: { code: "provider_error", message: "credit_limit_exceeded" } }, false], + [429, { error: { code: "tier_limit" } }, false], + [403, { error: { code: "credit_limit_exceeded" } }, true], + [403, { error: { type: "credit_limit_exceeded" } }, true], + [403, { error: "credit_limit_exceeded" }, true], + [403, { code: "credit_limit_exceeded" }, true], + [402, { error: "Payment required" }, false], + [402, { error: { code: 402, message: "Insufficient credits" } }, false], + ] + for (const [status, body, exhausted] of cases) { + test(`${status} ${JSON.stringify(body)} ${exhausted ? "exhausts" : "preserves"} balance`, async () => { + const text = typeof body === "string" ? body : JSON.stringify(body) + const p = _internal.createPlugin({ + options: { balance: 5000 }, + fetchImpl: async (url) => url.includes("/models") ? fake(url) : new Response(text, { status }), + }) + const result = await chat(p) + expect(result.res.status).toBe(exhausted ? 429 : status) + expect(result.res.headers.get("x-magpie-sign-in")).toBe(exhausted || status === 403 ? "kept" : null) + if (!exhausted) expect(result.body).toBe(text) + expect((await p.auth.usage(async () => auth)).balance).toBe(exhausted ? "0 credits" : "5000 credits") + }) + } +}) + +describe("chat 403 checks account credentials with models", () => { + for (const status of [200, 401, 403, 500, "network"]) { + test(`upstream Invalid API key with models ${status}`, async () => { + let probes = 0 + let cancelled = 0 + const body = JSON.stringify({ error: { code: "provider_error", message: "Fireworks: Invalid API key" } }) + const p = _internal.createPlugin({ + fetchImpl: async (url, init) => { + if (!url.includes("/models")) return new Response(body, { status: 403, headers: { "x-original": "preserved" } }) + probes++ + const headers = new Headers(init.headers) + expect(headers.get("authorization")).toBe(`Bearer ${auth.key}`) + expect(headers.get("x-auth-key")).toBe(auth.metadata.userId) + if (status === "network") throw new Error("offline") + return new Response(new ReadableStream({ cancel() { cancelled++ } }), { status }) + }, + }) + const result = await chat(p) + expect(probes).toBe(1) + expect(cancelled).toBe(status === "network" ? 0 : 1) + expect(result.res.status).toBe(403) + expect(result.body).toBe(body) + expect(result.res.headers.get("x-original")).toBe("preserved") + expect(result.res.headers.get("x-magpie-sign-in")).toBe(status === 200 ? "kept" : status === 401 || status === 403 ? "expired" : null) + }) + } +}) diff --git a/registry.json b/registry.json index 30e2f74..1564cdc 100644 --- a/registry.json +++ b/registry.json @@ -1,6 +1,8 @@ { "version": 1, "plugins": [ + { "package": "@magpie-community/opencode-gumloop-auth", "name": "Gumloop", "icon": "https://www.gumloop.com/favicon.ico", "providers": ["gumloop"], "community": true, + "summary": { "en": "Gumloop with your API key and user ID: account models, streaming, tool calls and a locally calibrated credit estimate.", "zh": "使用 API key 和用户 ID 接入 Gumloop:按账号发现模型,支持流式响应、工具调用和本地校准的积分估算。" } }, { "package": "@magpie-community/opencode-agnes-auth", "name": "Agnes AI", "icon": "https://www.agnes-ai.com/images/biglogo.png", "providers": ["agnes"], "community": true, "summary": { "en": "Agnes AI international with Chrome browser sign-in: live OpenAI-compatible text models, Token Plan and Agent Plan usage, and the USD wallet balance.", "zh": "通过 Chrome 浏览器登录 Agnes AI 国际版:动态发现 OpenAI 兼容文本模型,显示 Token Plan、Agent Plan 用量与美元余额,无需手动复制会话 token。" } }, { "package": "@magpie-community/opencode-atomcode-auth", "name": "AtomCode", "icon": "https://atomgit.com/favicon.ico", "providers": ["atomcode"], "community": true,