Skip to content

Commit 4890c1c

Browse files
committed
fix(providers): identify opencode-free with the client User-Agent it claims
opencode-free sent no User-Agent, so Zen saw the bare runtime default (Bun/x.y.z) and rate-limited it harder than a client that identifies itself. Adds "User-Agent: opencode" alongside the existing x-opencode-client: desktop marker. The value is deliberately unversioned. OmniRoute, an independent open-source broker against the same Zen upstream, defaults to exactly this pair and reached it by retreating from its own earlier opencode-cli/1.0.0 pin: a pinned version is a claim about an install we do not have, and it goes stale on the vendor's schedule. The registry edit alone would have shipped to nobody. staticHeaders is documented as merged into every upstream request, but it was only ever copied at seed time, so any config written before a header existed -- or carrying any header of its own -- never received it. routedProviderConfig and buildModelsRequest now fill registry static headers beneath user headers, matched case-insensitively so an override replaces rather than duplicates: spreading "User-Agent" over a user's "user-agent" leaves both keys, which Headers serializes as one comma-joined value. Model discovery gets the same treatment because a provider identified as opencode when it completes but anonymous when it lists its own models reads as two different clients to a rate limiter.
1 parent 5c07426 commit 4890c1c

5 files changed

Lines changed: 134 additions & 6 deletions

File tree

‎src/oauth/index.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { loginCommandCode, refreshCommandCodeToken } from "./command-code";
1717
import { ANTIGRAVITY_REQUEST_UA } from "../adapters/google-antigravity-wire";
1818
import { deriveOAuthDefaultModel, deriveOAuthProviderConfig } from "../providers/derive";
1919
import { apiKeyPoolEntryId, sanitizeApiKeyValue } from "../providers/api-keys";
20-
import { effectiveGoogleMode, getProviderRegistryEntry, providerMatchesRegistryTransport } from "../providers/registry";
20+
import { effectiveGoogleMode, getProviderRegistryEntry, mergeRegistryStaticHeaders, providerMatchesRegistryTransport } from "../providers/registry";
2121
import { resolveProviderModelDiscoveryUrl } from "../providers/model-discovery";
2222
import { resolveProviderTransport } from "../providers/xai-transport";
2323
import { detectClaudeCodeToken, detectGrokCliToken, hasComparableGrokIdentity, isSameGrokIdentity, shouldAdoptGrokGeneration } from "./local-token-detect";
@@ -828,7 +828,16 @@ export function buildModelsRequest(
828828
undefined,
829829
copilotApiBaseUrl,
830830
);
831-
const headers: Record<string, string> = { ...(effectiveProvider.headers ?? {}) };
831+
// Model discovery is an upstream request like any other, so it carries the same registry
832+
// static headers the inference path does. Without this a provider is identified correctly
833+
// when it answers a completion but anonymously when it lists its own models, which is the
834+
// kind of split fingerprint an upstream rate limiter reads as two different clients.
835+
const registryStaticHeaders = providerMatchesRegistryTransport(providerName, effectiveProvider)
836+
? getProviderRegistryEntry(providerName)?.staticHeaders
837+
: undefined;
838+
const headers: Record<string, string> = {
839+
...(mergeRegistryStaticHeaders(registryStaticHeaders, effectiveProvider.headers) ?? {}),
840+
};
832841
const discoveryUrl = (defaultUrl: string): string => resolveProviderModelDiscoveryUrl(
833842
providerName,
834843
prov,

‎src/providers/registry.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2435,6 +2435,16 @@ export const PROVIDER_REGISTRY: readonly ProviderRegistryEntry[] = [
24352435
note: "No key needed — public desktop tier. OpenCode currently advertises about 200 Big Pickle/free-model requests per 5 hours. The same Zen gateway can also short-window rate-limit free models at roughly 15-20 requests/minute, and may return generic 429s without Retry-After (opencodex synthesizes backoff only when that header is omitted). Free models are discovered live from Zen. Data use: per OpenCode's Zen docs (https://opencode.ai/docs/zen/), prompts sent to free models may be retained and used for training/improvement — do not send confidential material through this provider.",
24362436
dashboardUrl: "https://opencode.ai",
24372437
staticHeaders: {
2438+
// Zen answers a bare runtime User-Agent (Bun/x.y.z) more aggressively than a client
2439+
// that identifies itself, which is what the 429 in #2067 traced to. The value is
2440+
// deliberately unversioned: a pinned "opencode-cli/<version>" is a claim about an
2441+
// install we do not have and goes stale on the vendor's schedule, not ours.
2442+
// Corroboration, not authority: OmniRoute — an independent open-source broker against
2443+
// the same Zen upstream — defaults to exactly this pair (userAgent "opencode", client
2444+
// "desktop") in open-sse/executors/opencode.ts, and got there by RETREATING from its
2445+
// own earlier "opencode-cli/1.0.0" pin. An operator can still override either value
2446+
// through the provider headers API; user headers win case-insensitively at route time.
2447+
"User-Agent": "opencode",
24382448
"x-opencode-client": "desktop",
24392449
},
24402450
modelReasoningEfforts: Object.fromEntries(OPENCODE_FREE_DEEPSEEK_MODELS.map(id => [id, deepseekThinkingEffortsFor(id)])),
@@ -2591,6 +2601,36 @@ export function getProviderRegistryEntry(id: string): ProviderRegistryEntry | un
25912601
return PROVIDER_REGISTRY.find(entry => entry.id === id);
25922602
}
25932603

2604+
/**
2605+
* Merge a registry row's `staticHeaders` beneath a provider's own headers.
2606+
*
2607+
* The field is documented as "merged into every upstream request for this provider", but that
2608+
* was only ever true for a freshly seeded config: `providerConfigSeed` copies the block once
2609+
* (`derive.ts`), `enrichProviderFromCatalog` fills it only when the whole block is absent, and
2610+
* nothing merged it at request time. So an install that predates a header — or that saved any
2611+
* header of its own — never received the new one, which is exactly what #2067 would have
2612+
* shipped for every existing opencode-free user.
2613+
*
2614+
* The comparison is case-insensitive on purpose. HTTP header names are case-insensitive, but a
2615+
* plain object spread is not: merging a registry `User-Agent` over a user's `user-agent`
2616+
* produces two entries that `Headers` serializes as one comma-joined value
2617+
* ("opencode, custom-agent"), which is a corrupted request rather than an override. The user's
2618+
* spelling and value both win; the registry only fills names the user has not spoken for.
2619+
*/
2620+
export function mergeRegistryStaticHeaders(
2621+
staticHeaders: Record<string, string> | undefined,
2622+
userHeaders: Record<string, string> | undefined,
2623+
): Record<string, string> | undefined {
2624+
if (!staticHeaders) return userHeaders;
2625+
if (!userHeaders) return { ...staticHeaders };
2626+
const claimed = new Set(Object.keys(userHeaders).map(name => name.toLowerCase()));
2627+
const merged: Record<string, string> = { ...userHeaders };
2628+
for (const [name, value] of Object.entries(staticHeaders)) {
2629+
if (!claimed.has(name.toLowerCase())) merged[name] = value;
2630+
}
2631+
return merged;
2632+
}
2633+
25942634
/** Whether this registry row's per-model service-tier evidence applies to one configured target. */
25952635
export function registryModelServiceTierCapabilityApplies(
25962636
entry: Pick<ProviderRegistryEntry, "modelServiceTierCapabilityBaseUrlGuard">,

‎src/router.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { assertProviderDestinationAllowed } from "./lib/destination-policy";
1414
import { redactSecretString, redactUrlForLog } from "./lib/redact";
1515
import {
1616
PROVIDER_REGISTRY,
17+
mergeRegistryStaticHeaders,
1718
providerCodexAccountMode,
1819
registryModelServiceTierCapabilityApplies,
1920
} from "./providers/registry";
@@ -296,6 +297,11 @@ export function routedProviderConfig(providerName: string, provider: OcxProvider
296297
? mergePositiveNumberCaps(registryEntry.modelContextWindows, provider.modelContextWindows)
297298
: mergeRecordFill(registryEntry.modelContextWindows, provider.modelContextWindows);
298299
const modelInputModalities = mergeRecordFill(registryEntry.modelInputModalities, provider.modelInputModalities);
300+
// Registry static headers are documented as applying to every upstream request, so they are
301+
// filled at resolve time rather than only at seed time: a config written before a header
302+
// existed, or one carrying any header of its own, would otherwise never receive it. User
303+
// headers win, matched case-insensitively so an override replaces rather than duplicates.
304+
const headers = mergeRegistryStaticHeaders(registryEntry.staticHeaders, provider.headers);
299305
const modelMaxInputTokens = providerName === OPENAI_API_PROVIDER_ID
300306
? mergePositiveNumberCaps(registryEntry.modelMaxInputTokens, provider.modelMaxInputTokens)
301307
: mergeRecordFill(registryEntry.modelMaxInputTokens, provider.modelMaxInputTokens);
@@ -372,6 +378,7 @@ export function routedProviderConfig(providerName: string, provider: OcxProvider
372378
authMode: canonicalAuthMode,
373379
apiKey: resolvedApiKey,
374380
...(staticModelCatalog ? { liveModels: false } : {}),
381+
...(headers ? { headers } : {}),
375382
// Backfill the Google wire mode + Vertex project/location from the registry when the user
376383
// config omits them, so a minimal `google-vertex`/`google-antigravity` entry still routes
377384
// through the correct branch (CCA/Vertex) instead of falling back to AI Studio.

‎tests/management-provider-validation.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2888,11 +2888,18 @@ describe("provider management validation", () => {
28882888
};
28892889

28902890
// Clearing user-managed headers must not delete the registry-owned static
2891-
// metadata (opencode-free's x-opencode-client marker) the transport relies on.
2891+
// metadata (opencode-free's User-Agent and x-opencode-client markers) the transport
2892+
// relies on.
28922893
expect((await patch("opencode-free", { headers: null }))?.status).toBe(200);
2893-
expect(liveConfig.providers["opencode-free"].headers).toEqual({ "x-opencode-client": "desktop" });
2894+
expect(liveConfig.providers["opencode-free"].headers).toEqual({
2895+
"User-Agent": "opencode",
2896+
"x-opencode-client": "desktop",
2897+
});
28942898
const saved = JSON.parse(readFileSync(join(TEST_DIR, "config.json"), "utf8")) as OcxConfig;
2895-
expect(saved.providers["opencode-free"]?.headers).toEqual({ "x-opencode-client": "desktop" });
2899+
expect(saved.providers["opencode-free"]?.headers).toEqual({
2900+
"User-Agent": "opencode",
2901+
"x-opencode-client": "desktop",
2902+
});
28962903
});
28972904
test("concurrent provider PATCHes merge different headers", async () => {
28982905
if (existsSync(TEST_DIR)) rmSync(TEST_DIR, { recursive: true });

‎tests/opencode-free-provider.test.ts‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { describe, expect, test } from "bun:test";
22
import { PROVIDER_REGISTRY } from "../src/providers/registry";
33
import { providerConfigSeed, deriveKeyLoginMap, deriveFeaturedProviderIds } from "../src/providers/derive";
44
import { createOpenAIChatAdapter } from "../src/adapters/openai-chat";
5+
import { routedProviderConfig } from "../src/router";
6+
import { buildModelsRequest } from "../src/oauth";
57
import type { OcxParsedRequest, OcxProviderConfig } from "../src/types";
68

79
function minimalRequest(model = "kimi-k2.7-code"): OcxParsedRequest {
@@ -27,14 +29,16 @@ describe("opencode-free provider", () => {
2729
expect(entry?.models).toBeUndefined();
2830
});
2931

30-
test("static headers include only the public client marker", () => {
32+
test("static headers include only the public client markers", () => {
3133
expect(entry?.staticHeaders?.["Authorization"]).toBeUndefined();
34+
expect(entry?.staticHeaders?.["User-Agent"]).toBe("opencode");
3235
expect(entry?.staticHeaders?.["x-opencode-client"]).toBe("desktop");
3336
});
3437

3538
test("providerConfigSeed propagates static headers", () => {
3639
const seed = providerConfigSeed(entry!);
3740
expect(seed.headers?.["Authorization"]).toBeUndefined();
41+
expect(seed.headers?.["User-Agent"]).toBe("opencode");
3842
expect(seed.headers?.["x-opencode-client"]).toBe("desktop");
3943
expect(seed.keyOptional).toBe(true);
4044
expect(seed.liveModels).toBe(true);
@@ -55,6 +59,7 @@ describe("opencode-free provider", () => {
5559
const req = adapter.buildRequest(minimalRequest());
5660
const headers = req.headers as Record<string, string>;
5761
expect(headers["Authorization"]).toBeUndefined();
62+
expect(headers["User-Agent"]).toBe("opencode");
5863
expect(headers["x-opencode-client"]).toBe("desktop");
5964
expect(req.url).toBe("https://opencode.ai/zen/v1/chat/completions");
6065
});
@@ -84,6 +89,66 @@ describe("opencode-free provider", () => {
8489
expect(Object.keys(headers)).toContain("Authorization");
8590
});
8691

92+
// A seeded config is the easy case. The one that actually reaches users is a config written
93+
// BEFORE a static header existed: it is on disk with the old header set (or with none at all,
94+
// because the management API strips a block that exactly matches the registry), and nothing
95+
// rewrites it. If the header only arrives at seed time, every existing install stays on the
96+
// old fingerprint forever — which is what the original #2067 patch would have shipped.
97+
describe("existing installs receive newly added static headers", () => {
98+
const persisted = (headers?: Record<string, string>): OcxProviderConfig => ({
99+
adapter: "openai-chat",
100+
baseUrl: "https://opencode.ai/zen/v1",
101+
keyOptional: true,
102+
...(headers ? { headers } : {}),
103+
});
104+
105+
test("a config saved with no header block gains the full registry set", () => {
106+
const routed = routedProviderConfig("opencode-free", persisted());
107+
expect(routed.headers?.["User-Agent"]).toBe("opencode");
108+
expect(routed.headers?.["x-opencode-client"]).toBe("desktop");
109+
});
110+
111+
test("a config saved with only the older marker gains the new one", () => {
112+
const routed = routedProviderConfig("opencode-free", persisted({ "x-opencode-client": "desktop" }));
113+
expect(routed.headers?.["User-Agent"]).toBe("opencode");
114+
expect(routed.headers?.["x-opencode-client"]).toBe("desktop");
115+
});
116+
117+
test("the merged headers reach the wire, not just the resolved config", () => {
118+
const routed = routedProviderConfig("opencode-free", persisted({ "x-opencode-client": "desktop" }));
119+
const req = createOpenAIChatAdapter(routed).buildRequest(minimalRequest());
120+
expect((req.headers as Record<string, string>)["User-Agent"]).toBe("opencode");
121+
});
122+
123+
test("a user override wins and does not become a second comma-joined value", () => {
124+
// HTTP header names are case-insensitive but object keys are not: a naive spread would
125+
// leave both "user-agent" and "User-Agent", which `Headers` serializes as
126+
// "custom-agent, opencode" — a corrupted request rather than an override.
127+
const routed = routedProviderConfig("opencode-free", persisted({ "user-agent": "custom-agent" }));
128+
const uaKeys = Object.keys(routed.headers ?? {}).filter(k => k.toLowerCase() === "user-agent");
129+
expect(uaKeys).toEqual(["user-agent"]);
130+
expect(routed.headers?.["user-agent"]).toBe("custom-agent");
131+
expect(new Headers(routed.headers as Record<string, string>).get("user-agent")).toBe("custom-agent");
132+
// Names the user did not claim are still filled.
133+
expect(routed.headers?.["x-opencode-client"]).toBe("desktop");
134+
});
135+
136+
test("model discovery carries the same fingerprint as inference", () => {
137+
// A provider identified as `opencode` when it completes but anonymous when it lists its
138+
// own models reads as two different clients to an upstream rate limiter.
139+
const req = buildModelsRequest(persisted({ "x-opencode-client": "desktop" }), undefined, "opencode-free");
140+
expect(req.headers["User-Agent"]).toBe("opencode");
141+
expect(req.headers["x-opencode-client"]).toBe("desktop");
142+
});
143+
144+
test("model discovery honors a user User-Agent override", () => {
145+
const req = buildModelsRequest(persisted({ "user-agent": "custom-agent" }), undefined, "opencode-free");
146+
const uaKeys = Object.keys(req.headers).filter(k => k.toLowerCase() === "user-agent");
147+
expect(uaKeys).toEqual(["user-agent"]);
148+
expect(req.headers["user-agent"]).toBe("custom-agent");
149+
});
150+
});
151+
87152
test("provider note mentions no key needed", () => {
88153
expect(entry?.note?.toLowerCase()).toContain("no key needed");
89154
expect(entry?.note?.toLowerCase()).toContain("200");

0 commit comments

Comments
 (0)