Files
OmniRoute/open-sse/utils/opencodeHeaders.ts
CyrixJD115 9222528bdd fix(opencode): session stability, free-tier routing, and CLI defaults (#10571)
* fix(opencode): session stability, free-tier routing, and CLI defaults

- Wire generateSessionId() into opencodeHeaders so x-opencode-session
  is a deterministic fingerprint instead of randomUUID() per request,
  enabling upstream prompt caching across a conversation
- Thread request body through buildHeaders() so session fingerprint
  has access to model, system, messages, and tools
- Default CLI header synthesis to ON (opt-out via false), align
  values with 9router proven defaults (opencode/desktop/global)
- Auto-echo listing-valid model names for noAuth providers so
  response.model matches /v1/models listing
- Short-circuit free-tier model resolution to opencode provider first
  to prevent prefix inference misrouting when catalog is unreachable

* fix(opencode): make free-tier default flip self-consistent + add coverage

PR #10571 flipped OPENCODE_SYNTHESIZE_CLI_HEADERS to on-by-default and
changed the synthesized UA/client/project default values, but shipped
with 2 broken assertions in the existing #5997 regression test and no
coverage for the new session-fingerprinting, free-tier routing, or
noAuth echoModel logic (Hard Rule #18).

- Update tests/unit/opencode-cli-headers-synthesis-5997.test.ts to match
  the new on-by-default behavior and new default values; add an explicit
  opt-out coverage test so the forward-only path is still guarded.
- Fix 20 further test failures in tests/unit/opencode-executor.test.ts
  and tests/unit/refactor-buildHeaders-opencode.test.ts caused by the
  same default flip (pin OPENCODE_SYNTHESIZE_CLI_HEADERS=false for the
  characterization suites that predate #10571; use a genuinely
  CLI-looking UA where the preserved-UA test requires one).
- Fix a real bug found via TDD while adding the mandated free-tier
  routing regression test: the big-pickle/*-free short-circuit in
  open-sse/services/model.ts checked activeProviders?.has("opencode")
  literally, but getActiveProviderSet() canonicalizes every connection's
  provider id through resolveProviderAlias(), which rewrites "opencode"
  to "opencode-zen" via a manual override — so an active no-auth
  opencode connection could never satisfy the check. Now checks both
  opencode-family candidate ids. Proven with a test that fails on the
  original code and passes with the fix (both connections active with a
  stale synced catalog omitting big-pickle).
- Extract the noAuth-provider echoModel aliasing in chatCore.ts into a
  pure, directly-testable helper (open-sse/handlers/chatCore/noAuthEchoModel.ts),
  matching the existing chatCore god-file decomposition pattern.
- Add regression tests for generateSessionId()-based x-opencode-session
  fingerprinting (stable within a conversation, changes on model/message
  changes), the free-tier routing short-circuit, and the noAuth echoModel
  aliasing.
- Add the changelog.d/ fragment and sync docs/reference/ENVIRONMENT.md's
  OPENCODE_SYNTHESIZE_CLI_HEADERS/OPENCODE_USER_AGENT/OPENCODE_CLIENT/
  OPENCODE_PROJECT rows to the new defaults.

Does NOT resolve whether flipping OPENCODE_SYNTHESIZE_CLI_HEADERS's
default was the right call, and does NOT touch the separate open PR
#10357 which flips the same flag with a different literal default value
- that decision is left to the maintainer at merge time.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
2026-08-18 10:52:33 -03:00

147 lines
6.1 KiB
TypeScript

import { randomUUID } from "crypto";
import { setUserAgentHeader } from "../executors/base.ts";
import { generateSessionId } from "../services/sessionManager.ts";
/**
* Header keys that are forwarded from the client to the upstream provider.
* Used by both OpencodeExecutor and DefaultExecutor.
*/
const OPENCODE_HEADER_KEYS = [
"x-opencode-session",
"x-opencode-request",
"x-opencode-project",
"x-opencode-client",
] as const;
/**
* Common agent-metadata headers used by non-OpenCode clients (custom agents/
* providers) for upstream request tracking and attribution. Forwarded the same
* way as the x-opencode-* set: case-insensitive lookup, client value wins.
* Added for 9router#2413 — these were previously dropped for every client
* outside the OpenCode allowlist.
*/
const AGENT_METADATA_HEADER_KEYS = ["x-session-id", "x-title"] as const;
/**
* Case-insensitive lookup for a header in a headers record.
*/
function findHeader(headers: Record<string, string>, name: string): string | undefined {
return Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
}
/**
* Forward OpenCode client request metadata headers to the upstream provider.
*
* Shared logic used by OpencodeExecutor and DefaultExecutor:
* 1. Forwards User-Agent from clientHeaders via `setUserAgentHeader()`
* 2. Forwards x-opencode-session, x-opencode-request, x-opencode-project,
* x-opencode-client headers (case-insensitive match)
* 3. Forwards x-session-id, x-title agent-metadata headers (case-insensitive
* match) — common conventions used by non-OpenCode agent clients (9router#2413)
*
* @param headers - The outbound headers record to mutate
* @param clientHeaders - The client-provided headers to forward from
* @param options.synthesizeRequestId - When true (OpencodeExecutor only), maps
* x-session-affinity / x-session-id to x-opencode-session when the latter is
* missing, and synthesizes a UUID for x-opencode-request if also missing.
* @param options.cliDefaults - When provided (OpencodeExecutor only), synthesize
* the OpenCode CLI identity headers that Cloudflare requires on VPS egress
* (User-Agent, x-opencode-client, x-opencode-project) plus fresh request/session
* UUIDs, but ONLY for keys the client did not already supply. Client values always
* win; these defaults only fill gaps. User-Agent is the one exception: a client UA
* that is not already the OpenCode CLI (e.g. curl/8.5.0) is REPLACED with the
* synthesized CLI UA, because opencode.ai's free tier rejects generic client UAs
* from datacenter IPs with FreeUsageLimitError 429. (#5997, follow-up #10229)
* @param options.sessionBody - Request body fields used to generate a
* conversation-stable session fingerprint (model, system, messages, tools).
* When provided, x-opencode-session is a deterministic hash instead of a random
* UUID, so upstream prompt caching hits across requests in the same conversation.
*/
export function forwardOpencodeClientHeaders(
headers: Record<string, string>,
clientHeaders: Record<string, string>,
options?: {
synthesizeRequestId?: boolean;
cliDefaults?: { userAgent: string; client: string; project: string };
sessionBody?: {
model?: string;
system?: unknown;
messages?: Array<{ role?: string; content?: unknown }>;
tools?: Array<{ name?: string; function?: { name?: string } }>;
};
}
): void {
// 1. Forward User-Agent
const clientUA = clientHeaders["User-Agent"] || clientHeaders["user-agent"];
if (clientUA) {
setUserAgentHeader(headers, clientUA);
}
// 2. Forward x-opencode-* metadata headers
for (const headerName of OPENCODE_HEADER_KEYS) {
const value = findHeader(clientHeaders, headerName);
if (value) {
headers[headerName] = value;
}
}
// 2b. Forward agent-metadata headers (x-session-id, x-title) — 9router#2413
for (const headerName of AGENT_METADATA_HEADER_KEYS) {
const value = findHeader(clientHeaders, headerName);
if (value) {
headers[headerName] = value;
}
}
// 3. OpencodeExecutor-only: synthesize session/request id from fallback headers
if (options?.synthesizeRequestId && !headers["x-opencode-session"]) {
const sessionAffinity =
findHeader(clientHeaders, "x-session-affinity") || findHeader(clientHeaders, "x-session-id");
if (sessionAffinity) {
headers["x-opencode-session"] = sessionAffinity;
if (!headers["x-opencode-request"]) {
headers["x-opencode-request"] = randomUUID();
}
}
}
// 4. OpencodeExecutor-only: synthesize the OpenCode CLI identity Cloudflare expects
// on VPS egress, for any key the client did not supply (#5997).
if (options?.cliDefaults) {
applyCliDefaults(headers, options.cliDefaults, options.sessionBody);
}
}
/**
* Fill the OpenCode CLI identity headers Cloudflare requires on VPS egress. For
* x-opencode-* headers, client values always win (defaults only fill gaps). The
* User-Agent is the exception: a non-CLI client UA (curl, python, SDKs) is replaced
* with the synthesized CLI UA, because opencode.ai's free tier flags generic client
* UAs from datacenter IPs (FreeUsageLimitError 429). A client UA that already looks
* like the OpenCode CLI (opencode-cli/...) is preserved so the real CLI's versioned
* identity stays intact. (#5997, follow-up)
*/
function applyCliDefaults(
headers: Record<string, string>,
cliDefaults: { userAgent: string; client: string; project: string },
sessionBody?: {
model?: string;
system?: unknown;
messages?: Array<{ role?: string; content?: unknown }>;
tools?: Array<{ name?: string; function?: { name?: string } }>;
}
): void {
const existingUa = headers["User-Agent"] || headers["user-agent"];
const clientUaIsCliLike =
typeof existingUa === "string" && /^opencode-cli\//i.test(existingUa.trim());
if (!clientUaIsCliLike) {
setUserAgentHeader(headers, cliDefaults.userAgent);
}
headers["x-opencode-client"] ||= cliDefaults.client;
headers["x-opencode-project"] ||= cliDefaults.project;
headers["x-opencode-request"] ||= randomUUID();
headers["x-opencode-session"] ||=
generateSessionId(sessionBody ?? null) || randomUUID();
}