diff --git a/packages/zen-free/README.md b/packages/zen-free/README.md index 7a383c8..9ae0ec5 100644 --- a/packages/zen-free/README.md +++ b/packages/zen-free/README.md @@ -22,8 +22,14 @@ The plugin discovers Zen's current free models, including their context windows and reasoning levels. Use `opencode-zen-free/`, for example `opencode-zen-free/big-pickle`. -Retired models and SystemOne models are excluded. Availability and rate -limits are set by Zen; the plugin has no remaining-quota data. +Retired models and SystemOne models are excluded. The list is asked +again each time the host lists models (magpie does this on start and every +hour): a model Zen no longer gives free leaves it, and a new free one joins +it. When Zen's list can't be read, the last list is kept. A request for a +model that isn't free now gets a 404 naming the free ones; one made free +since the last list is served after the list is asked again (at most once a +minute). Availability and rate limits are set by Zen; the plugin has no +remaining-quota data. ## Requests diff --git a/packages/zen-free/index.test.mjs b/packages/zen-free/index.test.mjs index 2e96f1b..7e72c54 100644 --- a/packages/zen-free/index.test.mjs +++ b/packages/zen-free/index.test.mjs @@ -22,12 +22,9 @@ async function fixture(t, input = {}) { res.writeHead(state.modelsStatus, { "content-type": "application/json" }); res.end( JSON.stringify({ - data: [ - { id: "chat-free" }, - { id: "responses-free" }, - { id: "messages-free" }, - { id: "paid" }, - ], + data: (state.ids ?? ["chat-free", "responses-free", "messages-free", "paid"]).map((id) => ({ + id, + })), }), ); } else if (req.url === "/catalog") { @@ -43,6 +40,7 @@ async function fixture(t, input = {}) { "responses-free": { provider: { npm: "@ai-sdk/openai" } }, "messages-free": { provider: { npm: "@ai-sdk/anthropic" } }, paid: { cost: { input: 3, output: 10 } }, + "late-free": {}, }, }, }), @@ -340,8 +338,12 @@ test("rejects paid models, wrong protocol and foreign URLs before sending infere await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); const loader = await plugin.auth.loader(publicAuth); const before = state.calls.length; + const paid = await loader.fetch(`${origin}/v1/chat/completions`, { + method: "POST", + body: JSON.stringify({ model: "paid", stream: true }), + }); + assert.equal(paid.status, 404); for (const [url, model] of [ - [`${origin}/v1/chat/completions`, "paid"], [`${origin}/v1/responses`, "chat-free"], ["https://other.example/v1/chat/completions", "chat-free"], ]) { @@ -380,3 +382,54 @@ test("chat headers are scoped to this provider and retain the conversation sessi ); assert.equal(out.headers["x-session-id"], "s1"); }); + +test("a refresh drops a model Zen no longer lists and adds one it lists now", async (t) => { + const { plugin, state } = await fixture(t); + const before = await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + assert.deepEqual(Object.keys(before).sort(), ["chat-free", "messages-free", "responses-free"]); + state.ids = ["chat-free", "messages-free", "late-free"]; + const after = await plugin.provider.models({ models: before }, { auth: await publicAuth() }); + assert.deepEqual(Object.keys(after).sort(), ["chat-free", "late-free", "messages-free"]); + assert.equal(after[Symbol.for("magpie.fellBack")], undefined); + // a failed list keeps the last one, said as fallen back + state.modelsStatus = 503; + const kept = await plugin.provider.models({ models: after }, { auth: await publicAuth() }); + assert.deepEqual(Object.keys(kept).sort(), ["chat-free", "late-free", "messages-free"]); + assert.equal(kept[Symbol.for("magpie.fellBack")], true); +}); + +test("a model no longer free is answered 404 naming the free ones, so only it is set aside", async (t) => { + const { plugin, state, origin } = await fixture(t); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + const before = state.calls.length; + const response = await loader.fetch(`${origin}/v1/chat/completions`, { + method: "POST", + body: JSON.stringify({ model: "gone-free", stream: true }), + }); + assert.equal(response.status, 404); + const body = await response.json(); + assert.match(body.error.message, /Model gone-free is not available/); + assert.match(body.error.message, /chat-free, messages-free, responses-free/); + // listed a moment ago: the list isn't asked again for it + assert.equal(state.calls.length, before); +}); + +test("a model made free since the list was read is served after the list is asked again", async (t) => { + const { plugin, state, origin } = await fixture(t); + await plugin.provider.models({ models: {} }, { auth: await publicAuth() }); + const loader = await plugin.auth.loader(publicAuth); + state.ids = ["chat-free", "late-free"]; + state.chatProtocol = "chat/completions"; + const realNow = Date.now; + Date.now = () => realNow() + 61_000; + t.after(() => { + Date.now = realNow; + }); + const response = await loader.fetch(`${origin}/v1/chat/completions`, { + method: "POST", + body: JSON.stringify({ model: "late-free", stream: true }), + }); + assert.equal(response.status, 200); + assert.equal(state.calls.at(-1).body.model, "late-free"); +}); diff --git a/packages/zen-free/package.json b/packages/zen-free/package.json index 6c5079e..c6099ee 100644 --- a/packages/zen-free/package.json +++ b/packages/zen-free/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zen-free-auth", - "version": "0.1.1", + "version": "0.1.2", "description": "OpenCode Zen free models through the public credential, with native streaming protocols", "type": "module", "main": "./index.mjs", diff --git a/packages/zen-free/provider.mjs b/packages/zen-free/provider.mjs index 0864b09..c252acd 100644 --- a/packages/zen-free/provider.mjs +++ b/packages/zen-free/provider.mjs @@ -17,6 +17,10 @@ const DOCS = const PATHS = { chat: "/chat/completions", responses: "/responses", anthropic: "/messages" }; const CORE_TOOLS = ["bash", "edit", "glob", "grep", "read"]; const OPENCODE_VERSION = "1.18.34"; +// How long a request for a model the last list didn't have waits before it +// asks Zen's list again: a model Zen made free since is served at once, +// and a model typed in by hand doesn't ask the list on every request. +const RELIST_AFTER = 60_000; function httpURL(value) { const url = new URL(value); @@ -122,6 +126,7 @@ async function server(_input, options = {}) { let metadata = bootstrapProvider; let protocols = {}; let listed = false; + let listedAt = 0; async function discover(signal) { const headers = { authorization: "Bearer public", "x-opencode-client": "cli" }; @@ -160,6 +165,7 @@ async function server(_input, options = {}) { } known = discovered; listed = true; + listedAt = Date.now(); return discovered; } @@ -206,11 +212,31 @@ async function server(_input, options = {}) { const body = await request.json(); if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Expected a JSON request object"); - if (!listed && !Object.hasOwn(known, body.model)) { + if ( + !Object.hasOwn(known, body.model) && + (!listed || Date.now() - listedAt >= RELIST_AFTER) + ) { await discover(request.signal); } - const model = known[body.model]; - if (!model || model.api.npm !== SDK[protocol]) { + const model = Object.hasOwn(known, body.model) ? known[body.model] : undefined; + if (!model) { + // Zen no longer gives it free, or never did: said as a model + // not served, so the caller sets this model aside and not the + // account, whose other free models are still served. + const free = Object.keys(known).sort().join(", "); + const name = typeof body.model === "string" ? body.model : ""; + return new Response( + JSON.stringify({ + type: "error", + error: { + type: "not_found_error", + message: `Model ${name} is not available as an OpenCode Zen free model now. Free models: ${free || "none"}.`, + }, + }), + { status: 404, headers: { "content-type": "application/json" } }, + ); + } + if (model.api.npm !== SDK[protocol]) { throw new Error( "Model is not an available free model for this protocol. Refresh the model list.", );