refactor(chatCore): extrai resolvers de service-tier do Codex para leaf puro (#3501) (#4477)

Integrated into release/v3.8.32
This commit is contained in:
Diego Rodrigues de Sa e Souza
2026-06-21 08:30:20 -03:00
committed by GitHub
parent 3b69960b3b
commit e95fab8bbe
4 changed files with 150 additions and 37 deletions

View File

@@ -1,5 +1,6 @@
{
"_comment": "Catraca de tamanho (check-file-size.mjs). frozen so pode encolher; arquivos novos <= cap. --update ratcheta.",
"_rebaseline_2026_06_21_qg9_chatcore_service_tier": "QG v2 Fase 9 T5 (#3501) — chatCore.ts 5137->5110 (shrink -27). The two inline Codex service-tier resolvers (resolveEffectiveServiceTier / resolveReportedServiceTier, ~36 LOC) were extracted byte-identically into the new pure leaf open-sse/handlers/chatCore/serviceTier.ts; the handler now keeps a `let effectiveServiceTier` + two thin binding closures that pass provider/credentials?.providerSpecificData to the extracted functions, so every call site stays unchanged. The orphaned getCodexRequestDefaults/normalizeCodexServiceTier/CodexServiceTier imports moved to the leaf. Ratcheted the frozen value down to lock the freed budget. Covered by tests/unit/chatcore-service-tier.test.ts.",
"_rebaseline_2026_06_20_reviewprs_mine_r2_filesize": "Reconciliacao file-size pos-lote /review-prs 'apenas minhas' r2: dois frozen cresceram cumulativamente sem bump (cada PR media OK na sua base, mas o crescimento empilhou acima do frozen no tip de merge; o fast-path do release nao roda check:file-size, so release->main). (1) src/shared/constants/pricing.ts 1620->1623 (+3 = linhas de pricing Claude Code (cc) do #4440, sobre o 1620 que o #4447 ja setara para gpt-4.1-mini/nano + o3/o4-mini). (2) open-sse/executors/base.ts 1399->1407 (+8 = handling granular de reasoning_effort para Claude no Copilot do #4443). Ambos dados/wiring coesos nos chokepoints existentes; nao extraiveis. Cobertos por tests/unit (claude-code pricing / base-executor-sanitize-effort + github-claude-reasoning-effort-granular).",
"_rebaseline_2026_06_20_4023_web_cookie_noauth_validation": "PR #4023 (oyi77) own growth: src/lib/providers/validation.ts 4450->4518 (+68 = a new validateWebCookieProvider that probes the provider's /models endpoint — 401/403 => AUTH_007 SESSION_EXPIRED, any other status => valid session, empty cookie => invalid, provider-not-in-registry => unsupported — plus a local STANDARD_USER_AGENT const for the probe). Cohesive validator at the validateProviderApiKey dispatch; not extractable. Covered by tests/unit/provider-validation-web-cookie-auth007.test.ts. Heavily curated on merge — the PR's branch was badly stale-based (squash-base-stale), so its tree was DESTRUCTIVE: providers/index.ts deleted live providers openadapter/dit/tokenrouter (added by #4313) and the executor/base.ts edits reverted release fixes (#4037 duckduckgo host, theoldllm gpt5 models, base.ts fetch-start-timeout). Only the purely-additive validation feature was kept (validation.ts validateWebCookieProvider + errorCodes AUTH_007 + the test). Dropped: 5 malformed new registry entries (used non-RegistryEntry fields defaultModel/auth + referenced non-existent executors -> tsc TS2353), the destructive providers/index.ts + executor reverts, the unrelated pr-*.sh automation scripts, and evals/types.ts (belongs to the deferred evals modularization #4422). Also removed the PR's fragile 'Phase 2' executor probe (ran a live upstream chat during validation + classified any 'auth'-containing error as SESSION_EXPIRED) and rewrote the test to install its fetch mock before module load (the original mocked too late and silently hit live chatgpt.com).",
"_rebaseline_2026_06_20_1308_model_lockout_honors_reset": "port from 9router#1308 own growth: open-sse/services/accountFallback.ts 1731->1752 (+21 = the new exported pure helper selectLockoutCooldownMs + its doc comment — picks the parsed upstream reset as the model-lockout exactCooldownMs when it exceeds the base cooldown, e.g. Antigravity \"Resets in 160h\", else preserves the existing 0/base behavior) and open-sse/executors/antigravity.ts 1680->1686 (this PR +1 = parseRetryFromErrorMessage regex `reset` -> `resets?` so plural \"Resets in 160h27m24s\" matches, plus a comment line; frozen set to the SUM 1686 with the concurrent #1944 which adds +5 at the disjoint passthroughFields region of the same file, so either merge order passes — pair-file rule). The combo lockout call sites in combo.ts now pass selectLockoutCooldownMs(cooldownMs, mlSettings) instead of always base/exponential, so an exhausted model honors the real upstream reset instead of being retried within minutes. Both edits are cohesive at the existing lockout/parse chokepoints; the helper is its own pure function (not extractable further). Covered by tests/unit/combo-model-lockout-honors-reset-1308.test.ts.",
@@ -104,7 +105,7 @@
"open-sse/executors/muse-spark-web.ts": 1284,
"open-sse/executors/perplexity-web.ts": 1013,
"open-sse/handlers/audioSpeech.ts": 965,
"open-sse/handlers/chatCore.ts": 5137,
"open-sse/handlers/chatCore.ts": 5110,
"open-sse/handlers/imageGeneration.ts": 3777,
"open-sse/handlers/responseSanitizer.ts": 1103,
"open-sse/handlers/search.ts": 1546,

View File

@@ -193,10 +193,10 @@ import {
shouldRequestClaudeFastMode,
} from "@/lib/providers/claudeFastMode";
import {
getCodexRequestDefaults,
normalizeCodexServiceTier,
type CodexServiceTier,
} from "@/lib/providers/requestDefaults";
resolveEffectiveServiceTier as resolveEffectiveServiceTierFor,
resolveReportedServiceTier as resolveReportedServiceTierFor,
type EffectiveServiceTier,
} from "./chatCore/serviceTier.ts";
import { cacheReasoningFromAssistantMessage } from "../services/reasoningCache.ts";
import { sanitizeOpenAITool } from "../services/toolSchemaSanitizer.ts";
import {
@@ -737,42 +737,15 @@ export async function handleChatCore({
);
}
type EffectiveServiceTier = "standard" | CodexServiceTier;
let effectiveServiceTier: EffectiveServiceTier = "standard";
const resolveEffectiveServiceTier = (requestBody?: unknown): EffectiveServiceTier => {
if (provider !== "codex") return "standard";
const requestRecord =
requestBody && typeof requestBody === "object" && !Array.isArray(requestBody)
? (requestBody as Record<string, unknown>)
: {};
const rawServiceTier = requestRecord.service_tier;
if (typeof rawServiceTier === "string" && rawServiceTier.trim().length > 0) {
const normalizedServiceTier = normalizeCodexServiceTier(rawServiceTier);
if (normalizedServiceTier) return normalizedServiceTier;
}
return getCodexRequestDefaults(credentials?.providerSpecificData).serviceTier ?? "standard";
};
// Codex service-tier resolvers extracted to chatCore/serviceTier.ts (#3501); bind the per-request
// provider/credentials once and delegate so the existing call sites stay byte-identical.
const resolveEffectiveServiceTier = (requestBody?: unknown): EffectiveServiceTier =>
resolveEffectiveServiceTierFor(provider, credentials?.providerSpecificData, requestBody);
const resolveReportedServiceTier = (
payload?: unknown,
maxDepth = 3
): EffectiveServiceTier | null => {
if (
maxDepth <= 0 ||
provider !== "codex" ||
!payload ||
typeof payload !== "object" ||
Array.isArray(payload)
) {
return null;
}
const record = payload as Record<string, unknown>;
const rawServiceTier = record.service_tier;
if (typeof rawServiceTier === "string" && rawServiceTier.trim().length > 0) {
const normalizedServiceTier = normalizeCodexServiceTier(rawServiceTier);
if (normalizedServiceTier) return normalizedServiceTier;
}
return resolveReportedServiceTier(record.response, maxDepth - 1);
};
): EffectiveServiceTier | null => resolveReportedServiceTierFor(provider, payload, maxDepth);
const persistFailureUsage = (statusCode: number, errorCode?: string | null) => {
saveRequestUsage({
provider: provider || "unknown",

View File

@@ -0,0 +1,70 @@
/**
* chatCore Codex service-tier resolvers (Quality Gate v2 / Fase 9 — chatCore god-file
* decomposition, #3501).
*
* Pure, side-effect-free extraction of the two service-tier resolvers that used to be inline
* closures at the top of handleChatCore. Both are no-ops for non-Codex providers; for Codex they
* read the client-supplied `service_tier`, normalize it, and fall back to the per-connection
* request defaults. Behaviour is byte-identical to the previous inline code — the handler now binds
* `provider`/`providerSpecificData` once and delegates here.
*/
import {
getCodexRequestDefaults,
normalizeCodexServiceTier,
type CodexServiceTier,
} from "@/lib/providers/requestDefaults";
/** The effective service tier carried through a request: "standard" or a normalized Codex tier. */
export type EffectiveServiceTier = "standard" | CodexServiceTier;
/**
* Resolve the effective service tier for the *outbound* request. Non-Codex providers are always
* "standard". For Codex, a valid client `service_tier` wins; otherwise the per-connection request
* default applies, falling back to "standard".
*/
export function resolveEffectiveServiceTier(
provider: string | null | undefined,
providerSpecificData: unknown,
requestBody?: unknown
): EffectiveServiceTier {
if (provider !== "codex") return "standard";
const requestRecord =
requestBody && typeof requestBody === "object" && !Array.isArray(requestBody)
? (requestBody as Record<string, unknown>)
: {};
const rawServiceTier = requestRecord.service_tier;
if (typeof rawServiceTier === "string" && rawServiceTier.trim().length > 0) {
const normalizedServiceTier = normalizeCodexServiceTier(rawServiceTier);
if (normalizedServiceTier) return normalizedServiceTier;
}
return getCodexRequestDefaults(providerSpecificData).serviceTier ?? "standard";
}
/**
* Resolve the service tier *reported by the upstream* response. Non-Codex providers and missing
* payloads return null (caller keeps the prior value). For Codex, reads a top-level `service_tier`
* and otherwise descends through nested `response` envelopes up to `maxDepth` levels.
*/
export function resolveReportedServiceTier(
provider: string | null | undefined,
payload?: unknown,
maxDepth = 3
): EffectiveServiceTier | null {
if (
maxDepth <= 0 ||
provider !== "codex" ||
!payload ||
typeof payload !== "object" ||
Array.isArray(payload)
) {
return null;
}
const record = payload as Record<string, unknown>;
const rawServiceTier = record.service_tier;
if (typeof rawServiceTier === "string" && rawServiceTier.trim().length > 0) {
const normalizedServiceTier = normalizeCodexServiceTier(rawServiceTier);
if (normalizedServiceTier) return normalizedServiceTier;
}
return resolveReportedServiceTier(provider, record.response, maxDepth - 1);
}

View File

@@ -0,0 +1,69 @@
// tests/unit/chatcore-service-tier.test.ts
// Characterization of the Codex service-tier resolvers extracted from handleChatCore
// (chatCore god-file decomposition, #3501). Locks the provider!=="codex" short-circuit,
// the request-body service_tier normalization + defaults fallback, and the recursive
// descent through nested `response` payloads in resolveReportedServiceTier.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
resolveEffectiveServiceTier,
resolveReportedServiceTier,
} from "../../open-sse/handlers/chatCore/serviceTier.ts";
test("resolveEffectiveServiceTier: non-codex provider is always standard", () => {
assert.equal(resolveEffectiveServiceTier("openai", undefined, { service_tier: "flex" }), "standard");
assert.equal(resolveEffectiveServiceTier(null, undefined, { service_tier: "priority" }), "standard");
});
test("resolveEffectiveServiceTier: codex reads a valid request service_tier", () => {
assert.equal(resolveEffectiveServiceTier("codex", undefined, { service_tier: "priority" }), "priority");
assert.equal(resolveEffectiveServiceTier("codex", undefined, { service_tier: "flex" }), "flex");
});
test("resolveEffectiveServiceTier: codex with blank/absent/non-string service_tier falls back to defaults", () => {
// No providerSpecificData default → "standard"
assert.equal(resolveEffectiveServiceTier("codex", undefined, {}), "standard");
assert.equal(resolveEffectiveServiceTier("codex", undefined, { service_tier: " " }), "standard");
assert.equal(resolveEffectiveServiceTier("codex", undefined, { service_tier: 7 }), "standard");
assert.equal(resolveEffectiveServiceTier("codex", undefined, undefined), "standard");
// Non-object body is treated as empty record → defaults
assert.equal(resolveEffectiveServiceTier("codex", undefined, "not-an-object"), "standard");
assert.equal(resolveEffectiveServiceTier("codex", undefined, [1, 2]), "standard");
});
test("resolveEffectiveServiceTier: codex honors the providerSpecificData serviceTier default", () => {
const psd = { requestDefaults: { serviceTier: "priority" } };
assert.equal(resolveEffectiveServiceTier("codex", psd, {}), "priority");
// An explicit, valid request tier still wins over the default
assert.equal(resolveEffectiveServiceTier("codex", psd, { service_tier: "flex" }), "flex");
});
test("resolveReportedServiceTier: non-codex / missing payload → null", () => {
assert.equal(resolveReportedServiceTier("openai", { service_tier: "flex" }), null);
assert.equal(resolveReportedServiceTier("codex", null), null);
assert.equal(resolveReportedServiceTier("codex", undefined), null);
assert.equal(resolveReportedServiceTier("codex", []), null);
});
test("resolveReportedServiceTier: reads a top-level service_tier", () => {
assert.equal(resolveReportedServiceTier("codex", { service_tier: "priority" }), "priority");
});
test("resolveReportedServiceTier: descends into nested response payloads", () => {
assert.equal(
resolveReportedServiceTier("codex", { response: { service_tier: "flex" } }),
"flex"
);
assert.equal(
resolveReportedServiceTier("codex", { response: { response: { service_tier: "priority" } } }),
"priority"
);
});
test("resolveReportedServiceTier: stops after maxDepth and returns null when nothing matches", () => {
// 4 levels deep but default maxDepth=3 → never reaches the leaf tier
const deep = { response: { response: { response: { service_tier: "priority" } } } };
assert.equal(resolveReportedServiceTier("codex", deep), null);
// No service_tier anywhere → null
assert.equal(resolveReportedServiceTier("codex", { response: { foo: "bar" } }), null);
});