Files
OmniRoute/open-sse/executors/xai.ts
Alex 9db5377d7b feat(providers): add xAI OAuth PKCE provider (#7399)
* chore(ci): add .mergify.yml to main — Mergify only reads config from the default branch (#7168)

* fix(ci): add the auto-enqueue pull_request_rule to the Mergify config (queue_conditions alone are eligibility-only) (#7179)

* fix(ci): migrate Mergify auto-enqueue to merge_protections_settings.auto_merge_conditions (rules-based path is EOL 2026-07-16) (#7216)

* fix(ci): drop Mergify batch settings (batching is a paid-tier feature; free plan queue is serial) (#7220)

* fix(ci): merge queue tolerates the advisory dast-smoke failure (its GH-hosted build hang dequeued every attempt) (#7225)

* test(ci): make the #6634 selfref guard hermetic — main's copy hard-fails every PR (#7341)

main's copy of this test still does git I/O inside a unit test:

    const baseSrc = git(['show', 'origin/main:' + FILE]);

Runners check out a shallow single ref, so origin/main does not resolve and the
test dies with 'fatal: invalid object name origin/main'. Every PR into main
fails Unit Tests (7/8) on it — today that is #7313, #7315, #7316, #7334, #7336
and #7337, six PRs red on a defect none of them introduced. #7313 has no other
red at all.

release/v3.8.49 already carries a fix (2e42b8efc, #7174: try/catch, fetch
origin/main on demand, t.skip() when unreachable), but it only reaches main at
release time — so main stays broken for the whole cycle. Cherry-picking it would
also import a new problem: PR Test Policy classifies t.skip() as a silenced
assertion, which we watched it correctly catch on #7300 today.

This is the hermetic version instead (ported from #7327, which does the same for
the release branch): read the file straight off disk, compare against an empty
base so baseTaut/baseExtTaut are 0 — the strictest possible comparison point —
and call evaluateMasking() directly. No git ref, no fetch, no skip, nothing the
runner's checkout depth can break.

The #6634 regression stays covered: the guard's logic lives in
SELF_TEST_FIXTURE_RE (check-test-masking.mjs:337), not in the test. Proven both
ways on main before committing — neutralise SELF_TEST_FIXTURE_RE to /$^/ and
the test FAILS; restore it and it passes 2/2, with check-test-masking.mjs left
byte-identical.

Co-authored-by: growab <nekron@icloud.com>

* chore(quality): tighten main's coverage baseline to the CI's real numbers (#7347)

main's ratchet had been failing --require-tighten on every PR: 11 metrics
improved but the baseline was never tightened. Same class as the #6634
selfref guard — an infra fix that lands only on the release branch leaves
main red for the whole cycle, and every PR into main pays for it.

Values are the merged-coverage numbers from a run on main itself (a local
run measures ~68% vs CI's ~80%; the baseline's own note warns about that
gap). Only the 11 coverage values change — gitleaks and semgrepFindings
keep main's own state.

No changelog fragment: #7326 carries it on release/v3.8.49, and a second
one here would double the entry at release time.

* feat(providers): add xAI OAuth PKCE

* docs(changelog): note xAI OAuth provider

* test(xai): assert OAuth refresh client id

* refactor(oauth): rebaseline OAuthModal wiring note (file-size cap)

Correct the file-size-baseline.json annotation for the xai-oauth PKCE
provider-switch branch in OAuthModal.tsx (993->998, +5) to match the
modal's existing historical-progression annotation style (969->989->
993->998; structural shrink tracked in #3501). The frozen value (998)
stays unchanged — only the annotation text is corrected.

tests/unit/oauth-providers-config.test.ts already sits exactly at its
frozen cap (845) after registering xai-oauth in the shared provider
enumerations (import, EXPECTED_PROVIDER_KEYS, EXPECTED_CONFIG_BY_PROVIDER,
REQUIRED_FIELDS_BY_PROVIDER). check:file-size reports 0 violations for
it, so no test move or baseline bump was needed.

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

* test(oauth): compact required-field arrays (file-size budget on frozen oauth-providers-config suite)

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

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <8016841+diegosouzapw@users.noreply.github.com>
Co-authored-by: growab <nekron@icloud.com>
Co-authored-by: alexey.nazarov@softmg.ru <alexey.nazarov@softmg.ru>
Co-authored-by: Alex <4217955+fenix007@users.noreply.github.com>
2026-07-18 21:18:53 -03:00

160 lines
6.0 KiB
TypeScript

import { BaseExecutor, type ExecutorLog, type ProviderCredentials } from "./base.ts";
import { PROVIDERS } from "../config/constants.ts";
import { getModelTargetFormat } from "../config/providerModels.ts";
type JsonRecord = Record<string, unknown>;
/**
* xAI/Grok model ids (open-sse/config/providers/registry/xai/index.ts) that accept
* a graduated `reasoning_effort`. Kept narrow and reconciled against the REAL
* catalog rather than upstream's example ids (grok-4/grok-3 do not exist here):
* - grok-4.3 — current-generation flagship, reasoning-capable.
* - grok-4.20-0309-reasoning — explicit reasoning variant.
*
* grok-4.20-multi-agent-0309 is intentionally left unclassified (neither allow
* nor deny): its reasoning support is not documented in the local catalog, so
* we pass it through unchanged rather than guess.
*/
const REASONING_ALLOWED = ["grok-4.3", "grok-4.20-0309-reasoning"];
/**
* Model ids that reject `reasoning_effort` outright:
* - grok-build-0.1 — build/tool-oriented model, no reasoning mode.
* - grok-4.20-0309-non-reasoning — already encodes "no reasoning" in the id;
* forwarding reasoning_effort here would be redundant/rejected upstream.
*/
const REASONING_DENIED = ["grok-build-0.1", "grok-4.20-0309-non-reasoning"];
/** `-{level}` suffixes some clients append to a model id to select reasoning intensity. */
const EFFORT_SUFFIXES = ["low", "medium", "high", "xhigh"] as const;
function asRecord(value: unknown): JsonRecord | null {
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : null;
}
/**
* xAI/Grok executor (port of decolua/9router#2147).
*
* Some Grok clients select reasoning intensity via a `-{low,medium,high,xhigh}`
* suffix on the model id (e.g. `grok-4.3-high`) rather than a native
* `reasoning_effort` field — xAI itself does not recognize the suffixed id.
* This executor:
* 1. Parses and strips that suffix off the model id before the request
* reaches xAI, mapping it to `reasoning_effort` for allow-listed models.
* 2. Strips any `reasoning_effort` for deny-listed models — including ids
* that already encode their reasoning state in the name (`-reasoning` /
* `-non-reasoning`), which must not be double-mutated by also stacking a
* `reasoning_effort` field on top of what the id already declares.
* 3. Leaves unclassified models and bodies untouched otherwise.
*/
export class XaiExecutor extends BaseExecutor {
constructor(provider = "xai") {
super(provider, PROVIDERS[provider]);
}
/**
* Port of decolua/9router#2439 (author: @ryanngit): xAI ships a native
* `/v1/responses` endpoint alongside `/v1/chat/completions`. Models tagged
* `targetFormat: "openai-responses"` in the registry (currently
* grok-4.20-multi-agent-0309, per upstream) resolve to that endpoint instead
* of the default chat-completions bridge. The per-model registry tag is the
* single source of truth — it also drives chatCore's body translation — so
* the URL stays in lockstep with the translated body, mirroring the gh
* executor's targetFormat-driven routing (9router#102) and the "openai"
* -pro heuristic in open-sse/executors/default.ts.
*/
buildUrl(model: string, _stream: boolean, _urlIndex = 0) {
if (getModelTargetFormat(this.provider, model) === "openai-responses") {
return this.config.responsesBaseUrl || this.config.baseUrl;
}
return this.config.baseUrl;
}
async refreshCredentials(
credentials: ProviderCredentials,
log?: ExecutorLog | null
): Promise<Partial<ProviderCredentials> | null> {
if (this.provider !== "xai-oauth" || !credentials.refreshToken) return null;
try {
const response = await fetch(this.config.tokenUrl || "https://auth.x.ai/oauth2/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
body: new URLSearchParams({
grant_type: "refresh_token",
client_id: this.config.clientId || "",
refresh_token: credentials.refreshToken,
}),
});
if (!response.ok) {
log?.warn?.("TOKEN_REFRESH", `xAI OAuth refresh failed with status ${response.status}`);
return null;
}
const data = await response.json();
if (!data.access_token) {
log?.warn?.("TOKEN_REFRESH", "xAI OAuth refresh response omitted access_token");
return null;
}
const expiresIn = Number(data.expires_in) || 21600;
return {
accessToken: data.access_token,
refreshToken: data.refresh_token || credentials.refreshToken,
expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),
};
} catch (error) {
log?.warn?.(
"TOKEN_REFRESH",
`xAI OAuth refresh error: ${error instanceof Error ? error.message : String(error)}`
);
return null;
}
}
transformRequest(
model: string,
body: unknown,
stream: boolean,
credentials: ProviderCredentials
): unknown {
const cleaned = super.transformRequest(model, body, stream, credentials);
const record = asRecord(cleaned);
if (!record) return cleaned;
const out: JsonRecord = { ...record };
let modelId = typeof out.model === "string" ? out.model : model;
let suffixEffort: string | null = null;
for (const level of EFFORT_SUFFIXES) {
const suffix = `-${level}`;
if (modelId.endsWith(suffix)) {
suffixEffort = level;
modelId = modelId.slice(0, -suffix.length);
break;
}
}
if (suffixEffort && typeof out.model === "string") {
out.model = modelId;
}
const isDenied = REASONING_DENIED.some((id) => modelId.includes(id));
const isAllowed = REASONING_ALLOWED.some((id) => modelId.includes(id));
if (isDenied) {
delete out.reasoning_effort;
} else if (isAllowed) {
const effort = suffixEffort || out.reasoning_effort;
if (effort) out.reasoning_effort = effort;
}
return out;
}
}
export default XaiExecutor;