Skip to content

Commit 1c3421b

Browse files
release(v0.9.64): the versioned gate — Zen's free tier answers again ⚿
Zen stopped trusting the bearer and began fingerprinting the caller on 2026-09-17. Every free model answered `403 FreeTierError: OpenCode's free tier can only be used from within OpenCode`, so the account ladder burned a failover on every turn and `modelLock_big-pickle` clamped each account for 120s. Both lanes are gated alike — the keyless `public` one and a keyed connection. The gate names two shapes, and the harbor failed both: ⚿ A versioned identity. Upstream now requires `User-Agent: opencode/<version>` with the floor at 1.17.0: a bare `opencode` (what we sent) or any third-party UA draws the 403, and anything below the floor draws `426 Upgrade Required`. The executor now sends `opencode/1.18.31`, and passes a downstream opencode identity through only when the gate would accept it — a genuine `opencode/1.18.31 ai-sdk/…` client keeps its own UA, everyone else is dressed correctly. 🧵 A canonical session. `x-opencode-session` must wear `/^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/` — ses_ + 12 hex + 14 Base62, thirty characters — with `msg_` as its request twin. We minted `ses_` + a bare 32-char UUID, a shape the gate had never seen. Both ids are generated canonical now. 🔗 Translation, not regeneration. A client session (`claude:…`, `antigravity:…`, a bare conversation id) is hashed deterministically — SHA-256 salted with the downstream tool family — into canonical form, so one conversation keeps one upstream session and prompt caching and affinity survive the crossing. An already-canonical header passes through trimmed; an invalid one is translated rather than forwarded. 🛡️ The race is gone. The session used to ride `this._currentSessionId` instance state, resolved in `transformRequest` and read back in `buildHeaders`, so two concurrent turns on one executor could overwrite each other's session. It now travels request-locally on that call's credentials (`prepareRequestCredentials` + an `execute` override), and the caller's credential object is never mutated. ⚓ What sailed: open-sse/executors/opencode.js, tests/unit/opencode-zen.test.js, tests/unit/opencode-session.test.js, package.json, docker-compose.example.yml 🧪 Proof: 2 files, 27 tests, all green — tests/unit/opencode-zen.test.js (re-pinned: it had pinned the very UUID and bare-UA shapes that draw the 403) plus the new tests/unit/opencode-session.test.js. Coverage: canonical generation, deterministic translation and its isolation per conversation and per tool, native-header passthrough, the version floor in all four directions, and the exact headers that leave the wire on both lanes. ⚠️ Honest limit: no live upstream probe was run — the Lighthouse tower's transports cannot POST with custom headers, and a browser probe cannot set User-Agent at all. The fix is proven by construction against the gate's documented contract and by the wire-boundary assertions, not by a 200 from Zen. The gate's shape was read from decolua/9router#4101 (root cause and shipped fix), FishBottle7/opencode2dsh#9, and anomalyco/opencode#49621. Co-Authored-By: Shiori Shorekeeper <[email protected]>
1 parent 70e12bb commit 1c3421b

7 files changed

Lines changed: 392 additions & 25 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,62 @@ edge (`0.9.x → 1.0`). Versions carry two digits in the last place —
2525
2626
---
2727

28+
# v0.9.64 — The Versioned Gate ⚿
29+
> *"Zen stopped trusting the token and began asking who was knocking — a bare name drew the door shut; a versioned name, and the canonical shape of a session, opened it again."* ⚿💜
30+
31+
On 2026-09-17 Zen's free lane began **fingerprinting the caller** instead of
32+
trusting the bearer — and both lanes are gated alike, the keyless `public` one
33+
and a keyed connection. Every free model answered
34+
`403 FreeTierError: OpenCode's free tier can only be used from within OpenCode`,
35+
so the account ladder burned a failover on every turn and `modelLock_big-pickle`
36+
clamped each account for 120s. The gate names two shapes, and the harbor failed
37+
both:
38+
39+
- ⚿ **A versioned identity** (`open-sse/executors/opencode.js`): upstream now
40+
requires `User-Agent: opencode/<version>` with the floor at **1.17.0** — a bare
41+
`opencode`, or any third-party UA, draws the 403, and anything below the floor
42+
draws `426 Upgrade Required`. The executor sent a bare `opencode`. It now sends
43+
`opencode/1.18.31`, and passes a downstream opencode identity through **only
44+
when the gate would accept it** — so a genuine `opencode/1.18.31 ai-sdk/…`
45+
client keeps its own UA while every other caller is dressed correctly.
46+
- 🧵 **A canonical session** (same file): `x-opencode-session` must wear
47+
`/^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/` — `ses_` + 12 hex + 14 Base62, thirty
48+
characters — with `msg_` as its request twin. The executor minted `ses_` + a
49+
bare 32-char UUID, a shape the gate had never seen. Both ids are now generated
50+
canonical.
51+
- 🔗 **Translation, not regeneration**: a client session (`claude:…`,
52+
`antigravity:…`, a bare conversation id) is hashed **deterministically**
53+
(SHA-256 salted with the downstream tool family) into canonical form, so one
54+
conversation keeps one upstream session and prompt caching and affinity survive
55+
the crossing. A header that is already canonical passes through untouched,
56+
trimmed; an invalid one is translated rather than forwarded.
57+
- 🛡️ **The race is gone**: the session used to ride `this._currentSessionId`
58+
instance state — resolved in `transformRequest`, read back in `buildHeaders` —
59+
so two concurrent turns on one executor could overwrite each other's session.
60+
It now travels request-locally on that call's credentials
61+
(`prepareRequestCredentials` + an `execute` override), and the caller's
62+
credential object is never mutated.
63+
64+
**Proven**: `tests/unit/opencode-zen.test.js` (re-pinned to the gate's real
65+
contract — it had pinned the very UUID and bare-UA shapes that draw the 403) plus
66+
the new `tests/unit/opencode-session.test.js` — **2 files, 27 tests, all green**
67+
— covering canonical generation, deterministic translation and its isolation per
68+
conversation and per tool, native-header passthrough, the version floor in all
69+
four directions, and the exact headers that leave the wire on both lanes.
70+
71+
⚠️ **Honest limit**: no live upstream probe was run — the Lighthouse tower's
72+
transports cannot POST with custom headers, and a browser probe cannot set
73+
`User-Agent` at all. This fix is proven by construction against the gate's
74+
documented contract and by the wire-boundary assertions, not by a 200 from Zen.
75+
The gate's shape was read from decolua/9router#4101 (root cause + shipped fix),
76+
FishBottle7/opencode2dsh#9, and anomalyco/opencode#49621.
77+
78+
⚓ **What sailed**: `open-sse/executors/opencode.js`,
79+
`tests/unit/opencode-zen.test.js`, `tests/unit/opencode-session.test.js`,
80+
`package.json`, `docker-compose.example.yml`
81+
82+
---
83+
2884
# v0.9.63 — The Sanitized Stream 🧵
2985
> *"Six stones against the request path: a name that leaked its disguise, a transport that was overridden by a stale target, ids that collided by the millisecond, a schema the endpoint could not parse, a budget smuggled past by a bare object, a built-in whitelist the deep-endpoint demanded."* 🧵💜
3086
The Great Fold's second minor (ADR-004) — every request-input path from the

‎docker-compose.example.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ services:
6363
# breaker, fallback-rules DB, per-key ACL, pool egress geo, prompt
6464
# injectors. v0.9.12+ carries the redesigned sidebar, single-page
6565
# usage, /quota.
66-
image: ghcr.io/yumamax3/vela:0.9.63 # bump to the release you want
66+
image: ghcr.io/yumamax3/vela:0.9.64 # bump to the release you want
6767
container_name: vela-gateway
6868
hostname: vela-gateway
6969
restart: unless-stopped

‎open-sse/executors/opencode.js‎

Lines changed: 120 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,43 +4,143 @@ import { PROVIDERS } from "../config/providers.js";
44
import { injectReasoningContent } from "../utils/reasoningContentInjector.js";
55
import { resolveSessionId } from "../utils/sessionManager.js";
66

7-
const OPENCODE_UA = "opencode";
7+
// ── The 2026-09-17 free-tier gate ──────────────────────────────────────────
8+
// Zen fingerprints the caller before it serves a token, and both lanes are
9+
// gated (the keyless "public" one and a keyed connection alike):
10+
// • User-Agent must be `opencode/<version>` with version >= 1.17.0 — a bare
11+
// "opencode" or a third-party UA draws 403 FreeTierError, and anything
12+
// below 1.17.0 draws 426 Upgrade Required.
13+
// • `x-opencode-session` must wear OpenCode's canonical identifier shape —
14+
// `ses_` + 12 hex + 14 Base62 (30 chars), with `msg_` as its request twin.
15+
// A UUID-shaped id is refused outright.
16+
// So the wire identity is built here rather than inherited from the caller.
17+
const OPENCODE_UA = "opencode/1.18.31";
818
const MESSAGES_MODELS = new Set();
919

10-
function generateRequestId() {
11-
return `msg_${crypto.randomUUID().replace(/-/g, "")}`;
20+
export const OPENCODE_SESSION_RE = /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
21+
export const OPENCODE_REQUEST_RE = /^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
22+
const BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
23+
const MAX_SESSION_LENGTH = 256;
24+
const SESSION_HEADER = "x-opencode-session";
25+
const SESSION_FIELD = "_opencodeSession";
26+
27+
// Pass a downstream opencode version through only when the gate would accept it.
28+
function hasValidOpencodeVersion(ua) {
29+
const m = String(ua || "").match(/opencode\/(\d+)\.(\d+)(?:\.(\d+))?/i);
30+
if (!m) return false;
31+
const major = Number(m[1]);
32+
const minor = Number(m[2]);
33+
return major > 1 || (major === 1 && minor >= 17);
34+
}
35+
36+
// 12 hex chars of a big-endian 48-bit value — the time half of a canonical id.
37+
function timeHex(value) {
38+
let out = "";
39+
for (let i = 0; i < 6; i++) {
40+
out += Number((value >> BigInt(40 - 8 * i)) & 0xffn)
41+
.toString(16)
42+
.padStart(2, "0");
43+
}
44+
return out;
45+
}
46+
47+
function base62(bytes) {
48+
let out = "";
49+
for (const byte of bytes) out += BASE62_CHARS[byte % 62];
50+
return out;
51+
}
52+
53+
let lastTimestamp = 0;
54+
let counter = 0;
55+
56+
export function generateSessionId(timestamp = Date.now()) {
57+
if (timestamp !== lastTimestamp) {
58+
lastTimestamp = timestamp;
59+
counter = 0;
60+
}
61+
counter++;
62+
const current = BigInt(timestamp) * 0x1000n + BigInt(counter);
63+
return `ses_${timeHex(~current)}${base62(crypto.randomBytes(14))}`;
1264
}
1365

14-
function generateSessionId() {
15-
return `ses_${crypto.randomUUID().replace(/-/g, "")}`;
66+
export function generateRequestId(timestamp = Date.now()) {
67+
const current = BigInt(timestamp) * 0x1000n + 1n;
68+
return `msg_${timeHex(current)}${base62(crypto.randomBytes(14))}`;
1669
}
1770

18-
// Normalize any resolved id into opencode's ses_ format (stable per-conversation)
19-
function toOpencodeSession(id) {
20-
const stripped = String(id || "").replace(/^ses_/, "").replace(/-/g, "");
21-
return stripped ? `ses_${stripped}` : null;
71+
// Deterministic by design: the same conversation always lands on the same
72+
// canonical id, so upstream prompt caching and session affinity survive the
73+
// translation instead of being reset on every turn.
74+
export function translateSessionId(sessionId, clientTool = "") {
75+
if (typeof sessionId === "string" && OPENCODE_SESSION_RE.test(sessionId.trim())) {
76+
return sessionId.trim();
77+
}
78+
const digest = crypto
79+
.createHash("sha256")
80+
.update(`opencode\0${clientTool || "generic"}\0${sessionId || ""}`)
81+
.digest();
82+
return `ses_${digest.subarray(0, 6).toString("hex")}${base62(digest.subarray(6, 20))}`;
2283
}
2384

24-
function resolveOpencodeSession(body, credentials) {
25-
return toOpencodeSession(resolveSessionId({
26-
headers: credentials?.rawHeaders,
85+
function normalizeSession(value) {
86+
if (typeof value !== "string") return null;
87+
const normalized = value.trim();
88+
if (!normalized || normalized.length > MAX_SESSION_LENGTH) return null;
89+
return normalized;
90+
}
91+
92+
// Raw client headers arrive lowercase-mapped; accept either case regardless.
93+
function sessionHeader(headers) {
94+
if (!headers || typeof headers !== "object") return null;
95+
for (const [key, value] of Object.entries(headers)) {
96+
if (key.toLowerCase() === SESSION_HEADER) return normalizeSession(value);
97+
}
98+
return null;
99+
}
100+
101+
// Salt for the translation — the downstream tool family, stable per client.
102+
function clientToolOf(headers) {
103+
const ua = String(headers?.["user-agent"] ?? headers?.["User-Agent"] ?? "");
104+
return ua.split(/[/\s]/)[0].toLowerCase() || "generic";
105+
}
106+
107+
function resolveOpencodeSession(body, credentials, headers) {
108+
const native = sessionHeader(headers);
109+
if (native && OPENCODE_SESSION_RE.test(native)) return native;
110+
111+
const resolved = native || resolveSessionId({
112+
headers,
27113
body,
28114
connectionId: credentials?.connectionId,
29115
scope: "opencode",
30-
}));
116+
});
117+
118+
return resolved ? translateSessionId(resolved, clientToolOf(headers)) : generateSessionId();
31119
}
32120

33121
export class OpenCodeExecutor extends BaseExecutor {
34122
constructor() {
35123
super("opencode", PROVIDERS.opencode);
36-
this._currentSessionId = null;
124+
}
125+
126+
// Request-local: the session rides this call's credentials, never instance
127+
// state — two concurrent turns can no longer overwrite each other's session.
128+
prepareRequestCredentials({ body, credentials } = {}) {
129+
const source = credentials || {};
130+
return {
131+
...source,
132+
[SESSION_FIELD]: resolveOpencodeSession(body, source, source.rawHeaders || {}),
133+
};
37134
}
38135

39136
transformRequest(model, body, stream, credentials) {
40-
this._currentSessionId = resolveOpencodeSession(body, credentials);
41137
return injectReasoningContent({ provider: this.provider, model, body });
42138
}
43139

140+
async execute(args) {
141+
return super.execute({ ...args, credentials: this.prepareRequestCredentials(args) });
142+
}
143+
44144
buildUrl(model) {
45145
const base = this.config.baseUrl;
46146
return MESSAGES_MODELS.has(model)
@@ -54,7 +154,7 @@ export class OpenCodeExecutor extends BaseExecutor {
54154
for (const [k, v] of Object.entries(raw)) lower[k.toLowerCase()] = v;
55155

56156
const downstreamUa = lower["user-agent"] || "";
57-
const isOpencodeDownstream = downstreamUa.toLowerCase().includes("opencode");
157+
const isOpencodeDownstream = hasValidOpencodeVersion(downstreamUa);
58158

59159
// Hybrid lane: a connection holding an OpenCode API key (apikey connection)
60160
// rides authenticated Zen — lifted limits, paid models. The virtual
@@ -63,12 +163,15 @@ export class OpenCodeExecutor extends BaseExecutor {
63163
const key = credentials?.apiKey || credentials?.accessToken;
64164
const hasKey = typeof key === "string" && key && key !== "public";
65165

166+
const session = credentials?.[SESSION_FIELD]
167+
|| this.prepareRequestCredentials({ credentials })[SESSION_FIELD];
168+
66169
return {
67170
"Content-Type": "application/json",
68171
"Authorization": hasKey ? `Bearer ${key}` : "Bearer public",
69172
"User-Agent": isOpencodeDownstream ? downstreamUa : OPENCODE_UA,
70173
"x-opencode-client": lower["x-opencode-client"] || "desktop",
71-
"x-opencode-session": lower["x-opencode-session"] || this._currentSessionId || generateSessionId(),
174+
"x-opencode-session": session,
72175
"x-opencode-request": lower["x-opencode-request"] || generateRequestId(),
73176
"x-opencode-project": lower["x-opencode-project"] || "global",
74177
"Accept": stream ? "text/event-stream" : "*/*",

‎package-lock.json‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "vela-app",
3-
"version": "0.9.63",
3+
"version": "0.9.64",
44
"description": "Vela — the AI gateway: one OpenAI-compatible endpoint routing 40+ providers, with full key governance",
55
"homepage": "https://github.com/YumamaX3/Vela#readme",
66
"repository": {

0 commit comments

Comments
 (0)