Compare commits

..

1 Commits

Author SHA1 Message Date
diegosouzapw
a37c39ef73 fix(cli): setup-opencode respects --api-key/OMNIROUTE_API_KEY over context token (#12783) 2026-09-10 14:15:00 -03:00
10 changed files with 144 additions and 131 deletions

View File

@@ -35,16 +35,24 @@ export function resolveOpencodeTarget(opts = {}) {
baseUrl = `http://localhost:${Number(opts.port ?? process.env.PORT ?? 20128) || 20128}`;
}
// Precedence: explicit --api-key flag > OMNIROUTE_API_KEY env var > active
// context's management token. A context's accessToken/apiKey is a CLI
// management credential (oma_live_...) with no /v1/* inference scope — it
// must never silently outrank a real inference key the caller supplied
// either as a flag or via the ambient env var (mirrors the explicit >
// ambient-env > context precedence documented in bin/cli/api.mjs's
// buildHeaders()). Only fall back to the context token when neither an
// explicit flag nor the env var is set.
let apiKey = opts.apiKey ?? opts["api-key"];
if (!apiKey) apiKey = process.env.OMNIROUTE_API_KEY || "";
if (!apiKey) {
try {
const c = resolveActiveContext(opts.context ?? process.env.OMNIROUTE_CONTEXT);
apiKey = c?.accessToken || c?.apiKey;
apiKey = c?.accessToken || c?.apiKey || "";
} catch {
/* no context auth */
}
}
if (!apiKey) apiKey = process.env.OMNIROUTE_API_KEY || "";
return { baseUrl: baseUrl.replace(/\/+$/, ""), apiKey };
}
@@ -177,8 +185,17 @@ export function registerSetupOpencode(program) {
"--allow-container-write",
"Write even when the target is inside a container and not mounted from the host"
)
.action(async (opts) => {
const code = await runSetupOpencodeCommand(opts);
.action(async (opts, cmd) => {
// Commander parses the ancestor program's own global --api-key option
// (bin/cli/program.mjs, bound to .env("OMNIROUTE_API_KEY")) against any
// occurrence of the flag in argv, so it wins the value even when the
// user typed --api-key AFTER `setup-opencode` — this local option's own
// `opts.apiKey` never sees it. cmd.optsWithGlobals() resolves to the
// correct value either way ("globals overwrite locals" is exactly the
// outcome we want here, since the global option is where the value
// always actually lands).
const resolvedOpts = { ...opts, apiKey: cmd.optsWithGlobals().apiKey ?? opts.apiKey };
const code = await runSetupOpencodeCommand(resolvedOpts);
if (code !== 0) process.exit(code);
});
}

View File

@@ -1 +0,0 @@
- fix(providers): send `x-api-key` instead of `Authorization: Bearer` for OpenCode Zen's `/v1/responses` endpoint (Muse Spark Contributor models), fixing a 401 on OmniRoute's auth header (#12633)

View File

@@ -1 +0,0 @@
- fix(models): declare the real ~1M contextLength for OpenCode Zen's Muse Spark 1.2 models instead of falling back to the 200000 provider default (#12681)

View File

@@ -0,0 +1 @@
- fix(cli): setup-opencode no longer sends an active context's management token to `/v1/models` when `--api-key`/`OMNIROUTE_API_KEY` is supplied — an explicit flag or the env var now always outranks the context's token, and the flag itself is no longer swallowed by the parent program's global `--api-key` option (#12783)

View File

@@ -30,25 +30,17 @@ export const opencodeProvider: RegistryEntry = {
// content (see issue #10867). The opencode provider is passthrough, so
// declaring them here only sets the wire format / capability flags — the
// live upstream model list already advertises both ids.
// #12681: real window confirmed against the opencode-go registry's own
// muse-spark-1.2-contributor entries (contextLength: 1048576, maxOutputTokens:
// 131072) — without an explicit value here resolution fell back to the
// provider-wide defaultContextLength (200000), understating the real window.
{
id: "muse-spark-1.2",
name: "Muse Spark 1.2",
supportsReasoning: true,
targetFormat: "openai-responses",
contextLength: 1048576,
maxOutputTokens: 131072,
},
{
id: "muse-spark-1.2-contributor-free",
name: "Muse Spark 1.2 Contributor Free",
supportsReasoning: true,
targetFormat: "openai-responses",
contextLength: 1048576,
maxOutputTokens: 131072,
},
{ id: "deepseek-v4-flash-free", name: "DeepSeek V4 Flash Free", supportsReasoning: true },
// #6998: 2026-07-14 refresh — the upstream free tier rotated its lineup;

View File

@@ -63,17 +63,11 @@ export const opencode_zenProvider: RegistryEntry = {
// targetFormat declaration, so requests routed here still hit
// /chat/completions with a mismatched or unanswerable body and the
// upstream returns an empty message.
// #12681: real window confirmed against the opencode-go registry's own
// muse-spark-1.2-contributor entries (contextLength: 1048576, maxOutputTokens:
// 131072) — without an explicit value here resolution fell back to the
// provider-wide defaultContextLength (200000), understating the real window.
{
id: "muse-spark-1.2",
name: "Muse Spark 1.2",
supportsReasoning: true,
targetFormat: "openai-responses",
contextLength: 1048576,
maxOutputTokens: 131072,
},
// Explicit wire-format overlay of the base opencode provider's muse-spark entry
// (targetFormat: openai-responses). Keep in sync with base on catalog syncs.
@@ -82,8 +76,6 @@ export const opencode_zenProvider: RegistryEntry = {
name: "Muse Spark 1.2 Contributor Free",
supportsReasoning: true,
targetFormat: "openai-responses",
contextLength: 1048576,
maxOutputTokens: 131072,
},
// ── DeepSeek ────────────────────────────────────────────────

View File

@@ -31,13 +31,6 @@ import {
import { isOpencodeGeoBlocked, proxyKeyOf } from "./opencodeGeoBlock.ts";
import { isNetworkRotationSharedEgressGuardEnabled } from "@/shared/utils/featureFlags";
/**
* The main OpenCode Zen host, shared by the `opencode` and `opencode-zen`
* registry entries. Used to scope the `x-api-key` auth override (#12633) away
* from `opencode-go`, which serves a different upstream (`.../zen/go/v1`).
*/
const ZEN_BASE_URL = "https://opencode.ai/zen/v1";
/**
* Per-account proxy configuration, persisted by NoAuthAccountCard under
* `providerSpecificData.accountProxies` (keyed by the account id, which the UI
@@ -783,20 +776,6 @@ export class OpencodeExecutor extends BaseExecutor {
}
}
/**
* #12633: OpenCode Zen's `/v1/responses` endpoint (reached when
* `_requestFormat === "openai-responses"`, e.g. Muse Spark Contributor
* models) requires `x-api-key`, not `Authorization: Bearer` — unlike the
* default `/chat/completions` endpoint on the same host, which accepts
* Bearer. Scoped by baseUrl (not provider id/alias) so this only applies to
* the main Zen host (`opencode` / `opencode-zen`, both `https://opencode.ai/zen/v1`)
* and never to opencode-go, which serves Responses-format models from a
* different upstream (`https://opencode.ai/zen/go/v1`) that expects Bearer.
*/
private usesZenApiKeyAuth(): boolean {
return this._requestFormat === "openai-responses" && this.config?.baseUrl === ZEN_BASE_URL;
}
buildHeaders(
credentials: ProviderCredentials | null,
stream = true,
@@ -813,7 +792,7 @@ export class OpencodeExecutor extends BaseExecutor {
: undefined;
if (key) {
if (this._requestFormat === "claude" || this.usesZenApiKeyAuth()) {
if (this._requestFormat === "claude") {
headers["x-api-key"] = key;
} else {
headers["Authorization"] = `Bearer ${key}`;

View File

@@ -1,54 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { OpencodeExecutor } from "../../open-sse/executors/opencode.ts";
test("#12633: openai-responses format on opencode-zen sends x-api-key, not Authorization Bearer", () => {
const executor = new OpencodeExecutor("opencode-zen");
executor._requestFormat = "openai-responses";
const headers = executor.buildHeaders(
{ apiKey: "sk-zen-test" },
true,
null,
"muse-spark-1.2-contributor-free"
);
assert.equal(headers["x-api-key"], "sk-zen-test");
assert.equal(headers["Authorization"], undefined);
});
test("#12633: openai-responses format on the base opencode (oc) provider also sends x-api-key", () => {
const executor = new OpencodeExecutor("opencode");
executor._requestFormat = "openai-responses";
const headers = executor.buildHeaders(
{ apiKey: "sk-oc-test" },
true,
null,
"muse-spark-1.2-contributor-free"
);
assert.equal(headers["x-api-key"], "sk-oc-test");
assert.equal(headers["Authorization"], undefined);
});
test("#12633: openai-responses format on opencode-go (different upstream endpoint) keeps Authorization Bearer", () => {
const executor = new OpencodeExecutor("opencode-go");
executor._requestFormat = "openai-responses";
const headers = executor.buildHeaders(
{ apiKey: "sk-go-test" },
true,
null,
"muse-spark-1.2-contributor"
);
assert.equal(headers["Authorization"], "Bearer sk-go-test");
assert.equal(headers["x-api-key"], undefined);
});
test("#12633: claude format keeps sending x-api-key (unchanged behavior)", () => {
const executor = new OpencodeExecutor("opencode-zen");
executor._requestFormat = "claude";
const headers = executor.buildHeaders({ apiKey: "sk-claude-test" }, true, null, "some-model");
assert.equal(headers["x-api-key"], "sk-claude-test");
assert.equal(headers["Authorization"], undefined);
});

View File

@@ -1,33 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { REGISTRY } from "../../open-sse/config/providerRegistry.ts";
import { getTokenLimit } from "../../open-sse/services/contextManager.ts";
test("#12681: opencode registry declares an explicit real contextLength for muse-spark-1.2 models", () => {
const opencode = REGISTRY["opencode"];
const museSpark = opencode.models.find((m) => m.id === "muse-spark-1.2");
const museSparkFree = opencode.models.find((m) => m.id === "muse-spark-1.2-contributor-free");
assert.notEqual(
museSpark?.contextLength,
undefined,
"muse-spark-1.2 should declare its own real contextLength instead of relying on the 200000 provider default"
);
assert.notEqual(
museSparkFree?.contextLength,
undefined,
"muse-spark-1.2-contributor-free should declare its own real contextLength instead of relying on the 200000 provider default"
);
});
test("#12681: opencode-zen registry declares an explicit real contextLength for muse-spark-1.2 models", () => {
const zen = REGISTRY["opencode-zen"];
const museSpark = zen.models.find((m) => m.id === "muse-spark-1.2");
const museSparkFree = zen.models.find((m) => m.id === "muse-spark-1.2-contributor-free");
assert.notEqual(museSpark?.contextLength, undefined);
assert.notEqual(museSparkFree?.contextLength, undefined);
});
test("#12681: contextManager.getTokenLimit resolves muse-spark-1.2-contributor-free to its real 1M+ window, not the 200000 provider default", () => {
assert.equal(getTokenLimit("opencode", "muse-spark-1.2-contributor-free"), 1048576);
assert.equal(getTokenLimit("opencode-zen", "muse-spark-1.2-contributor-free"), 1048576);
});

View File

@@ -0,0 +1,121 @@
import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { resolveOpencodeTarget } from "../../bin/cli/commands/setup-opencode.mjs";
/** Point OMNIROUTE_CONTEXT config resolution at an isolated, throwaway DATA_DIR. */
function withIsolatedContext(contextConfig, fn) {
const dir = mkdtempSync(join(tmpdir(), "omniroute-setup-opencode-test-"));
const originalDataDir = process.env.DATA_DIR;
process.env.DATA_DIR = dir;
writeFileSync(
join(dir, "config.json"),
JSON.stringify({
version: 1,
currentContext: "remote",
contexts: { remote: contextConfig },
})
);
try {
return fn();
} finally {
if (originalDataDir === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = originalDataDir;
rmSync(dir, { recursive: true, force: true });
}
}
function withEnvApiKey(value, fn) {
const original = process.env.OMNIROUTE_API_KEY;
if (value === undefined) delete process.env.OMNIROUTE_API_KEY;
else process.env.OMNIROUTE_API_KEY = value;
try {
return fn();
} finally {
if (original === undefined) delete process.env.OMNIROUTE_API_KEY;
else process.env.OMNIROUTE_API_KEY = original;
}
}
test("setup-opencode: --api-key typed AFTER the subcommand name is not stolen by the parent program's global option", async () => {
const { createProgram } = await import("../../bin/cli/program.mjs");
const program = createProgram();
const setupOpencode = program.commands.find((c) => c.name() === "setup-opencode");
assert.ok(setupOpencode, "setup-opencode subcommand must be registered");
let capturedApiKey;
setupOpencode._actionHandler = null; // avoid the real network-calling action
setupOpencode.action((opts, cmd) => {
capturedApiKey = cmd.optsWithGlobals().apiKey ?? opts.apiKey;
});
await program.parseAsync(
[
"node",
"omniroute",
"setup-opencode",
"--remote",
"http://100.64.0.1:20128",
"--api-key",
"sk-TESTKEY123",
],
{ from: "node" }
);
assert.equal(
capturedApiKey,
"sk-TESTKEY123",
"the CLI-supplied --api-key value must reach the setup-opencode action handler"
);
});
test("resolveOpencodeTarget: (a) explicit --api-key flag wins over an active context's management token", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ apiKey: "sk-FLAG", context: "remote" });
assert.equal(apiKey, "sk-FLAG");
}
);
});
});
test("resolveOpencodeTarget: (b) OMNIROUTE_API_KEY env wins over an active context's management token when no flag is passed", () => {
withEnvApiKey("sk-ENVKEY", () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ context: "remote" });
assert.equal(apiKey, "sk-ENVKEY");
}
);
});
});
test("resolveOpencodeTarget: (c) the context's token is used only when neither a flag nor the env var is set", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ context: "remote" });
assert.equal(apiKey, "oma_live_CONTEXT_TOKEN");
}
);
});
});
test("resolveOpencodeTarget: falls back to '' when neither a flag, env var, nor a resolvable context is present", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext({ baseUrl: "http://100.64.0.1:20128" }, () => {
const { apiKey } = resolveOpencodeTarget({
remote: "http://100.64.0.1:20128",
context: "__no-such-context__",
});
assert.equal(apiKey, "");
});
});
});