zen-free 0.1.15: an agent's prompt goes with OpenCode's environment block, so Zen serves it as OpenCode's

杨梅 on magpie's Discord: deepseek-v4.1-flash-free and glm-5.3-flash-free
answered from OpenCode, while the same models from Kimi Work and WorkBuddy
failed at once with 429 (magpie: "额度用尽").

Cause, found against opencode.ai from this machine on 2026-10-25: Zen's
free tier tells OpenCode's requests by the body, not the headers. A
request whose system messages carry OpenCode's environment block (`<env>`,
a `Working directory:` line, `</env>`) is served; one without gets a small
allowance a day, then 429 FreeUsageLimitError "Free usage limit reached.
Free models work in OpenCode", Retry-After to 00:00 UTC. Captured real
OpenCode 2.0.25 (sandbox HOME, MITM with a sandbox CA) and replayed its
request: 200. Its headers with another system prompt, or without tools:
429. Our headers (1.19.0 UA, /inference/v1) with its body: 200, so UA,
path (/inference/openai/v1 vs /inference/v1), session ids, project and
trace headers don't matter. Bisected the prompt to the <env> block: case
sensitive, needs "Working directory:", counts only in a system message
(in a user message or a tool description it doesn't), value free
("unknown", "/" and "" all pass), and still needs tools (the core
stand-ins already sent pass).

Fix: addEnvironment appends "<env>\n  Working directory: unknown\n</env>"
to the agent's first system message (a part of its own for content in
parts, a new first system message when there is none), Anthropic's
`system` and Responses' `instructions` likewise. A prompt that already
has a block, as OpenCode's does, goes as it is. The directory isn't known
in the plugin and the agent's own prompt says it, so it is said as
unknown, not a path that would mislead the model or leak the user's.

Run:
- Real, through the plugin's loader.fetch from this machine (whose
  non-OpenCode allowance was used up): a WorkBuddy-like request (its own
  system prompt, a Read tool, WorkBuddy UA) at origin/main's provider.mjs:
  deepseek-v4.1-flash-free 429 FreeUsageLimitError (2.3s), glm-5.3
  stream 429 (1.8s), the reporter's case. With this change: deepseek 200,
  glm-5.3 stream 200, big-pickle 200.
- tools-smoke.mjs, real: big-pickle and mimo-v2.6-flash-free, stream and
  not, 200 with a Bash call.
- New test, per protocol: the block added once after the agent's prompt,
  added with no prompt and for content in parts, added when the block is
  only in a user message, an OpenCode prompt left as it is. Red on
  origin/main's provider.mjs (3 of 3 fail), green with it.
- HOME=$(mktemp -d) bun test at the repo root: 2670 tests, 0 fail;
  bun scripts/check.mjs: ok.

Not tried: a Responses or Anthropic Messages free model against Zen
(Zen lists none free now; all eight are Chat), so where Zen looks for the
block on those two is a guess from Chat's. Kimi Work and WorkBuddy
themselves weren't run; their request was built by hand.
This commit is contained in:
yetone
2026-10-25 18:33:40 +08:00
parent 57598ad410
commit 564719b9d9
4 changed files with 134 additions and 1 deletions
+10
View File
@@ -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 (`<env>`, a `Working directory:`
line, `</env>`) 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
+69
View File
@@ -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 = /<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(/<env>/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, "<env>\n Working directory: /x\n</env>"));
assert.match(systemText(protocol, sent), ENV);
// OpenCode's own prompt already has one, and gets no second
const own = `${agentPrompt}\n<env>\n Working directory: /Users/me/project\n</env>`;
sent = await send(withPrompt(protocol, own, "hello"));
assert.equal(systemText(protocol, sent), own);
});
}
+1 -1
View File
@@ -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",
+54
View File
@@ -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: `<env>`, a
// `Working directory:` line and `</env>`, 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 `<ENV>` 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 = "<env>\n Working directory: unknown\n</env>";
const HAS_ENVIRONMENT = /<env>[\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