Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/server/responses/core-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ export interface HandleResponsesOptions {
callerDirectAuth?: CallerDirectAuth | null;
/** Internal recursion guard; callers outside this module must not set it. */
comboAttempt?: boolean;
/** Internal handoff: this combo was selected by shadow-call interception. */
shadowCallIntercepted?: boolean;
compactionRoutingOverride?: CompactionRoutingOverride | null;
/** Internal combo handoff for one parent-validated continuation snapshot. */
comboReplaySnapshot?: {
Expand Down
85 changes: 51 additions & 34 deletions src/server/responses/passthrough-delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,36 +380,62 @@ export async function deliverPassthroughResponse(
});
// Capture the binding that actually served the first leg, after its permitted reselection.
const webSearchBridgeBinding = requestBindings.get(nativeExchange.request);
// The bridge wraps the RAW upstream body, so terminal repair below still owns the single
// client-facing terminal — the bridge drops the terminal of every intercepted leg.
const upstreamSseBody = webSearchBridgePlan
// Repair must observe the raw first leg before the bridge suppresses an intercepted search
// lifecycle. Otherwise a provider that leaves that complete call open never arms repair's
// grace timer, so the bridge cannot execute the search or begin its continuation.
let passthroughSseBody = terminalRepairPolicy
? relayResponsesSseWithTerminalRepair(
upstreamResponse.body,
upstream,
terminalRepairPolicy,
translatorBudget,
options.responsesTerminalRepairScheduler,
)
: upstreamResponse.body;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
passthroughSseBody = webSearchBridgePlan
? createPassthroughWebSearchBridgeStream({
plan: webSearchBridgePlan,
firstLeg: upstreamResponse.body,
firstLeg: passthroughSseBody,
requestBody: nativeExchange.request.body,
// Continuation legs replay the same built request with the executed search appended.
// The first leg already passed the recovery ladder, the outbound size ceiling, and the
// host circuit; a KEY-auth destination has no OAuth refresh to replay on a later leg.
send: (continuationBody: string) => fetchWithHeaderTimeout(
nativeExchange.request.url,
{ method: nativeExchange.request.method, headers: nativeExchange.request.headers, body: continuationBody },
upstream.signal,
connectMs,
true,
providerFetch(route.provider, options.codexWsRuntimeIdentity, {
// Pacing can outlive a manual selection change. A continuation must retain the
// first leg's key and appended search result, never rebuild from the original turn.
beforeDispatch: () => {
if (webSearchBridgeBinding?.kind !== "api-key"
|| !providerApiKeySelectionIsCurrent(config, route.providerName, webSearchBridgeBinding.provider)) {
throw new Error("API key selection changed during a web-search continuation");
}
},
providerName: route.providerName,
modelId: route.modelId,
}),
false,
),
send: async (continuationBody: string) => {
const continuation = await fetchWithHeaderTimeout(
nativeExchange.request.url,
{ method: nativeExchange.request.method, headers: nativeExchange.request.headers, body: continuationBody },
upstream.signal,
connectMs,
true,
providerFetch(route.provider, options.codexWsRuntimeIdentity, {
// Pacing can outlive a manual selection change. A continuation must retain the
// first leg's key and appended search result, never rebuild from the original turn.
beforeDispatch: () => {
if (webSearchBridgeBinding?.kind !== "api-key"
|| !providerApiKeySelectionIsCurrent(config, route.providerName, webSearchBridgeBinding.provider)) {
throw new Error("API key selection changed during a web-search continuation");
}
},
providerName: route.providerName,
modelId: route.modelId,
}),
false,
);
// The same provider can leave a complete continuation open without a terminal, which
// stalls the bridge's decide loop exactly like the first leg — so every leg gets the
// same repair, not only the intercepted first one.
if (!terminalRepairPolicy || !continuation.ok || !continuation.body) return continuation;
return new Response(
relayResponsesSseWithTerminalRepair(
continuation.body,
upstream,
terminalRepairPolicy,
translatorBudget,
options.responsesTerminalRepairScheduler,
),
continuation,
);
},
execute: createPassthroughWebSearchBridgeExecutor(webSearchBridgePlan, {
providerApiKey: route.provider.apiKey ?? "",
auth: webSearchBridgeAuth,
Expand All @@ -433,16 +459,7 @@ export async function deliverPassthroughResponse(
onFinalize: () => releaseCodexAuthContextProbeLease(openAiSidecar?.authContext),
signal: upstream.signal,
})
: upstreamResponse.body;
const passthroughSseBody = terminalRepairPolicy
? relayResponsesSseWithTerminalRepair(
upstreamSseBody,
upstream,
terminalRepairPolicy,
translatorBudget,
options.responsesTerminalRepairScheduler,
)
: upstreamSseBody;
: passthroughSseBody;
const repairConfig = route.provider.responsesItemIdRepair;
// Grok Build renders deltas live but reconstructs its durable assistant
// turn from the completed response snapshot. Native Responses streams
Expand Down
27 changes: 20 additions & 7 deletions src/server/responses/request-prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,20 +225,29 @@ export async function prepareResponsesRequest(
// hops — which only exist inside that loop — are unreachable (#4129). Rewrite the selector
// here instead, before comboIdFromRawBody reads `model`, and identify the combo by CONFIG
// LOOKUP so the check can never observe a one-candidate collapse.
let shadowCallIntercepted = false;
if (!options.comboAttempt && !options.compactionRoutingOverride && body && typeof body === "object" && !Array.isArray(body)) {
const shadowIntercept = config.shadowCallIntercept;
const rawShadowModel = (body as { model?: unknown }).model;
if (shadowIntercept?.enabled && shadowIntercept.model && typeof rawShadowModel === "string"
&& isShadowSourceModel(rawShadowModel, shadowIntercept.sourceModels)) {
const shadowComboId = resolveComboId(config, shadowIntercept.model);
if (shadowComboId && Object.hasOwn(config.combos ?? {}, shadowComboId)) {
(body as Record<string, unknown>).model = shadowIntercept.model;
// Same rule as the late intercept site: record the operator-configured prefix that
// matched, never the caller's raw model string. Matching is by prefix, so the raw
// value is caller-controlled and reaches usage.jsonl and /api/logs.
logCtx.shadowCallRewrittenFrom = sanitizeLogMetadataString(
shadowSourceModelPrefix(rawShadowModel, shadowIntercept.sourceModels),
);
const sourcePrefix = shadowSourceModelPrefix(rawShadowModel, shadowIntercept.sourceModels)!;
let sourceIdentity = { providerName: OPENAI_CODEX_PROVIDER_ID, modelId: sourcePrefix };
try {
const resolvedSource = routeConcreteModel(config, rawShadowModel);
sourceIdentity = { providerName: resolvedSource.providerName, modelId: sourcePrefix };
} catch { /* Native Codex helper calls remain OpenAI-owned without an enabled OpenAI route. */ }
const targetRoute = routeModel(config, shadowIntercept.model, evidenceFromBody(body));
if (shouldInterceptShadowCall(rawShadowModel, shadowIntercept.sourceModels, sourceIdentity, targetRoute)) {
shadowCallIntercepted = true;
(body as Record<string, unknown>).model = shadowIntercept.model;
// Same rule as the late intercept site: record the operator-configured prefix that
// matched, never the caller's raw model string. Matching is by prefix, so the raw
// value is caller-controlled and reaches usage.jsonl and /api/logs.
logCtx.shadowCallRewrittenFrom = sanitizeLogMetadataString(sourcePrefix);
}
}
}
}
Expand All @@ -247,6 +256,9 @@ export async function prepareResponsesRequest(
options.onRequestBodyRead?.();
return requestDispatchers.handleComboResponses(req, body, comboId, config, logCtx, {
...options,
// Concrete combo child selectors no longer match the shadow source model. Carry the
// interception decision explicitly so provider-specific helper isolation still applies.
shadowCallIntercepted,
// The original request body was accepted above. Combo children are synthetic
// replays and must not repeat the caller-owned timeout transition.
onRequestBodyRead: undefined,
Expand Down Expand Up @@ -369,6 +381,7 @@ export async function prepareResponsesRequest(
}
}
if (cursorClientThreadId) parsed._cursorClientThreadId = cursorClientThreadId;
if (options.shadowCallIntercepted === true) parsed._cursorIsolateConversation = true;
} catch (err) {
if (isTranslatorBudgetExceededError(err)) {
return formatErrorResponse(413, "request_too_large", "request translation buffer exceeded the safe limit", {
Expand Down
Loading
Loading