Repository navigation
refactor(chatCore): extrai resolveExecutorWithProxy + getExecutionCredentials para leaves (#3501) #4646
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
refactor(chatCore): extrai resolveExecutorWithProxy + getExecutionCredentials para leaves (#3501) #4646
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| /** | ||
| * chatCore execution-credentials resolver (Quality Gate v2 / Fase 9 — chatCore god-file | ||
| * decomposition, #3501). | ||
| * | ||
| * Pure builder extracted from handleChatCore: derives the per-execution credentials object from the | ||
| * resolved request context. Applies the native-Codex passthrough endpoint override, forces | ||
| * apiType=responses (and the responses-upstream marker) for Azure AI Foundry / OCI when the model | ||
| * routes to the OpenAI Responses format, and threads the Claude Code session id when present. | ||
| * Side-effect-free; behaviour is byte-identical to the previous inline closure. | ||
| */ | ||
|
|
||
| import { FORMATS } from "../../translator/formats.ts"; | ||
|
|
||
| type CredentialsLike = | ||
| | { | ||
| providerSpecificData?: Record<string, unknown> | null; | ||
| [key: string]: unknown; | ||
| } | ||
| | null | ||
| | undefined; | ||
|
|
||
| export function resolveExecutionCredentials(opts: { | ||
| credentials: CredentialsLike; | ||
| nativeCodexPassthrough: boolean; | ||
| endpointPath: string; | ||
| targetFormat: string; | ||
| provider: string | null | undefined; | ||
| ccSessionId: string | null; | ||
| }) { | ||
| const { credentials, nativeCodexPassthrough, endpointPath, targetFormat, provider, ccSessionId } = | ||
| opts; | ||
|
|
||
| const nextCredentials = nativeCodexPassthrough | ||
| ? { ...credentials, requestEndpointPath: endpointPath } | ||
| : credentials; | ||
|
|
||
| const providerSpecificData = | ||
| nextCredentials?.providerSpecificData && | ||
| typeof nextCredentials.providerSpecificData === "object" | ||
| ? { ...nextCredentials.providerSpecificData } | ||
| : {}; | ||
|
|
||
| // Some providers (Azure AI Foundry, OCI OpenAI-compatible) choose upstream | ||
| // endpoint path from providerSpecificData.apiType. When a model routes to | ||
| // OpenAI Responses format, force apiType=responses unless explicitly set. | ||
| if ( | ||
| targetFormat === FORMATS.OPENAI_RESPONSES && | ||
| (provider === "azure-ai" || provider === "oci") && | ||
| providerSpecificData.apiType !== "responses" | ||
| ) { | ||
| providerSpecificData.apiType = "responses"; | ||
| } | ||
|
|
||
| if (targetFormat === FORMATS.OPENAI_RESPONSES && (provider === "azure-ai" || provider === "oci")) { | ||
| providerSpecificData._omnirouteForceResponsesUpstream = true; | ||
| } | ||
|
|
||
| const withApiType = { | ||
| ...nextCredentials, | ||
| providerSpecificData, | ||
| }; | ||
|
|
||
| if (!ccSessionId) return withApiType; | ||
|
|
||
| return { | ||
| ...withApiType, | ||
| providerSpecificData: { | ||
| ...(withApiType?.providerSpecificData || {}), | ||
| ccSessionId, | ||
| }, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,98 @@ | ||||||||||||||
| /** | ||||||||||||||
| * chatCore upstream-proxy executor resolver (Quality Gate v2 / Fase 9 — chatCore god-file | ||||||||||||||
| * decomposition, #3501). | ||||||||||||||
| * | ||||||||||||||
| * Extracted from handleChatCore: resolves the executor for a provider honoring the configured | ||||||||||||||
| * upstream proxy mode. `native` / disabled → the provider's own executor; `cliproxyapi` → the | ||||||||||||||
| * CLIProxyAPI passthrough executor; `fallback` → a wrapper that tries the native executor first and | ||||||||||||||
| * retries via CLIProxyAPI on configured failure codes (default 5xx + 429 + network) or on a thrown | ||||||||||||||
| * error. Behaviour is byte-identical to the previous inline closure (it only captured `log`). | ||||||||||||||
| */ | ||||||||||||||
|
|
||||||||||||||
| import { getExecutor } from "../../executors/index.ts"; | ||||||||||||||
| import { getCachedSettings } from "@/lib/db/readCache"; | ||||||||||||||
| import { getUpstreamProxyConfigCached } from "./comboContextCache.ts"; | ||||||||||||||
|
|
||||||||||||||
| type LoggerLike = | ||||||||||||||
| | { | ||||||||||||||
| info?: (...args: unknown[]) => void; | ||||||||||||||
| error?: (...args: unknown[]) => void; | ||||||||||||||
| warn?: (...args: unknown[]) => void; | ||||||||||||||
| } | ||||||||||||||
| | null | ||||||||||||||
| | undefined; | ||||||||||||||
|
|
||||||||||||||
| export async function resolveExecutorWithProxy(prov: string, log?: LoggerLike) { | ||||||||||||||
| const cfg = await getUpstreamProxyConfigCached(prov); | ||||||||||||||
| if (!cfg.enabled || cfg.mode === "native") return getExecutor(prov); | ||||||||||||||
|
|
||||||||||||||
| if (cfg.mode === "cliproxyapi") { | ||||||||||||||
| log?.info?.("UPSTREAM_PROXY", `${prov} routed through CLIProxyAPI (passthrough)`); | ||||||||||||||
| return getExecutor("cliproxyapi"); | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| // mode === "fallback": try native first, retry via CLIProxyAPI on specific failures | ||||||||||||||
| const nativeExec = getExecutor(prov); | ||||||||||||||
| const proxyExec = getExecutor("cliproxyapi"); | ||||||||||||||
|
|
||||||||||||||
| // Read custom fallback codes from settings. Default: 5xx + 429 + network errors. | ||||||||||||||
| let fallbackCodes: number[] = [429, 500, 502, 503, 504]; | ||||||||||||||
| try { | ||||||||||||||
| const allSettings = await getCachedSettings(); | ||||||||||||||
| if ( | ||||||||||||||
| typeof allSettings.cliproxyapi_fallback_codes === "string" && | ||||||||||||||
| allSettings.cliproxyapi_fallback_codes.trim() | ||||||||||||||
| ) { | ||||||||||||||
| const parsed = allSettings.cliproxyapi_fallback_codes | ||||||||||||||
| .split(",") | ||||||||||||||
| .map((s: string) => Number.parseInt(s.trim(), 10)) | ||||||||||||||
| .filter((n: number) => !Number.isNaN(n)); | ||||||||||||||
| if (parsed.length > 0) fallbackCodes = parsed; | ||||||||||||||
| } | ||||||||||||||
| } catch { | ||||||||||||||
| /* use defaults */ | ||||||||||||||
| } | ||||||||||||||
| const isRetryableStatus = (s: number) => fallbackCodes.includes(s) || s === 0; | ||||||||||||||
|
|
||||||||||||||
| const wrapper = Object.create(nativeExec); | ||||||||||||||
| wrapper.execute = async (input: { | ||||||||||||||
| model: string; | ||||||||||||||
| body: unknown; | ||||||||||||||
| stream: boolean; | ||||||||||||||
| credentials: unknown; | ||||||||||||||
| signal?: AbortSignal | null; | ||||||||||||||
| log?: unknown; | ||||||||||||||
| upstreamExtraHeaders?: Record<string, string> | null; | ||||||||||||||
| }) => { | ||||||||||||||
| let result; | ||||||||||||||
| try { | ||||||||||||||
| result = await nativeExec.execute(input); | ||||||||||||||
| } catch (err) { | ||||||||||||||
| const errMsg = err instanceof Error ? err.message : String(err); | ||||||||||||||
| log?.info?.("UPSTREAM_PROXY", `${prov} native error (${errMsg}), retrying via CLIProxyAPI`); | ||||||||||||||
| try { | ||||||||||||||
| return await proxyExec.execute(input); | ||||||||||||||
| } catch (proxyErr) { | ||||||||||||||
| const proxyMsg = proxyErr instanceof Error ? proxyErr.message : String(proxyErr); | ||||||||||||||
| log?.error?.("UPSTREAM_PROXY", `${prov} CLIProxyAPI fallback also failed: ${proxyMsg}`); | ||||||||||||||
| throw proxyErr; | ||||||||||||||
| } | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| if (!isRetryableStatus(result.response.status)) { | ||||||||||||||
| return result; | ||||||||||||||
| } | ||||||||||||||
|
Comment on lines
+82
to
+84
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To prevent potential runtime
Suggested change
|
||||||||||||||
| log?.info?.( | ||||||||||||||
| "UPSTREAM_PROXY", | ||||||||||||||
| `${prov} native failed (${result.response.status}), retrying via CLIProxyAPI` | ||||||||||||||
| ); | ||||||||||||||
| try { | ||||||||||||||
| return await proxyExec.execute(input); | ||||||||||||||
| } catch (proxyErr) { | ||||||||||||||
| const proxyMsg = proxyErr instanceof Error ? proxyErr.message : String(proxyErr); | ||||||||||||||
| log?.error?.("UPSTREAM_PROXY", `${prov} CLIProxyAPI fallback also failed: ${proxyMsg}`); | ||||||||||||||
| throw proxyErr; | ||||||||||||||
| } | ||||||||||||||
| }; | ||||||||||||||
| return wrapper; | ||||||||||||||
| } | ||||||||||||||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current type signature for
inputis incomplete and hardcodes only a subset of the properties actually passed at runtime (missingcontextEditing,clientHeaders,extendedContext, etc.). To ensure complete type safety and prevent this from going out of sync when new parameters are added to executors, dynamically derive the parameter type from the executor'sexecutemethod.