diff --git a/packages/zen-free/README.md b/packages/zen-free/README.md
index 666cad1..d6fc296 100644
--- a/packages/zen-free/README.md
+++ b/packages/zen-free/README.md
@@ -16,6 +16,14 @@ sends OpenCode 2.0.25's headers (`opencode/latest/2.0.25/cli`, its
session id under `x-session-affinity` and `x-session-id` too): update
the plugin.
+From 0.1.19 a request is OpenCode 2.2.5's, header for header and in its
+order, as captured from the release binary on 2026-11-01: its
+User-Agent (`opencode/latest/2.2.5/cli`, the version kept current from
+OpenCode's own updater), its `b3` and `traceparent` trace headers, and
+its project id, `sha1("directory:" + folder)` or the repository's remote,
+where 0.1.14 to 0.1.18 sent `global`. The model list goes as OpenCode
+too, not as Bun.
+
## Install
```sh
@@ -76,8 +84,8 @@ reply's text says so; a turn whose every call was left out ends as an
ordinary answer. Tools run in the agent.
Zen's free tier only answers a request that carries tools, so a request
-is sent with the five core OpenCode tools the agent doesn't declare
-itself (`bash`, `edit`, `glob`, `grep`, `read`), described as not
+is sent with the five core OpenCode 2 tools the agent doesn't declare
+itself (`edit`, `glob`, `grep`, `read`, `shell`), described as not
available. A call of one of them the agent doesn't have reaches the agent
like any other.
diff --git a/packages/zen-free/index.test.mjs b/packages/zen-free/index.test.mjs
index 689b7ea..d878802 100644
--- a/packages/zen-free/index.test.mjs
+++ b/packages/zen-free/index.test.mjs
@@ -1,10 +1,13 @@
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { once } from "node:events";
-import { readFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
+import { join } from "node:path";
+import { createHash } from "node:crypto";
import test from "node:test";
import { protocols, declaredTools, toolReply } from "./tool-fixtures.mjs";
-import { addEnvironment } from "./provider.mjs";
+import { addEnvironment, environment, latestVersion, projectID, traceHeaders, userAgent } from "./provider.mjs";
const subject = import("./index.mjs").then((module) => ({
default: { server: module.ZenFreePlugin },
@@ -15,7 +18,8 @@ async function fixture(t, input = {}) {
const server = createServer(async (req, res) => {
let text = "";
for await (const chunk of req) text += chunk;
- state.calls.push({ url: req.url, headers: req.headers, body: text && JSON.parse(text) });
+ const rawOrder = req.rawHeaders.filter((_, i) => i % 2 === 0).map((name) => name.toLowerCase());
+ state.calls.push({ url: req.url, headers: req.headers, rawOrder, body: text && JSON.parse(text) });
if (state.discoveryHang) {
state.onDiscovery?.();
return;
@@ -124,8 +128,14 @@ for (const { protocol, path, model } of protocols) {
const tool = protocol === "chat" ? raw.function : raw;
assert.match(tool.description, /Not available\. Never call this tool\./);
assert.equal((tool.parameters ?? tool.input_schema).additionalProperties, false);
- // Zen's free tier refuses a bash or read that takes nothing
- assert.equal(Object.keys((tool.parameters ?? tool.input_schema).properties).length, 1);
+ // Zen's free tier refuses a core tool that takes nothing
+ const schema = tool.parameters ?? tool.input_schema;
+ assert.equal(Object.keys(schema.properties).length, 1);
+ assert.deepEqual(schema.required, Object.keys(schema.properties));
+ // OpenCode 2's names and parameters, never 1.x's bash or filePath
+ assert.notEqual(tool.name, "bash");
+ assert.ok(!("filePath" in schema.properties));
+ if (protocol === "chat") assert.equal(tool.strict, false);
}
// A call of a tool the agent doesn't have reaches the agent as
// called, as a tool call, so the agent answers it with its own
@@ -161,13 +171,17 @@ test("keeps declared tools isolated between requests using the same loader", asy
assert.match(text, /"name"\s*:\s*"bash"/);
});
+// OpenCode 2.2.5 names a folder that isn't a git repository
+// sha1("directory:" + folder), and sends `global` only from a repository
+// with no remote and no commit; 0.1.14 to 0.1.18 sent `global` always.
+const homeProject = () => projectID(homedir());
for (const [input, supplied, expected] of [
- [{}, undefined, "global"],
- [{ project: { id: "magpie" } }, undefined, "global"],
+ [{}, undefined, homeProject],
+ [{ project: { id: "magpie" } }, undefined, homeProject],
[{ project: { id: "abc123", vcs: "git" } }, undefined, "abc123"],
[{}, "client-project", "client-project"],
]) {
- test(`uses OpenCode project identity ${expected}`, async (t) => {
+ test(`uses OpenCode project identity ${typeof expected === "function" ? "of the folder" : expected}`, async (t) => {
const { plugin, state, origin } = await fixture(t, input);
await plugin.provider.models({ models: {} }, { auth: await publicAuth() });
const loader = await plugin.auth.loader(publicAuth);
@@ -177,13 +191,108 @@ for (const [input, supplied, expected] of [
body: JSON.stringify({ model: "chat-free", stream: true }),
});
await response.text();
- assert.equal(state.calls.at(-1).headers["x-opencode-project"], expected);
- assert.equal(state.calls.at(-1).headers["user-agent"], "opencode/latest/2.0.25/cli");
+ const want = typeof expected === "function" ? expected() : expected;
+ assert.equal(state.calls.at(-1).headers["x-opencode-project"], want);
+ assert.notEqual(state.calls.at(-1).headers["x-opencode-project"], "global");
+ assert.equal(state.calls.at(-1).headers["user-agent"], "opencode/latest/2.2.5/cli");
});
}
-// The headers OpenCode 2.0.25's release binary sends to Zen, captured on
-// 2026-10-25: these and no others, whatever the caller sent. Zen's free
+test("names the project as OpenCode does: the stated folder, or its repository's remote", (t) => {
+ const root = mkdtempSync(join(tmpdir(), "zen-project-"));
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ const real = realpathSync(root);
+ const sha1 = (text) => createHash("sha1").update(text).digest("hex");
+ // a plain folder: what OpenCode 2.2.5 sent from ~/runs/zencap/home/work
+ assert.equal(projectID("/Users/yetone/runs/zencap/home/work"), "1132ded9876e9dc00df57eea7de251c155550345");
+ const plain = join(real, "plain");
+ mkdirSync(plain);
+ assert.equal(projectID(plain), sha1(`directory:${plain}`));
+ // a repository with a remote, from a folder inside it
+ const repo = join(real, "repo");
+ mkdirSync(join(repo, ".git"), { recursive: true });
+ mkdirSync(join(repo, "src"));
+ writeFileSync(
+ join(repo, ".git", "config"),
+ '[core]\n\tbare = false\n[remote "upstream"]\n\turl = https://example.com/x/y.git\n[remote "origin"]\n\turl = git@GitHub.com:magpie/app.git\n',
+ );
+ assert.equal(projectID(join(repo, "src")), sha1("git-remote:github.com/magpie/app"));
+ // one with no remote: its root folder
+ const bare = join(real, "bare");
+ mkdirSync(join(bare, ".git"), { recursive: true });
+ writeFileSync(join(bare, ".git", "config"), "[core]\n\tbare = false\n");
+ mkdirSync(join(bare, "sub"));
+ assert.equal(projectID(join(bare, "sub")), sha1(`directory:${bare}`));
+ const env = environment(join(bare, "sub"));
+ assert.match(env, /Is directory a git repo: yes/);
+ assert.match(env, new RegExp(`Workspace root folder: ${bare}\\n`));
+});
+
+// OpenCode's version is the one its own updater is told is latest; a
+// version that can't be read, or is older than the one built in, leaves
+// the built-in one.
+test("reads OpenCode's latest version from its updater, and keeps its own otherwise", async (t) => {
+ let reply = '{"version":"2.3.0","minimum":false}';
+ let asked;
+ const server = createServer((req, res) => {
+ asked = req.url;
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(reply);
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ t.after(() => {
+ server.closeAllConnections();
+ server.close();
+ });
+ const url = `http://127.0.0.1:${server.address().port}/update`;
+ assert.equal(await latestVersion(url), "2.3.0");
+ assert.equal(asked, "/update?current=2.2.5");
+ for (reply of ['{"version":"2.1.0"}', '{"version":"latest"}', "nope", "{}"]) {
+ assert.equal(await latestVersion(url), undefined, reply);
+ }
+ assert.equal(await latestVersion("http://127.0.0.1:1/none"), undefined);
+ assert.equal(userAgent("2.3.0"), "opencode/latest/2.3.0/cli");
+ // a plugin given the updater sends the version it names
+ reply = '{"version":"2.4.1"}';
+ const { state, origin } = await fixture(t);
+ const module = await subject;
+ const plugin = await module.default.server({}, {
+ baseURL: `${origin}/v1`,
+ catalogURL: `${origin}/catalog`,
+ docsURL: `${origin}/docs`,
+ versionURL: url,
+ });
+ await plugin.provider.models({ models: {} }, { auth: await publicAuth() });
+ const loader = await plugin.auth.loader(publicAuth);
+ const response = await loader.fetch(`${origin}/v1/chat/completions`, {
+ method: "POST",
+ body: JSON.stringify({ model: "chat-free", stream: true }),
+ });
+ await response.text();
+ assert.equal(state.calls.at(-1).headers["user-agent"], "opencode/latest/2.4.1/cli");
+ // the model list goes as OpenCode too, never as Bun
+ const list = state.calls.find((call) => call.url === "/v1/models");
+ assert.equal(list.headers["user-agent"], "opencode/latest/2.4.1/cli");
+});
+
+test("trace headers keep one trace a conversation and a new span each request", () => {
+ const first = traceHeaders("ses_trace_a");
+ const again = traceHeaders("ses_trace_a");
+ const other = traceHeaders("ses_trace_b");
+ const b3 = /^([0-9a-f]{32})-([0-9a-f]{16})-1-[0-9a-f]{16}$/;
+ const parent = /^00-([0-9a-f]{32})-([0-9a-f]{16})-01$/;
+ for (const trace of [first, again, other]) {
+ const [, id, span] = b3.exec(trace.b3);
+ assert.deepEqual(parent.exec(trace.traceparent).slice(1), [id, span]);
+ }
+ assert.equal(b3.exec(first.b3)[1], b3.exec(again.b3)[1]);
+ assert.notEqual(b3.exec(first.b3)[2], b3.exec(again.b3)[2]);
+ assert.notEqual(b3.exec(first.b3)[1], b3.exec(other.b3)[1]);
+});
+
+// The headers OpenCode 2.2.5's release binary sends to Zen, captured on
+// 2026-11-01, in its order: these and no others, whatever the caller sent. Zen's free
// tier refuses (429 FreeUsageLimitError) the User-Agent OpenCode 1.19.0
// sent, which 0.1.6 to 0.1.15 sent on every request, since 2026-10-26.
for (const [path, model, key] of [
@@ -208,7 +317,7 @@ for (const [path, model, key] of [
});
await response.text();
const sent = state.calls.at(-1).headers;
- assert.equal(sent["user-agent"], "opencode/latest/2.0.25/cli");
+ assert.equal(sent["user-agent"], "opencode/latest/2.2.5/cli");
assert.notEqual(sent["user-agent"], "claude-cli/2.1.0");
assert.equal(sent.accept, "*/*");
const own = Object.keys(sent).filter(
@@ -218,7 +327,9 @@ for (const [path, model, key] of [
own.sort(),
[
"accept",
+ "b3",
"content-type",
+ "traceparent",
"user-agent",
"x-opencode-client",
"x-opencode-project",
@@ -234,6 +345,28 @@ for (const [path, model, key] of [
// never goes on.
assert.equal(sent["x-session-affinity"], sent["x-opencode-session"]);
assert.equal(sent["x-session-id"], sent["x-opencode-session"]);
+ // in the order OpenCode's own request has on Bun, which the plugin
+ // host runs: the headers Bun knows first, then the rest sorted, then
+ // fetch's own Accept (so none is set here)
+ const order = state.calls.at(-1).rawOrder.filter(
+ (name) => !["host", "connection", "content-length", "accept-encoding"].includes(name),
+ );
+ assert.deepEqual(order, [
+ ...(path === "messages" ? [] : ["authorization"]),
+ "content-type",
+ "user-agent",
+ ...(path === "messages" ? ["anthropic-version"] : []),
+ "b3",
+ "traceparent",
+ ...(path === "messages" ? ["x-api-key"] : []),
+ "x-opencode-client",
+ "x-opencode-project",
+ "x-opencode-session",
+ "x-opencode-session-id",
+ "x-session-affinity",
+ "x-session-id",
+ "accept",
+ ]);
});
}
@@ -423,7 +556,7 @@ test("forces upstream streaming, preserves existing tools and returns the SSE bo
const sent = state.calls.at(-1);
assert.equal(sent.headers.authorization, "Bearer public");
assert.match(sent.headers["x-opencode-session"], /^ses_[0-9a-f]{9}ff[0-9a-f][0-9A-Za-z]{14}$/);
- // OpenCode 2.0.25 sends its own session id under both; a caller's
+ // OpenCode 2.2.5 sends its own session id under both; a caller's
// (session_123) never goes on.
assert.equal(sent.headers["x-session-affinity"], sent.headers["x-opencode-session"]);
assert.equal(sent.headers["x-session-id"], sent.headers["x-opencode-session"]);
@@ -433,7 +566,7 @@ test("forces upstream streaming, preserves existing tools and returns the SSE bo
assert.deepEqual(sent.body.tools[0], bash);
assert.deepEqual(
sent.body.tools.map((tool) => tool.function.name),
- ["bash", "edit", "glob", "grep", "read"],
+ ["bash", "edit", "glob", "grep", "read", "shell"],
);
});
@@ -469,7 +602,7 @@ for (const [path, model, key] of [
});
await response.text();
const sent = state.calls.at(-1);
- assert.equal(sent.body.tools[0].name, "bash");
+ assert.equal(sent.body.tools[0].name, "edit");
assert.equal(sent.body.tools[0][key].type, "object");
if (path === "messages") {
assert.equal(sent.headers["x-api-key"], "public");
@@ -730,7 +863,7 @@ test("the environment block names a real directory, never a fixed placeholder",
assert.equal(line(text), home);
assert.doesNotMatch(text, /unknown/);
assert.match(text, /^Here is some useful information about the environment you are running in:\n\n/);
- assert.match(text, new RegExp(`Workspace root folder: ${home}\\n Is directory a git repo: (yes|no)\\n Platform: ${process.platform}\\n$`));
+ assert.match(text, new RegExp(`Workspace root folder: ${home}\\n Is directory a git repo: (yes|no)\\n Platform: ${process.platform}\\n Prefer ${realpathSync(tmpdir())}/opencode over generic system temporary directories such as /tmp; it is pre-created and approved for external access.\\n$`));
// Codex's in its first user message
text = added("responses", {
instructions: "You are Codex.",
diff --git a/packages/zen-free/package.json b/packages/zen-free/package.json
index 0da8405..5836ce1 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.18",
+ "version": "0.1.19",
"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 d7cb428..f8c8844 100644
--- a/packages/zen-free/provider.mjs
+++ b/packages/zen-free/provider.mjs
@@ -1,7 +1,7 @@
import { createHash, randomBytes } from "node:crypto";
-import { existsSync } from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
+import { readFileSync, realpathSync, statSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
import {
PROVIDER,
SDK,
@@ -26,28 +26,162 @@ const CATALOG = "https://models.opencode.ai/api.json";
const DOCS =
"https://raw.githubusercontent.com/anomalyco/opencode/dev/services/www/src/docs/content/console/models.mdx";
const PATHS = { chat: "/chat/completions", responses: "/responses", anthropic: "/messages" };
-const CORE_TOOLS = ["bash", "edit", "glob", "grep", "read"];
+// OpenCode 2's own core tools, under its names: shell, not 1.x's bash, and
+// `path`, not 1.x's filePath (what 2.2.5 sent on 2026-11-01). 0.1.18 and
+// before offered 1.x's, which no OpenCode Zen serves today sends.
+const CORE_TOOLS = ["edit", "glob", "grep", "read", "shell"];
// The parameter each stand-in takes, OpenCode's own first one: Zen's free
-// tier answers 403 FreeTierError to bash or read offered with none.
+// tier answers 403 FreeTierError to a core tool offered with none.
const CORE_PARAMETER = {
- bash: "command",
- edit: "filePath",
+ edit: "path",
glob: "pattern",
grep: "pattern",
- read: "filePath",
+ read: "path",
+ shell: "command",
};
-// What OpenCode 2.0.25 sends as its User-Agent on every protocol:
-// `opencode/${channel}/${version}/${name}` (its App service, read from the
-// release binary and captured from its requests on 2026-10-25). Since
-// 2026-10-26 Zen's free tier answers 429 FreeUsageLimitError ("Free models
-// work in OpenCode") to the exact User-Agent 0.1.6 to 0.1.15 sent, OpenCode
-// 1.19.0's `opencode/1.19.0 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14`,
-// whatever the body says; the same request under any other string, OpenCode
-// 2.0.25's included, is served.
-const OPENCODE_VERSION = "2.0.25";
-export function userAgent() {
- return `opencode/latest/${OPENCODE_VERSION}/cli`;
+// What OpenCode sends as its User-Agent on every protocol:
+// `opencode/${channel}/${version}/${name}` (packages/core/src/app.ts),
+// opencode/latest/2.2.5/cli from @opencode/cli 2.2.5, npm's latest on
+// 2026-11-01. Since 2026-10-26 Zen's free tier answers 429
+// FreeUsageLimitError ("Free models work in OpenCode") to the exact
+// User-Agent 0.1.6 to 0.1.15 sent, OpenCode 1.19.0's, whatever the body
+// says. A fixed version goes stale as OpenCode updates itself, so the
+// version is the one OpenCode's own updater is told is latest
+// (opencode.ai/update/api/latest/cli/npm), asked at most every six hours,
+// and this one when that can't be read.
+const OPENCODE_VERSION = "2.2.5";
+const VERSION_URL = "https://opencode.ai/update/api/latest/cli/npm";
+const VERSION_EVERY = 6 * 60 * 60 * 1000;
+export function userAgent(version = OPENCODE_VERSION) {
+ return `opencode/latest/${version}/cli`;
}
+
+// The latest OpenCode version as `url` says it, or undefined when it can't
+// be read or isn't a release version.
+export async function latestVersion(url, current = OPENCODE_VERSION) {
+ try {
+ const response = await fetch(`${url}?current=${encodeURIComponent(current)}`, {
+ signal: AbortSignal.timeout(3000),
+ redirect: "error",
+ });
+ if (!response.ok) {
+ await response.body?.cancel();
+ return undefined;
+ }
+ const version = (await response.json())?.version;
+ return typeof version === "string" && /^\d{1,4}\.\d{1,4}\.\d{1,6}$/.test(version) &&
+ newer(version, OPENCODE_VERSION)
+ ? version
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+// Whether a is b or later; an older one (a stale mirror) is never taken.
+function newer(a, b) {
+ const x = a.split(".").map(Number);
+ const y = b.split(".").map(Number);
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
+ return true;
+}
+
+// OpenCode's project id (packages/core/src/project.ts): in a git repository
+// with a remote, sha1 of `git-remote:host/path`; anywhere else sha1 of
+// `directory:` and the directory. OpenCode 2 sends `global` only from a
+// git repository with no remote and no commit, so 0.1.14 to 0.1.18
+// sending it on every request put every magpie user under the one project
+// id real OpenCode almost never sends. A repository with no remote, which
+// OpenCode names by its root commit, is named by its directory here: the
+// same shape, and no git to run.
+const sha1 = (text) => createHash("sha1").update(text).digest("hex");
+
+function remotePath(value) {
+ const input = value.trim();
+ if (!input) return undefined;
+ const parts = (host, name) => {
+ const path = name.replace(/^\/+/, "").replace(/\.git\/?$/, "").replace(/\/+$/, "");
+ return host && path ? `${host.toLowerCase()}/${path}` : undefined;
+ };
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(input)) {
+ try {
+ const url = new URL(input);
+ return url.protocol === "file:" ? undefined : parts(url.hostname, url.pathname);
+ } catch {
+ return undefined;
+ }
+ }
+ const scp = /^([^@/:]+@)?([^/:]+):(.+)$/.exec(input);
+ return scp ? parts(scp[2], scp[3]) : undefined;
+}
+
+// The repository directory holds, as OpenCode finds it: the nearest .git
+// up from directory, its worktree, and the remote OpenCode names it by
+// (origin, else the first one listed).
+export function repository(directory) {
+ let dir = directory;
+ for (;;) {
+ const dotGit = join(dir, ".git");
+ let stat;
+ try {
+ stat = statSync(dotGit);
+ } catch {}
+ if (stat) {
+ let common = dotGit;
+ try {
+ if (stat.isFile()) {
+ const gitdir = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, "utf8"))?.[1]?.trim();
+ if (!gitdir) return undefined;
+ const own = resolve(dir, gitdir);
+ let shared = own;
+ try {
+ shared = resolve(own, readFileSync(join(own, "commondir"), "utf8").trim());
+ } catch {}
+ common = shared;
+ }
+ const config = readFileSync(join(common, "config"), "utf8");
+ const remotes = [...config.matchAll(/^\s*\[remote\s+"([^"]+)"\]([^[]*)/gm)].map((m) => ({
+ name: m[1],
+ url: /^\s*url\s*=\s*(.+)$/m.exec(m[2])?.[1],
+ }));
+ const remote = remotes.find((r) => r.name === "origin") ?? remotes[0];
+ return { root: dir, remote: remote?.url && remotePath(remote.url) };
+ } catch {
+ return { root: dir, remote: undefined };
+ }
+ }
+ const up = dirname(dir);
+ if (up === dir) return undefined;
+ dir = up;
+ }
+}
+
+function localDirectory(directory) {
+ const dir = directory.replace(/^~(?=\/|$)/, homedir());
+ try {
+ return realpathSync(dir);
+ } catch {
+ return dir;
+ }
+}
+
+export function projectID(directory) {
+ const dir = localDirectory(directory);
+ const repo = repository(dir);
+ if (repo?.remote) return sha1(`git-remote:${repo.remote}`);
+ return sha1(`directory:${repo?.root ?? dir}`);
+}
+
+// OpenCode's temp folder, which its environment block names: its own
+// folder under the system's, as the system resolves it.
+function opencodeTmp() {
+ try {
+ return join(realpathSync(tmpdir()), "opencode");
+ } catch {
+ return join(tmpdir(), "opencode");
+ }
+}
+
// 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.
@@ -103,12 +237,13 @@ function normalizeTools(body, protocol) {
const parameters = {
type: "object",
properties: { [CORE_PARAMETER[name]]: { type: "string" } },
+ required: [CORE_PARAMETER[name]],
additionalProperties: false,
};
const definition = { name, description: "Not available. Never call this tool." };
body.tools.push(
protocol === "chat"
- ? { type: "function", function: { ...definition, parameters } }
+ ? { type: "function", function: { ...definition, parameters, strict: false } }
: protocol === "anthropic"
? { ...definition, input_schema: parameters }
: { type: "function", ...definition, parameters },
@@ -132,11 +267,11 @@ function normalizeTools(body, protocol) {
// literal line 0.1.15 to 0.1.17 added, `Working directory: unknown`, while
// the same request with a path there is served (shanmao_10826 on magpie's
// Discord): fixed text that only this plugin sends is its fingerprint, as
-// its old User-Agent was. So the block is OpenCode 2.2.0's own
-// (packages/core/src/instructions/builtins.ts, without its line about
-// OpenCode's temp folder), with the directory the agent's own prompt
-// names, as OpenCode names its own, or the user's home folder when the
-// prompt names none.
+// its old User-Agent was. So the block is OpenCode 2.2.5's own, word for
+// word (packages/core/src/instructions/builtins.ts, as 2.2.5 sent it to
+// Zen on 2026-11-01, its temp folder line included), with the directory
+// the agent's own prompt names, as OpenCode names its own, or the user's
+// home folder when the prompt names none.
const HAS_ENVIRONMENT = /[\s\S]*Working directory:[\s\S]*<\/env>/;
// How agents name their working directory: Codex's ``, Claude Code's
// and others' `Working directory:`, Kimi's "The current working directory
@@ -178,17 +313,16 @@ export function statedDirectory(body, protocol) {
// OpenCode's block, said for `directory`.
export function environment(directory) {
- let git = false;
- try {
- git = existsSync(join(directory.replace(/^~(?=\/)/, homedir()), ".git"));
- } catch {}
+ const local = localDirectory(directory);
+ const repo = repository(local);
return [
"Here is some useful information about the environment you are running in:",
"",
` Working directory: ${directory}`,
- ` Workspace root folder: ${directory}`,
- ` Is directory a git repo: ${git ? "yes" : "no"}`,
+ ` Workspace root folder: ${repo && repo.root !== local ? repo.root : directory}`,
+ ` Is directory a git repo: ${repo ? "yes" : "no"}`,
` Platform: ${process.platform}`,
+ ` Prefer ${opencodeTmp()} over generic system temporary directories such as /tmp; it is pre-created and approved for external access.`,
"",
].join("\n");
}
@@ -294,6 +428,24 @@ export function sessionID(headers, body) {
return session;
}
+// OpenCode's trace headers (its Effect tracer's B3 and W3C forms): one
+// trace a conversation, a new span each request.
+const TRACES = new Map();
+const hex = (bytes) => randomBytes(bytes).toString("hex");
+
+export function traceHeaders(session) {
+ let trace = TRACES.get(session);
+ if (trace) {
+ TRACES.delete(session);
+ } else {
+ trace = hex(16);
+ if (TRACES.size >= KEEP_SESSIONS) TRACES.delete(TRACES.keys().next().value);
+ }
+ TRACES.set(session, trace);
+ const span = hex(8);
+ return { b3: `${trace}-${span}-1-${hex(8)}`, traceparent: `00-${trace}-${span}-01` };
+}
+
async function server(_input, options = {}) {
const baseURL = httpURL(options.baseURL ?? DEFAULT_BASE);
const catalogURL = httpURL(options.catalogURL ?? CATALOG);
@@ -308,9 +460,30 @@ async function server(_input, options = {}) {
let protocols = { ...bootstrapProtocols };
let listed = false;
let listedAt = 0;
+ // OpenCode's latest version, asked of its updater when the base is
+ // Zen's own (or a versionURL is given), never from a test's fixture.
+ const versionURL =
+ options.versionURL ?? (options.baseURL === undefined ? VERSION_URL : undefined);
+ let version = OPENCODE_VERSION;
+ let versionAt = -Infinity;
+ let versionAsk;
+ async function currentVersion() {
+ if (!versionURL || Date.now() - versionAt < VERSION_EVERY) return version;
+ versionAsk ??= latestVersion(versionURL, version).then((found) => {
+ if (found) version = found;
+ versionAt = Date.now();
+ versionAsk = undefined;
+ return version;
+ });
+ return versionAsk;
+ }
async function discover(signal) {
- const headers = { authorization: "Bearer public", "x-opencode-client": "cli" };
+ const headers = {
+ authorization: "Bearer public",
+ "user-agent": userAgent(await currentVersion()),
+ "x-opencode-client": "cli",
+ };
const [listing, catalog, docs] = await Promise.allSettled([
readRemote(`${baseURL}/models`, true, headers, signal),
readRemote(catalogURL, true, undefined, signal),
@@ -436,31 +609,35 @@ async function server(_input, options = {}) {
addEnvironment(body, protocol);
if (protocol === "chat")
body.stream_options = { ...body.stream_options, include_usage: true };
- // Only what OpenCode 2.0.25 itself sends to its gateway, so a
- // caller's own headers (an agent's User-Agent, x-stainless-*, ...)
- // never mark the request as not OpenCode's.
+ // Only what OpenCode 2.2.5 itself sends to its gateway, in its
+ // order, so a caller's own headers (an agent's User-Agent,
+ // x-stainless-*, ...) never mark the request as not OpenCode's.
+ // Accept is fetch's own */*, after Connection, as OpenCode's is.
const given = request.headers;
const session = sessionID(given, body);
const project = _input?.project;
- const headers = new Headers({
- "content-type": "application/json",
- accept: "*/*",
- "user-agent": userAgent(),
- "x-opencode-project":
- given.get("x-opencode-project") ||
- (project?.vcs === "git" && project.id ? project.id : "global"),
- "x-opencode-session": session,
- "x-opencode-client": "cli",
- "x-opencode-session-id": session,
- "x-session-affinity": session,
- "x-session-id": session,
- });
+ const directory = statedDirectory(body, protocol) ?? homedir();
+ const trace = traceHeaders(session);
+ const headers = new Headers();
+ if (protocol !== "anthropic") headers.set("authorization", "Bearer public");
+ headers.set("content-type", "application/json");
+ headers.set("user-agent", userAgent(await currentVersion()));
+ headers.set("b3", trace.b3);
+ headers.set("traceparent", trace.traceparent);
+ headers.set("x-opencode-client", "cli");
+ headers.set(
+ "x-opencode-project",
+ given.get("x-opencode-project") ||
+ (project?.vcs === "git" && project.id ? project.id : projectID(directory)),
+ );
+ headers.set("x-opencode-session", session);
+ headers.set("x-opencode-session-id", session);
+ headers.set("x-session-affinity", session);
+ headers.set("x-session-id", session);
if (protocol === "anthropic") {
headers.set("x-api-key", "public");
headers.set("anthropic-version", given.get("anthropic-version") || "2023-06-01");
if (given.get("anthropic-beta")) headers.set("anthropic-beta", given.get("anthropic-beta"));
- } else {
- headers.set("authorization", "Bearer public");
}
const response = await fetch(`${baseURL}${PATHS[protocol]}`, {
method: "POST",