diff --git a/packages/zen-free/README.md b/packages/zen-free/README.md index a1d72d6..7c57311 100644 --- a/packages/zen-free/README.md +++ b/packages/zen-free/README.md @@ -74,6 +74,16 @@ itself (`bash`, `edit`, `glob`, `grep`, `read`), described as not available. A call of one of them the agent doesn't have reaches the agent like any other. +Zen's free tier also tells OpenCode's own requests by the environment +block every OpenCode prompt ends with (``, a `Working directory:` +line, ``) in a system message. Another agent's request without one +gets a small allowance a day and then `429 FreeUsageLimitError` ("Free +models work in OpenCode") until 00:00 UTC, while OpenCode's go through. +So a request whose system messages have no such block gets one added +after the agent's own prompt (Anthropic `system` and Responses +`instructions` likewise), its working directory said as unknown; a +prompt that has one, as OpenCode's does, goes as it is. + Now and then Zen closes a streamed Chat Completions reply before its `[DONE]`. When the reply has said something and no tool call of it is unfinished, it ends there as an ordinary answer, and its text says it was diff --git a/packages/zen-free/index.test.mjs b/packages/zen-free/index.test.mjs index 4729325..5ff7a9f 100644 --- a/packages/zen-free/index.test.mjs +++ b/packages/zen-free/index.test.mjs @@ -637,3 +637,72 @@ test("asks the inference API, also for a model listed at /zen/v1", async (t) => } assert.ok(!asked.some((url) => url.startsWith("https://opencode.ai/zen/")), asked.join("\n")); }); + +// Zen's free tier serves a request as OpenCode's only with OpenCode's +// environment block in a system message; without it an agent's request +// (Kimi Work's, WorkBuddy's) is 429 FreeUsageLimitError after a small +// daily allowance, while OpenCode's own goes through (杨梅 on magpie's +// Discord, 2026-10-25). +const ENV = /[\s\S]*Working directory:[\s\S]*<\/env>/; +const systemText = (protocol, body) => { + const text = (content) => + typeof content === "string" ? content : (content ?? []).map((part) => part.text).join("\n"); + if (protocol === "anthropic") return text(body.system); + if (protocol === "responses") + return [ + body.instructions ?? "", + ...(body.input ?? []).filter((m) => ["system", "developer"].includes(m.role)).map((m) => text(m.content)), + ].join("\n"); + return body.messages.filter((m) => m.role === "system").map((m) => text(m.content)).join("\n"); +}; +const agentPrompt = "You are WorkBuddy. Help the user."; +const withPrompt = (protocol, prompt, user) => + protocol === "anthropic" + ? { ...(prompt === undefined ? {} : { system: prompt }), messages: [{ role: "user", content: user }] } + : protocol === "responses" + ? Array.isArray(prompt) + ? { input: [{ role: "system", content: prompt }, { role: "user", content: user }] } + : { ...(prompt === undefined ? {} : { instructions: prompt }), input: [{ role: "user", content: user }] } + : { + messages: [ + ...(prompt === undefined ? [] : [{ role: "system", content: prompt }]), + { role: "user", content: user }, + ], + }; + +for (const { protocol, path, model } of protocols) { + test(`${protocol}: an agent's own prompt goes with OpenCode's environment block, once`, 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 send = async (body) => { + const response = await loader.fetch(`${origin}/v1/${path}`, { + method: "POST", + body: JSON.stringify({ model, stream: true, ...body }), + }); + await response.text(); + return state.calls.at(-1).body; + }; + // the agent's prompt is kept, first, and the block follows it + let sent = await send(withPrompt(protocol, agentPrompt, "hello")); + let system = systemText(protocol, sent); + assert.match(system, ENV); + assert.ok(system.startsWith(agentPrompt), system); + assert.equal(system.match(//g).length, 1); + if (protocol === "chat") assert.equal(sent.messages.filter((m) => m.role === "system").length, 1); + // an agent that sent no prompt gets one holding the block + sent = await send(withPrompt(protocol, undefined, "hello")); + assert.match(systemText(protocol, sent), ENV); + if (protocol === "chat") assert.equal(sent.messages[0].role, "system"); + // a prompt in parts gets a part of its own + sent = await send(withPrompt(protocol, [{ type: "text", text: agentPrompt }], "hello")); + assert.match(systemText(protocol, sent), ENV); + // the block in a user message doesn't count with Zen, so it is added + sent = await send(withPrompt(protocol, agentPrompt, "\n Working directory: /x\n")); + assert.match(systemText(protocol, sent), ENV); + // OpenCode's own prompt already has one, and gets no second + const own = `${agentPrompt}\n\n Working directory: /Users/me/project\n`; + sent = await send(withPrompt(protocol, own, "hello")); + assert.equal(systemText(protocol, sent), own); + }); +} diff --git a/packages/zen-free/package.json b/packages/zen-free/package.json index df6caf2..290cf63 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.14", + "version": "0.1.15", "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 e960652..d287350 100644 --- a/packages/zen-free/provider.mjs +++ b/packages/zen-free/provider.mjs @@ -110,6 +110,59 @@ function normalizeTools(body, protocol) { return { declared }; } +// Zen's free tier serves a request as OpenCode's own only when one of its +// system messages carries OpenCode's environment block: ``, a +// `Working directory:` line and ``, as every OpenCode prompt ends. +// A request without one (another agent's own prompt: Kimi Work's, +// WorkBuddy's) gets a small allowance a day, then 429 FreeUsageLimitError +// ("Free models work in OpenCode") until 00:00 UTC, whatever its headers +// say; the same request with the block added is served (tried against +// opencode.ai on 2026-10-25, deepseek-v4.1-flash-free and +// glm-5.3-flash-free). In a user message or a tool description it doesn't +// count, and `` or `working directory:` don't either. The directory +// isn't known here, and the agent's own prompt says it, so it is told as +// unknown rather than as a path that would mislead the model. +const ENVIRONMENT = "\n Working directory: unknown\n"; +const HAS_ENVIRONMENT = /[\s\S]*Working directory:[\s\S]*<\/env>/; + +function textOf(content) { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content.map((part) => (typeof part?.text === "string" ? part.text : "")).join("\n"); +} + +function withEnvironment(content) { + if (typeof content === "string") return content ? `${content}\n\n${ENVIRONMENT}` : ENVIRONMENT; + if (Array.isArray(content)) return [...content, { type: "text", text: ENVIRONMENT }]; + return ENVIRONMENT; +} + +const SYSTEM_ROLES = ["system", "developer"]; + +export function addEnvironment(body, protocol) { + if (protocol === "anthropic") { + if (!HAS_ENVIRONMENT.test(textOf(body.system))) body.system = withEnvironment(body.system); + return; + } + const messages = protocol === "chat" ? body.messages : body.input; + const system = Array.isArray(messages) + ? messages.filter((message) => SYSTEM_ROLES.includes(message?.role)) + : []; + if (system.some((message) => HAS_ENVIRONMENT.test(textOf(message.content)))) return; + if (protocol === "responses") { + if (!HAS_ENVIRONMENT.test(textOf(body.instructions))) + body.instructions = withEnvironment(body.instructions); + return; + } + // Added to the agent's own system message, so the prompt stays one + // system message, the same on every turn (its cache holds); one is put + // first when the agent sent none. + const first = system.find((message) => message.role === "system"); + if (first) first.content = withEnvironment(first.content); + else if (Array.isArray(messages)) messages.unshift({ role: "system", content: ENVIRONMENT }); + else body.messages = [{ role: "system", content: ENVIRONMENT }]; +} + const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; let lastStamp = 0; let counter = 0; @@ -319,6 +372,7 @@ async function server(_input, options = {}) { const streaming = body.stream === true; body.stream = true; const toolPolicy = normalizeTools(body, protocol); + addEnvironment(body, protocol); if (protocol === "chat") body.stream_options = { ...body.stream_options, include_usage: true }; // Only what OpenCode 1.19.0 itself sends to its gateway, so a