@bitkyc08/opencodex 2.95.0 → 2.96.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/gui/dist/assets/{App-8yedBkhm.js → App-bwugJRKn.js} +18 -18
- package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-BOPQyDbH.js} +1 -1
- package/gui/dist/assets/{index-D7DCm5eQ.js → index-ebuVUtB7.js} +2 -2
- package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-6HsrHQAy.js} +1 -1
- package/gui/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/adapters/ollama-native.ts +10 -6
- package/src/adapters/openai-responses/canonical-forward.ts +50 -13
- package/src/adapters/openai-responses/passthrough.ts +3 -4
- package/src/adapters/openai-responses/transport.ts +17 -26
- package/src/adapters/qoder/adapter.ts +1 -1
- package/src/adapters/qoder/image-input.ts +5 -2
- package/src/cli/agent.ts +44 -15
- package/src/cli/capabilities-agents-routing.ts +9 -0
- package/src/cli/ensure-desired-integrations.ts +4 -3
- package/src/cli/index.ts +4 -1
- package/src/cli/message-command.ts +2 -1
- package/src/cli/message-mcp-command.ts +29 -0
- package/src/cli/registry.ts +1 -1
- package/src/codex/account-store.ts +1 -0
- package/src/codex/auth-context-provider.ts +15 -0
- package/src/codex/auth-context.ts +10 -19
- package/src/codex/forward-transport-headers.ts +33 -33
- package/src/codex/installation-id.ts +72 -0
- package/src/generated/compatibility-version.json +83 -47
- package/src/grok/sync.ts +10 -1
- package/src/lib/windows-secret-acl.ts +2 -2
- package/src/messaging/mcp-queue-rpc.ts +102 -0
- package/src/messaging/mcp-queue-server.ts +42 -0
- package/src/messaging/mcp-queue-tools.ts +39 -0
- package/src/oauth/anthropic-identity.ts +2 -6
- package/src/oauth/index.ts +5 -0
- package/src/providers/anthropic-subscription.ts +25 -0
- package/src/providers/claude-cli-usage.ts +15 -67
- package/src/providers/quota/anthropic-decision-windows.ts +5 -19
- package/src/providers/quota/anthropic-usage-windows.ts +55 -0
- package/src/responses/parser-tools.ts +1 -0
- package/src/responses/schema.ts +5 -2
- package/src/server/audio-dictation.ts +3 -0
- package/src/server/audio-live.ts +8 -2
- package/src/server/audio-upstream.ts +2 -0
- package/src/server/claude-messages.ts +6 -3
- package/src/server/context-history.ts +9 -6
- package/src/server/images.ts +14 -5
- package/src/server/index/live-sideband.ts +16 -2
- package/src/server/index/serve-options.ts +1 -0
- package/src/server/index/websocket-handler.ts +1 -1
- package/src/server/live.ts +30 -5
- package/src/server/responses/adapter-dispatch.ts +5 -0
- package/src/server/responses/codex-auth-error.ts +4 -0
- package/src/server/responses/combo-required-tool-contract.ts +24 -12
- package/src/server/responses/compact.ts +37 -19
- package/src/server/responses/core-codex-account.ts +17 -6
- package/src/server/responses/core-combo.ts +12 -8
- package/src/server/responses/core-normalize.ts +7 -1
- package/src/server/responses/passthrough-build-error.ts +36 -0
- package/src/server/responses/passthrough-dispatch.ts +7 -22
- package/src/server/responses/request-sidecar-auth.ts +3 -1
- package/src/server/search.ts +13 -4
- package/src/server/ws-bridge.ts +5 -2
- package/src/vision/describe.ts +4 -7
- package/src/web-search/executor.ts +4 -7
package/src/server/live.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
|
|
2
|
+
import { isolateCodexPoolClientMetadata, mergeCodexSelectedHeaders } from "../codex/forward-transport-headers";
|
|
1
3
|
import { codexCompatibleUrl } from "../codex/context-compat";
|
|
2
4
|
/**
|
|
3
5
|
* /v1/live and /v1/realtime/calls relay (issue #371).
|
|
@@ -38,6 +40,7 @@ import {
|
|
|
38
40
|
CodexModelAvailabilityError,
|
|
39
41
|
CodexPoolAuthenticationError,
|
|
40
42
|
CodexThreadAffinityExpiredError,
|
|
43
|
+
type CodexAuthContext,
|
|
41
44
|
} from "../codex/auth-context";
|
|
42
45
|
import { formatCodexProviderForLog } from "../codex/routing";
|
|
43
46
|
import { cancelBodyOnAbort, signalWithTimeout } from "../lib/abort";
|
|
@@ -315,10 +318,12 @@ export type LiveSidebandTarget =
|
|
|
315
318
|
|
|
316
319
|
export type LiveRelayTarget = {
|
|
317
320
|
headers: Record<string, string>;
|
|
321
|
+
authContext?: CodexAuthContext;
|
|
318
322
|
providerBaseUrl: string;
|
|
319
323
|
usesBackendShape: boolean;
|
|
320
324
|
keyed: boolean;
|
|
321
325
|
recordOutcome?: (status: number | "timeout" | "connect_error") => void;
|
|
326
|
+
releaseProbeLease?: () => void;
|
|
322
327
|
};
|
|
323
328
|
|
|
324
329
|
function isChatGptBackendBaseUrl(baseUrl: string): boolean {
|
|
@@ -723,7 +728,9 @@ export async function resolveLiveRelay(
|
|
|
723
728
|
);
|
|
724
729
|
}
|
|
725
730
|
} catch (err) {
|
|
726
|
-
if (err instanceof
|
|
731
|
+
if (err instanceof CodexInstallationIdUnavailableError) {
|
|
732
|
+
forwardAuthError = formatErrorResponse(503, "server_busy", err.message);
|
|
733
|
+
} else if (err instanceof CodexAccountCooldownError) {
|
|
727
734
|
forwardAuthError = cooldownErrorResponse(err);
|
|
728
735
|
} else if (err instanceof CodexMainProfileDrainingError) {
|
|
729
736
|
forwardAuthError = codexMainProfileDrainingResponse();
|
|
@@ -769,11 +776,12 @@ export async function resolveLiveRelay(
|
|
|
769
776
|
forward.releaseProbeLease?.();
|
|
770
777
|
return denial;
|
|
771
778
|
}
|
|
772
|
-
|
|
773
|
-
for (const [name, value] of forward.headers) headers[name] = value;
|
|
779
|
+
const selectedHeaders = mergeCodexSelectedHeaders({ ...headers, ...provider.headers }, forward.headers);
|
|
774
780
|
logCtx.model = "gpt-live";
|
|
775
781
|
return {
|
|
776
|
-
headers,
|
|
782
|
+
headers: Object.fromEntries(selectedHeaders),
|
|
783
|
+
authContext: forward.authContext,
|
|
784
|
+
releaseProbeLease: forward.releaseProbeLease,
|
|
777
785
|
providerBaseUrl: provider.baseUrl,
|
|
778
786
|
usesBackendShape: isChatGptBackendBaseUrl(provider.baseUrl),
|
|
779
787
|
keyed: false,
|
|
@@ -855,6 +863,18 @@ export async function handleLive(
|
|
|
855
863
|
const linkedSignal = signalWithTimeout(LIVE_UPSTREAM_TIMEOUT_MS, req.signal);
|
|
856
864
|
const sidecarExit = sidecarEnter("live");
|
|
857
865
|
try {
|
|
866
|
+
if (relay.authContext?.kind === "pool") {
|
|
867
|
+
let parsed: unknown;
|
|
868
|
+
try { parsed = JSON.parse(new TextDecoder().decode(outboundBody)); } catch { /* Upstream owns invalid JSON. */ }
|
|
869
|
+
const accountId = relay.authContext.chatgptAccountId;
|
|
870
|
+
let isolated = isolateCodexPoolClientMetadata(parsed, accountId);
|
|
871
|
+
if (isolated && typeof isolated === "object" && !Array.isArray(isolated)) {
|
|
872
|
+
const record = isolated as Record<string, unknown>;
|
|
873
|
+
const session = isolateCodexPoolClientMetadata(record.session, accountId);
|
|
874
|
+
if (session !== record.session) isolated = { ...record, session };
|
|
875
|
+
}
|
|
876
|
+
if (isolated !== parsed) outboundBody = new TextEncoder().encode(JSON.stringify(isolated)).buffer as ArrayBuffer;
|
|
877
|
+
}
|
|
858
878
|
const upstreamResponse = await fetch(url, {
|
|
859
879
|
method: "POST",
|
|
860
880
|
headers,
|
|
@@ -901,6 +921,10 @@ export async function handleLive(
|
|
|
901
921
|
if (req.signal.aborted) {
|
|
902
922
|
return formatErrorResponse(499, "client_closed_request", "live request canceled by client");
|
|
903
923
|
}
|
|
924
|
+
if (err instanceof CodexInstallationIdUnavailableError) {
|
|
925
|
+
relay.releaseProbeLease?.();
|
|
926
|
+
return formatErrorResponse(503, "server_busy", err.message);
|
|
927
|
+
}
|
|
904
928
|
if (err instanceof Error && err.name === "TimeoutError") {
|
|
905
929
|
relay.recordOutcome?.("timeout");
|
|
906
930
|
return formatErrorResponse(504, "upstream_error", "live upstream timed out");
|
|
@@ -925,7 +949,7 @@ export async function resolveLiveSidebandUpgrade(
|
|
|
925
949
|
target: LiveSidebandTarget,
|
|
926
950
|
turnAdmissionLease?: AdmissionLease,
|
|
927
951
|
admission?: DataPlaneAdmission,
|
|
928
|
-
): Promise<{ headers: Record<string, string>; upstreamWsUrl: string; recordOutcome?: LiveRelayTarget["recordOutcome"] } | Response> {
|
|
952
|
+
): Promise<{ headers: Record<string, string>; upstreamWsUrl: string; authContext?: CodexAuthContext; recordOutcome?: LiveRelayTarget["recordOutcome"] } | Response> {
|
|
929
953
|
const relay = await resolveLiveRelay(req, config, logCtx, turnAdmissionLease, {
|
|
930
954
|
admission,
|
|
931
955
|
model: liveSidebandModel(target),
|
|
@@ -933,6 +957,7 @@ export async function resolveLiveSidebandUpgrade(
|
|
|
933
957
|
});
|
|
934
958
|
if (relay instanceof Response) return relay;
|
|
935
959
|
return {
|
|
960
|
+
authContext: relay.authContext,
|
|
936
961
|
headers: relay.headers,
|
|
937
962
|
upstreamWsUrl: buildLiveSidebandUpstreamWsUrl(target, config.experimentalRealtimeWsBaseUrl),
|
|
938
963
|
recordOutcome: relay.recordOutcome,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { codexAdapterBuildRefusal } from "./passthrough-build-error";
|
|
1
2
|
import { recoverAutoPausedAccount } from "./account-auto-pause-recovery";
|
|
2
3
|
import { wasAccountAutoPaused, wasPermanentAccountRefusal } from "../../oauth/account-auto-pause";
|
|
3
4
|
import { bindAnthropicRejectionResponse } from "../../adapters/anthropic-rejection-memo";
|
|
@@ -364,6 +365,8 @@ export async function prepareAdapterExchange(
|
|
|
364
365
|
code: "translation_buffer_limit",
|
|
365
366
|
});
|
|
366
367
|
}
|
|
368
|
+
const authRefusal = codexAdapterBuildRefusal(err, admissionState.authCtx, route.codexAccountNamespace);
|
|
369
|
+
if (authRefusal) return authRefusal;
|
|
367
370
|
const msg = err instanceof Error ? err.message : String(err);
|
|
368
371
|
return formatErrorResponse(400, "invalid_request_error", redactSecretString(msg));
|
|
369
372
|
}
|
|
@@ -662,6 +665,8 @@ export async function prepareAdapterExchange(
|
|
|
662
665
|
recordAdapterReasoning(logCtx, retryRequest);
|
|
663
666
|
recordAdapterTier(logCtx, retryRequest);
|
|
664
667
|
} catch (err) {
|
|
668
|
+
const authRefusal = options.abortSignal?.aborted ? undefined : codexAdapterBuildRefusal(err, admissionState.authCtx, route.codexAccountNamespace, () => { cleanupUpstreamAbort(); upstream.abort(); });
|
|
669
|
+
if (authRefusal) return { failed: authRefusal };
|
|
665
670
|
// A rotated credential that cannot be shaped keeps the refusal it was meant to
|
|
666
671
|
// replace. The image-tier rebuild is different: the request itself failed to shape,
|
|
667
672
|
// and its established 413/400 build-error contract stays authoritative.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../../codex/installation-id";
|
|
1
2
|
import { formatErrorResponse } from "../../bridge";
|
|
2
3
|
import {
|
|
3
4
|
CodexAccountCooldownError,
|
|
@@ -78,6 +79,9 @@ export function mapCodexAuthContextErrorToResponse(
|
|
|
78
79
|
error: unknown,
|
|
79
80
|
options: CodexAuthContextErrorResponseOptions,
|
|
80
81
|
): Response | undefined {
|
|
82
|
+
if (error instanceof CodexInstallationIdUnavailableError) {
|
|
83
|
+
return formatErrorResponse(503, "server_busy", error.message);
|
|
84
|
+
}
|
|
81
85
|
if (error instanceof CodexAccountCooldownError) {
|
|
82
86
|
const response = cooldownErrorResponse(error, options.now, options.accountSelector);
|
|
83
87
|
// Exact class only (#7850): main hard-lock, credit, Reserve, recovery-withheld and future
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { REQUIRED_TOOL_CONTRACT_CODE } from "../../lib/errors";
|
|
2
|
+
import { mapToolChoice } from "../../responses/parser-tools";
|
|
3
|
+
import { modelInList, type OcxProviderConfig } from "../../types";
|
|
2
4
|
import { hasResponseMediaType } from "../../lib/http-response-semantics";
|
|
3
5
|
import { applyReplayRefusalClientHeaders, isNonReplayableResponse, markResponseNonReplayable } from "../../lib/upstream-retry";
|
|
4
6
|
import { clientWireOf } from "../inference/client-wire";
|
|
@@ -15,6 +17,16 @@ const allowedHostedSelectors = new Set([
|
|
|
15
17
|
"code_interpreter", "image_generation", "image_gen", "tool_search",
|
|
16
18
|
]);
|
|
17
19
|
|
|
20
|
+
function knownToolSelector(value: unknown): boolean {
|
|
21
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
22
|
+
const entry = value as Record<string, unknown>;
|
|
23
|
+
if (entry.type === "mcp") return typeof entry.server_label === "string" && !!entry.server_label.trim()
|
|
24
|
+
&& (entry.name === undefined || entry.name === null || (typeof entry.name === "string" && !!entry.name.trim()));
|
|
25
|
+
if (entry.name !== undefined && (typeof entry.name !== "string" || !entry.name.trim())) return false;
|
|
26
|
+
if (entry.type === "function" || entry.type === "custom") return typeof entry.name === "string";
|
|
27
|
+
return typeof entry.type === "string" && allowedHostedSelectors.has(entry.type);
|
|
28
|
+
}
|
|
29
|
+
|
|
18
30
|
/** Only definite, well-formed mandatory selectors justify excluding a destination. */
|
|
19
31
|
export function hasMandatoryToolChoice(rawBody: unknown): boolean {
|
|
20
32
|
if (!rawBody || typeof rawBody !== "object" || Array.isArray(rawBody)) return false;
|
|
@@ -22,19 +34,19 @@ export function hasMandatoryToolChoice(rawBody: unknown): boolean {
|
|
|
22
34
|
if (choice === "required") return true;
|
|
23
35
|
if (!choice || typeof choice !== "object" || Array.isArray(choice)) return false;
|
|
24
36
|
const selector = choice as Record<string, unknown>;
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return selector.type === "allowed_tools" && selector.mode === "required"
|
|
37
|
+
// Eligibility is broader than terminal inspection: hosted selectors retain their own terminal owner.
|
|
38
|
+
if (selector.type !== "allowed_tools") return knownToolSelector(selector);
|
|
39
|
+
return selector.mode === "required"
|
|
29
40
|
&& Array.isArray(selector.tools) && selector.tools.length > 0
|
|
30
|
-
&& selector.tools.every(
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
41
|
+
&& selector.tools.every(knownToolSelector);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A translated Chat target must not turn a mandatory selector into auto or none. */
|
|
45
|
+
export function chatCanPreserveMandatoryToolChoice(rawBody: unknown, provider: OcxProviderConfig, modelId: string): boolean {
|
|
46
|
+
if (!hasMandatoryToolChoice(rawBody)) return true;
|
|
47
|
+
if (modelInList(provider.autoToolChoiceOnlyModels, modelId)) return false;
|
|
48
|
+
const mapped = mapToolChoice((rawBody as Record<string, unknown>).tool_choice);
|
|
49
|
+
return mapped === "required" || (!!mapped && typeof mapped === "object");
|
|
38
50
|
}
|
|
39
51
|
|
|
40
52
|
const hostedCalls = new Map([
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../../codex/installation-id";
|
|
2
|
+
import { isolateCodexPoolClientMetadata } from "../../codex/forward-transport-headers";
|
|
1
3
|
import { captureAccountAutoPauseAttempt, wasAccountAutoPaused, wasPermanentAccountRefusal } from "../../oauth/account-auto-pause";
|
|
2
4
|
import { spendLedgerStorageErrorResponse } from "./spend-storage-error";
|
|
3
5
|
import { captureAdmissionPolicy } from "../capture-admission-policy";
|
|
@@ -393,7 +395,7 @@ async function refreshNativeMainCompactContext(args: {
|
|
|
393
395
|
});
|
|
394
396
|
for (const name of FORWARD_HEADERS) {
|
|
395
397
|
const value = selected.get(name);
|
|
396
|
-
if (value) headers.set(name, value);
|
|
398
|
+
if (value !== null) headers.set(name, value);
|
|
397
399
|
}
|
|
398
400
|
const override = (refreshedProvider as { _codexAccountOverride?: { accessToken: string; chatgptAccountId: string } })._codexAccountOverride;
|
|
399
401
|
if (override) {
|
|
@@ -488,7 +490,7 @@ async function refreshPoolCompactContext(args: {
|
|
|
488
490
|
});
|
|
489
491
|
for (const name of FORWARD_HEADERS) {
|
|
490
492
|
const value = selected.get(name);
|
|
491
|
-
if (value) headers.set(name, value);
|
|
493
|
+
if (value !== null) headers.set(name, value);
|
|
492
494
|
}
|
|
493
495
|
const override = (refreshedProvider as { _codexAccountOverride?: { accessToken: string; chatgptAccountId: string } })._codexAccountOverride;
|
|
494
496
|
if (override) {
|
|
@@ -541,11 +543,12 @@ async function resolveAlternateCompactContext(args: {
|
|
|
541
543
|
excludeAccountId: string | null;
|
|
542
544
|
turnAdmissionLease?: AdmissionLease;
|
|
543
545
|
admission?: DataPlaneAdmission;
|
|
544
|
-
}): Promise<{ authCtx: CodexAuthContext; provider: OcxProviderConfig; headers: Headers } | null> {
|
|
546
|
+
}): Promise<{ authCtx: CodexAuthContext; provider: OcxProviderConfig; headers: Headers } | { failure: Response } | null> {
|
|
545
547
|
const { req, config, route, selectedModelId, excludeAccountId, turnAdmissionLease } = args;
|
|
546
548
|
if (!route.codexAccountMode || !excludeAccountId) return null;
|
|
549
|
+
let authCtx: CodexAuthContext | undefined;
|
|
547
550
|
try {
|
|
548
|
-
|
|
551
|
+
authCtx = await resolveCodexAuthContext(req.headers, config, route.codexAccountMode, {
|
|
549
552
|
admission: args.admission,
|
|
550
553
|
...(selectedModelId ? { modelId: selectedModelId } : {}),
|
|
551
554
|
excludeAccountId,
|
|
@@ -561,7 +564,7 @@ async function resolveAlternateCompactContext(args: {
|
|
|
561
564
|
const selected = headersForCodexAuthContext(req.headers, authCtx, config, selectedModelId, args.admission);
|
|
562
565
|
for (const name of FORWARD_HEADERS) {
|
|
563
566
|
const value = selected.get(name);
|
|
564
|
-
if (value) headers.set(name, value);
|
|
567
|
+
if (value !== null) headers.set(name, value);
|
|
565
568
|
}
|
|
566
569
|
const override = (provider as { _codexAccountOverride?: { accessToken: string; chatgptAccountId: string } })._codexAccountOverride;
|
|
567
570
|
if (override) {
|
|
@@ -571,6 +574,8 @@ async function resolveAlternateCompactContext(args: {
|
|
|
571
574
|
if (provider.apiKey) headers.set("authorization", `Bearer ${resolveProviderApiKey(provider.apiKey)}`);
|
|
572
575
|
return { authCtx, provider, headers };
|
|
573
576
|
} catch (err) {
|
|
577
|
+
releaseCodexAuthContextProbeLease(authCtx);
|
|
578
|
+
if (err instanceof CodexInstallationIdUnavailableError) return { failure: formatErrorResponse(503, "server_busy", err.message) };
|
|
574
579
|
if (err instanceof CodexMainProfileDrainingError) {
|
|
575
580
|
// The native-main fence can start after account A has already rejected the
|
|
576
581
|
// request. Treat the now-fenced main profile as no alternate and preserve A's
|
|
@@ -603,7 +608,7 @@ function compactResponseHeaders(upstream: Response): Headers {
|
|
|
603
608
|
const headers = new Headers({ "Content-Type": upstream.headers.get("content-type") ?? "application/json" });
|
|
604
609
|
for (const name of COMPACT_PASSTHROUGH_HEADERS) {
|
|
605
610
|
const value = upstream.headers.get(name);
|
|
606
|
-
if (value) headers.set(name, value);
|
|
611
|
+
if (value !== null) headers.set(name, value);
|
|
607
612
|
}
|
|
608
613
|
return headers;
|
|
609
614
|
}
|
|
@@ -907,7 +912,7 @@ export async function handleResponsesCompact(
|
|
|
907
912
|
compactProvider = applyCodexAuthContextToProvider(route.provider, authCtx, route.codexAccountMode);
|
|
908
913
|
for (const name of FORWARD_HEADERS) {
|
|
909
914
|
const value = selected.get(name);
|
|
910
|
-
if (value) headers.set(name, value);
|
|
915
|
+
if (value !== null) headers.set(name, value);
|
|
911
916
|
}
|
|
912
917
|
const override = (compactProvider as { _codexAccountOverride?: { accessToken: string; chatgptAccountId: string } })._codexAccountOverride;
|
|
913
918
|
if (override) {
|
|
@@ -1058,6 +1063,14 @@ export async function handleResponsesCompact(
|
|
|
1058
1063
|
compactHostAdmissionLease = null;
|
|
1059
1064
|
};
|
|
1060
1065
|
const connectMs = () => resolveConnectTimeoutMs(config.connectTimeoutMs, { localUpstream: isLocalUpstream(compactUrl) });
|
|
1066
|
+
const applyCompactPoolQuotaHeaders = async (ctx: CodexAuthContext, response: Response) => {
|
|
1067
|
+
if (ctx.kind !== "pool" && ctx.kind !== "main-pool") return;
|
|
1068
|
+
const { applyAccountQuotaFromUpstreamHeaders } = await import("../../codex/quota");
|
|
1069
|
+
applyAccountQuotaFromUpstreamHeaders(ctx.accountId, response.headers, ctx.writerGeneration,
|
|
1070
|
+
ctx.kind === "main-pool" ? ctx.mainQuotaWriter : undefined,
|
|
1071
|
+
{ modelId: route.modelId, poolWriter: ctx.kind === "pool" ? ctx.poolQuotaWriter : undefined,
|
|
1072
|
+
poolResponse: ctx.kind === "pool" });
|
|
1073
|
+
};
|
|
1061
1074
|
// Takes its context explicitly: the alternate-account flow below records a rejection
|
|
1062
1075
|
// against A while promoting B, then records B's own outcome. A closure over a single
|
|
1063
1076
|
// `authCtx` cannot express either.
|
|
@@ -1166,6 +1179,9 @@ export async function handleResponsesCompact(
|
|
|
1166
1179
|
if (!isOpenAiOperatedResponsesDestination(sendProvider) && sendProvider.preserveResponsesMessageMetadata !== true) {
|
|
1167
1180
|
replayBody = stripInternalChatMessageMetadataPassthrough(replayBody) as typeof replayBody;
|
|
1168
1181
|
}
|
|
1182
|
+
if (sendAuthCtx.kind === "pool" && isCanonicalOpenAiForwardProvider(sendProvider)) {
|
|
1183
|
+
replayBody = isolateCodexPoolClientMetadata(replayBody, sendAuthCtx.chatgptAccountId) as typeof replayBody;
|
|
1184
|
+
}
|
|
1169
1185
|
// A queued key selection can refresh the destination; project only for this send.
|
|
1170
1186
|
return isOpenAiOperatedResponsesDestination(sendProvider)
|
|
1171
1187
|
? repairUrlCitationAnnotations(replayBody) : stripCanonicalOnlyInputItems(stripCanonicalOnlyTopLevelFields(replayBody));
|
|
@@ -1469,6 +1485,12 @@ export async function handleResponsesCompact(
|
|
|
1469
1485
|
excludeAccountId: authCtx.accountId,
|
|
1470
1486
|
turnAdmissionLease,
|
|
1471
1487
|
});
|
|
1488
|
+
if (alternate && "failure" in alternate) {
|
|
1489
|
+
await applyCompactPoolQuotaHeaders(authCtx, upstream);
|
|
1490
|
+
recordCompactPoolOutcome(authCtx, upstream.status, { retryAfter: firstRetryAfter, resetAt: firstResetAt });
|
|
1491
|
+
await upstream.body?.cancel().catch(() => undefined);
|
|
1492
|
+
return alternate.failure;
|
|
1493
|
+
}
|
|
1472
1494
|
// Resolution can await a credential refresh, so the client may have gone away
|
|
1473
1495
|
// while we were choosing B. Re-check before spending anything: recording A,
|
|
1474
1496
|
// cancelling its body, and sending B are all observable side effects, and B's
|
|
@@ -1510,17 +1532,7 @@ export async function handleResponsesCompact(
|
|
|
1510
1532
|
// quota snapshot that produced it, so refresh A's cache before recording its
|
|
1511
1533
|
// rejection. Skipping this leaves quota-strategy routing and the dashboard
|
|
1512
1534
|
// reading numbers from before the account ran out.
|
|
1513
|
-
|
|
1514
|
-
const { applyAccountQuotaFromUpstreamHeaders } = await import("../../codex/auth-api");
|
|
1515
|
-
applyAccountQuotaFromUpstreamHeaders(
|
|
1516
|
-
authCtx.accountId,
|
|
1517
|
-
upstream.headers,
|
|
1518
|
-
authCtx.writerGeneration,
|
|
1519
|
-
authCtx.kind === "main-pool" ? authCtx.mainQuotaWriter : undefined,
|
|
1520
|
-
{ modelId: route.modelId, poolWriter: authCtx.kind === "pool" ? authCtx.poolQuotaWriter : undefined,
|
|
1521
|
-
poolResponse: authCtx.kind === "pool" },
|
|
1522
|
-
);
|
|
1523
|
-
}
|
|
1535
|
+
await applyCompactPoolQuotaHeaders(authCtx, upstream);
|
|
1524
1536
|
recordCompactPoolOutcome(authCtx, upstream.status, {
|
|
1525
1537
|
retryAfter: firstRetryAfter,
|
|
1526
1538
|
resetAt: firstResetAt,
|
|
@@ -1569,6 +1581,12 @@ export async function handleResponsesCompact(
|
|
|
1569
1581
|
excludeAccountId: authCtx.accountId,
|
|
1570
1582
|
turnAdmissionLease,
|
|
1571
1583
|
});
|
|
1584
|
+
if (alternate && "failure" in alternate) {
|
|
1585
|
+
await applyCompactPoolQuotaHeaders(authCtx, upstream);
|
|
1586
|
+
recordCompactPoolOutcome(authCtx, firstStatus, { retryAfter: firstRetryAfter, resetAt: firstResetAt });
|
|
1587
|
+
await upstream.body?.cancel().catch(() => undefined);
|
|
1588
|
+
return alternate.failure;
|
|
1589
|
+
}
|
|
1572
1590
|
if (alternate && req.signal.aborted) {
|
|
1573
1591
|
releaseCodexAuthContextProbeLease(alternate.authCtx);
|
|
1574
1592
|
recordCompactPoolOutcome(outcomeCtx, 499);
|
|
@@ -1728,7 +1746,7 @@ export async function handleResponsesCompact(
|
|
|
1728
1746
|
const internalHeaders = new Headers({ "content-type": "application/json" });
|
|
1729
1747
|
for (const name of FORWARD_HEADERS) {
|
|
1730
1748
|
const value = req.headers.get(name);
|
|
1731
|
-
if (value) internalHeaders.set(name, value);
|
|
1749
|
+
if (value || (value !== null && (name === "x-codex-installation-id" || name === "x-codex-turn-metadata"))) internalHeaders.set(name, value);
|
|
1732
1750
|
}
|
|
1733
1751
|
copyResponsesClientMetadata(internalHeaders, req.headers, route.provider);
|
|
1734
1752
|
const internalReq = new Request("http://localhost/v1/responses", {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../../codex/installation-id";
|
|
1
2
|
import { captureAccountAutoPauseAttempt, wasPermanentAccountRefusal } from "../../oauth/account-auto-pause";
|
|
2
3
|
import type { OcxConfig, OcxProviderConfig, OcxParsedRequest } from "../../types";
|
|
3
4
|
import type { CodexAuthContext, CodexAuthPolicyConfig } from "../../codex/auth-context";
|
|
@@ -886,7 +887,7 @@ export async function retryCodexPoolOnAlternateAccount(
|
|
|
886
887
|
retryHeaders = headersForCodexAuthContext(callerAuthHeaders, retryAuthCtx, options.codexAuthPolicy ?? config, route.modelId, options.admission);
|
|
887
888
|
retryProvider = applyCodexAuthContextToProvider(stripCodexRuntimeProviderFields(route.provider), retryAuthCtx, "pool");
|
|
888
889
|
} catch (error) {
|
|
889
|
-
if (!(error instanceof CodexPoolAccountCreditsOffError)) throw error;
|
|
890
|
+
if (!(error instanceof CodexPoolAccountCreditsOffError) && !(error instanceof CodexInstallationIdUnavailableError)) throw error;
|
|
890
891
|
// Body/entitlement reads above can outlive credit consent. No alternate will send:
|
|
891
892
|
// release its reservation and probes, then let the owner map the policy refusal.
|
|
892
893
|
accountMovePermit?.release();
|
|
@@ -929,11 +930,21 @@ export async function retryCodexPoolOnAlternateAccount(
|
|
|
929
930
|
});
|
|
930
931
|
}
|
|
931
932
|
}
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
933
|
+
let request;
|
|
934
|
+
try {
|
|
935
|
+
request = await retryAdapter.buildRequest(parsed, {
|
|
936
|
+
headers: retryHeaders,
|
|
937
|
+
providerName: route.providerName,
|
|
938
|
+
translatorBudget: options.translatorBudget,
|
|
939
|
+
});
|
|
940
|
+
} catch (error) {
|
|
941
|
+
if (!(error instanceof CodexInstallationIdUnavailableError)) throw error;
|
|
942
|
+
accountMovePermit?.release();
|
|
943
|
+
releaseCodexAuthContextProbeLease(firstAuthCtx);
|
|
944
|
+
releaseCodexAuthContextProbeLease(retryAuthCtx);
|
|
945
|
+
await firstResponse.body?.cancel().catch(() => undefined);
|
|
946
|
+
return { kind: "transport", error, authCtx: retryAuthCtx };
|
|
947
|
+
}
|
|
937
948
|
recordAdapterReasoning(logCtx, request);
|
|
938
949
|
recordAdapterTier(logCtx, request);
|
|
939
950
|
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { effectiveAzureOutputBudget } from "../../adapters/azure";
|
|
2
2
|
import { buildResponsesTransport } from "../../adapters/openai-responses/transport";
|
|
3
3
|
import { isMetaAiResponsesDestination } from "../../responses/muse-tool-name-alias";
|
|
4
|
-
import { hasMandatoryToolChoice } from "./combo-required-tool-contract";
|
|
4
|
+
import { chatCanPreserveMandatoryToolChoice, hasMandatoryToolChoice } from "./combo-required-tool-contract";
|
|
5
5
|
import { isCodexAccountCooldownResponse } from "../../codex/account-cooldown-response";
|
|
6
6
|
import { resolveWireProtocolOverride } from "../adapter-resolve";
|
|
7
|
+
import { parseSyntheticRowId } from "../fast-row";
|
|
8
|
+
import { resolveOpenAiVirtualModel } from "../../providers/openai-virtual-models";
|
|
7
9
|
import { comboCooldownRetryAfterSeconds, isDefiniteContextOverflow, type CodexAccountModelRefusal } from "../../combos/failover";
|
|
8
10
|
import { fallbackTriggerForStatus, guardFallbackHop } from "../../routing/fallback-policy";
|
|
9
11
|
import {
|
|
@@ -539,13 +541,15 @@ export async function executeComboResponses(
|
|
|
539
541
|
const museToolEligible = (target: (typeof combo.targets)[number]): boolean => {
|
|
540
542
|
if (!hasMandatoryToolChoice(body)) return true;
|
|
541
543
|
try {
|
|
542
|
-
const
|
|
544
|
+
const selector = `${target.provider}/${target.model}`, { fastRow, effortRow } = parseSyntheticRowId(selector, config);
|
|
545
|
+
const route = routeConcreteModel(config, fastRow?.baseId ?? effortRow?.baseId ?? selector);
|
|
546
|
+
const modelId = resolveOpenAiVirtualModel(route.providerName, route.modelId)?.wireModelId ?? route.modelId;
|
|
543
547
|
const inboundWire = options.inboundWire ?? "responses";
|
|
544
|
-
const policy = captureRouteStaticPolicy(route.providerName,
|
|
548
|
+
const policy = captureRouteStaticPolicy(route.providerName, modelId, route.provider,
|
|
545
549
|
route.staticPolicy.effectiveAlias, inboundWire);
|
|
546
|
-
const provider = resolveWireProtocolOverride(route.providerName,
|
|
547
|
-
return provider.adapter
|
|
548
|
-
|| !isMetaAiResponsesDestination(buildResponsesTransport(provider, { headers: req.headers }).url);
|
|
550
|
+
const provider = resolveWireProtocolOverride(route.providerName, modelId, route.provider, inboundWire, policy);
|
|
551
|
+
return provider.adapter === "openai-chat" ? chatCanPreserveMandatoryToolChoice(body, provider, modelId)
|
|
552
|
+
: provider.adapter !== "openai-responses" || !isMetaAiResponsesDestination(buildResponsesTransport(provider, { headers: req.headers }).url);
|
|
549
553
|
} catch {
|
|
550
554
|
return true;
|
|
551
555
|
}
|
|
@@ -674,7 +678,7 @@ export async function executeComboResponses(
|
|
|
674
678
|
{ parentThreadId: inboundClientThreadId },
|
|
675
679
|
);
|
|
676
680
|
if (!options.abortSignal?.aborted && onlyMuseToolIncompatible()) {
|
|
677
|
-
return comboUnavailableResponse(`No available targets for combo: ${comboId};
|
|
681
|
+
return comboUnavailableResponse(`No available targets for combo: ${comboId}; targets cannot preserve mandatory tool_choice`);
|
|
678
682
|
}
|
|
679
683
|
return options.abortSignal?.aborted
|
|
680
684
|
? clientCancelledResponse()
|
|
@@ -694,7 +698,7 @@ export async function executeComboResponses(
|
|
|
694
698
|
if (protocolRefusal) return protocolRefusal;
|
|
695
699
|
if (onlyReplayIncompatibleTargetsRemain()) return targetIncompatibleResponse();
|
|
696
700
|
if (!options.abortSignal?.aborted && onlyMuseToolIncompatible()) {
|
|
697
|
-
return comboUnavailableResponse(`No available targets for combo: ${comboId};
|
|
701
|
+
return comboUnavailableResponse(`No available targets for combo: ${comboId}; targets cannot preserve mandatory tool_choice`);
|
|
698
702
|
}
|
|
699
703
|
return options.abortSignal?.aborted
|
|
700
704
|
? clientCancelledResponse()
|
|
@@ -346,11 +346,17 @@ export async function applyFinalRouteRequestNormalization(args: {
|
|
|
346
346
|
// Native passthrough keeps its snapshot-owned effort contract, including saved exclusions.
|
|
347
347
|
if (!shouldApplyNativeEffortClamp(route.providerName, route.provider, finalSelectedModelId)) {
|
|
348
348
|
const previousEffort = parsed.options.reasoning;
|
|
349
|
+
const previousThinkingEnabled = parsed.options.thinkingEnabled;
|
|
349
350
|
normalizeThinkingOptions(route.provider, route.modelId, parsed.options);
|
|
351
|
+
const raw = parsed._rawBody as { reasoning?: unknown } | undefined;
|
|
350
352
|
if (previousEffort !== undefined && parsed.options.reasoning === undefined) {
|
|
351
|
-
const raw = parsed._rawBody as { reasoning?: unknown } | undefined;
|
|
352
353
|
if (raw) raw.reasoning = stripEmptyLadderEffort(raw.reasoning, []);
|
|
353
354
|
}
|
|
355
|
+
if (previousThinkingEnabled !== undefined && parsed.options.thinkingEnabled === undefined
|
|
356
|
+
&& raw?.reasoning && typeof raw.reasoning === "object" && !Array.isArray(raw.reasoning)) {
|
|
357
|
+
delete (raw.reasoning as { enabled?: boolean }).enabled;
|
|
358
|
+
if (Object.keys(raw.reasoning).length === 0) delete raw.reasoning;
|
|
359
|
+
}
|
|
354
360
|
}
|
|
355
361
|
const { applyEffortCap, effortCapAppliesTo, supportedLadderFor } = await import("../effort-policy");
|
|
356
362
|
const surface = collabSurface(parsed);
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { releaseCodexAuthContextProbeLease, type CodexAuthContext } from "../../codex/auth-context";
|
|
2
|
+
import { formatErrorResponse } from "../../bridge";
|
|
3
|
+
import { redactSecretString } from "../../lib/redact";
|
|
4
|
+
import { NamespaceToolCollisionError } from "../../responses/namespace-tool-compat";
|
|
5
|
+
import { RoutedCustomToolCompatError } from "../../responses/custom-tool-compat";
|
|
6
|
+
import { XaiToolSchemaCompatibilityError } from "../../adapters/xai-tool-schema";
|
|
7
|
+
import { MuseToolChoiceCompatibilityError } from "../../adapters/openai-responses/muse-tool-choice";
|
|
8
|
+
import { MuseToolCatalogCompatibilityError } from "../../adapters/openai-responses/muse-tool-catalog";
|
|
9
|
+
import { OpenGatewayInputCompatibilityError } from "../../adapters/openai-responses/opengateway-input";
|
|
10
|
+
import { mapCodexAuthContextErrorToResponse } from "./codex-auth-error";
|
|
11
|
+
|
|
12
|
+
/** Input-lowering errors are 400; late credential/identity failures retain their own contract. */
|
|
13
|
+
export function passthroughBuildErrorResponse(error: unknown, accountSelector?: string): Response | undefined {
|
|
14
|
+
const refusal = mapCodexAuthContextErrorToResponse(error, { now: Date.now(), accountSelector });
|
|
15
|
+
if (refusal) return refusal;
|
|
16
|
+
if (error instanceof NamespaceToolCollisionError
|
|
17
|
+
|| error instanceof XaiToolSchemaCompatibilityError
|
|
18
|
+
|| error instanceof RoutedCustomToolCompatError
|
|
19
|
+
|| error instanceof MuseToolChoiceCompatibilityError
|
|
20
|
+
|| error instanceof MuseToolCatalogCompatibilityError
|
|
21
|
+
|| error instanceof OpenGatewayInputCompatibilityError) {
|
|
22
|
+
return formatErrorResponse(400, "invalid_request_error", redactSecretString(error.message));
|
|
23
|
+
}
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Auth failures precede generic adapter-build 400s and preservation of an older rejection. */
|
|
28
|
+
export function codexAdapterBuildRefusal(error: unknown, context: CodexAuthContext | undefined,
|
|
29
|
+
accountSelector?: string, cleanup?: () => void): Response | undefined {
|
|
30
|
+
const refusal = mapCodexAuthContextErrorToResponse(error, { now: Date.now(), accountSelector });
|
|
31
|
+
if (refusal) {
|
|
32
|
+
cleanup?.();
|
|
33
|
+
releaseCodexAuthContextProbeLease(context);
|
|
34
|
+
}
|
|
35
|
+
return refusal;
|
|
36
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../../codex/installation-id";
|
|
2
|
+
import { passthroughBuildErrorResponse } from "./passthrough-build-error";
|
|
1
3
|
import { recoverAutoPausedAccount, rotatePassthroughKeyOn429 } from "./passthrough-key-rotation";
|
|
2
4
|
import { adoptCodexWsStage, capturePassthroughAffinity } from "./passthrough-observations";
|
|
3
5
|
import { spendLedgerStorageErrorResponse } from "./spend-storage-error";
|
|
@@ -48,14 +50,9 @@ import {
|
|
|
48
50
|
createCodexAuthDispatchGuard,
|
|
49
51
|
} from "../../codex/auth-context";
|
|
50
52
|
import {
|
|
51
|
-
NamespaceToolCollisionError,
|
|
52
53
|
restoreRoutedNamespaceCalls,
|
|
53
54
|
} from "../../responses/namespace-tool-compat";
|
|
54
|
-
import { restoreRoutedCustomCalls
|
|
55
|
-
import { XaiToolSchemaCompatibilityError } from "../../adapters/xai-tool-schema";
|
|
56
|
-
import { MuseToolChoiceCompatibilityError } from "../../adapters/openai-responses/muse-tool-choice";
|
|
57
|
-
import { MuseToolCatalogCompatibilityError } from "../../adapters/openai-responses/muse-tool-catalog";
|
|
58
|
-
import { OpenGatewayInputCompatibilityError } from "../../adapters/openai-responses/opengateway-input";
|
|
55
|
+
import { restoreRoutedCustomCalls } from "../../responses/custom-tool-compat";
|
|
59
56
|
import { formatErrorResponse } from "../../bridge";
|
|
60
57
|
import { redactSecretString } from "../../lib/redact";
|
|
61
58
|
import {
|
|
@@ -379,22 +376,8 @@ export async function preparePassthroughExchange(
|
|
|
379
376
|
});
|
|
380
377
|
} catch (error) {
|
|
381
378
|
releaseCodexAuthContextProbeLease(admissionState.authCtx);
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
// it here escaped every catch up to the Bun handler, so the same request produced an
|
|
385
|
-
// unstructured 500 — and no request log — depending only on whether a rotation ran first.
|
|
386
|
-
// Same shape for a tool_choice this proxy cannot honor: the destination rejects a schema the
|
|
387
|
-
// catalog had to drop, so the selector naming it is a client input error, not a 500.
|
|
388
|
-
if (
|
|
389
|
-
error instanceof NamespaceToolCollisionError
|
|
390
|
-
|| error instanceof XaiToolSchemaCompatibilityError
|
|
391
|
-
|| error instanceof RoutedCustomToolCompatError
|
|
392
|
-
|| error instanceof MuseToolChoiceCompatibilityError
|
|
393
|
-
|| error instanceof MuseToolCatalogCompatibilityError
|
|
394
|
-
|| error instanceof OpenGatewayInputCompatibilityError
|
|
395
|
-
) {
|
|
396
|
-
return formatErrorResponse(400, "invalid_request_error", redactSecretString(error.message));
|
|
397
|
-
}
|
|
379
|
+
const refusal = passthroughBuildErrorResponse(error, route.codexAccountNamespace);
|
|
380
|
+
if (refusal) return refusal;
|
|
398
381
|
throw error;
|
|
399
382
|
}
|
|
400
383
|
const functionRepairSchemas = isCanonicalOpenAiForwardProvider(route.provider)
|
|
@@ -1124,6 +1107,7 @@ export async function preparePassthroughExchange(
|
|
|
1124
1107
|
recordAdapterReasoning(logCtx, request);
|
|
1125
1108
|
recordAdapterTier(logCtx, request);
|
|
1126
1109
|
} catch (err) {
|
|
1110
|
+
if (err instanceof CodexInstallationIdUnavailableError) return { failed: transportFailureResponse(err) };
|
|
1127
1111
|
upstream.abort();
|
|
1128
1112
|
if (options.abortSignal?.aborted) return { failed: clientCancelledResponse() };
|
|
1129
1113
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -1418,6 +1402,7 @@ export async function preparePassthroughExchange(
|
|
|
1418
1402
|
recordAdapterReasoning(logCtx, request);
|
|
1419
1403
|
recordAdapterTier(logCtx, request);
|
|
1420
1404
|
} catch (err) {
|
|
1405
|
+
if (err instanceof CodexInstallationIdUnavailableError) return transportFailureResponse(err);
|
|
1421
1406
|
upstream.abort();
|
|
1422
1407
|
if (options.abortSignal?.aborted) return clientCancelledResponse();
|
|
1423
1408
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../../codex/installation-id";
|
|
1
2
|
import type { ResponsesRequestContext } from "./core-options";
|
|
2
3
|
import type { PreparedResponsesRequest } from "./request-prepare";
|
|
3
4
|
import type { ResponsesTransport } from "./request-transport";
|
|
@@ -111,7 +112,8 @@ export async function prepareResponsesSidecarAuth(
|
|
|
111
112
|
// An unavailable/cooling/expired Multi credential disables the helper; it
|
|
112
113
|
// must not turn a valid routed-provider request into a Codex-auth failure.
|
|
113
114
|
if (
|
|
114
|
-
!(err instanceof
|
|
115
|
+
!(err instanceof CodexInstallationIdUnavailableError)
|
|
116
|
+
&& !(err instanceof CodexPoolAuthenticationError)
|
|
115
117
|
&& !(err instanceof CodexAuthContextError)
|
|
116
118
|
&& !(err instanceof CodexAccountCooldownError)
|
|
117
119
|
&& !(err instanceof CodexThreadAffinityExpiredError)
|
package/src/server/search.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
|
|
2
|
+
import { isolateCodexPoolClientMetadata, mergeCodexSelectedHeaders } from "../codex/forward-transport-headers";
|
|
1
3
|
/**
|
|
2
4
|
* /v1/alpha/search relay.
|
|
3
5
|
*
|
|
@@ -159,6 +161,7 @@ export async function handleSearch(
|
|
|
159
161
|
? `${upstream.providerName}-${accountNamespace}`
|
|
160
162
|
: formatCodexProviderForLog(upstream.providerName, codexLogAccountId(upstream.authContext), config);
|
|
161
163
|
} catch (err) {
|
|
164
|
+
if (err instanceof CodexInstallationIdUnavailableError) return formatErrorResponse(503, "server_busy", err.message);
|
|
162
165
|
if (err instanceof CodexAccountCooldownError) {
|
|
163
166
|
return cooldownErrorResponse(err, Date.now(), accountNamespace);
|
|
164
167
|
}
|
|
@@ -194,9 +197,9 @@ export async function handleSearch(
|
|
|
194
197
|
}
|
|
195
198
|
}
|
|
196
199
|
|
|
197
|
-
const headers
|
|
198
|
-
|
|
199
|
-
|
|
200
|
+
const headers = mergeCodexSelectedHeaders(
|
|
201
|
+
{ "content-type": "application/json", ...upstream.provider.headers }, upstream.headers,
|
|
202
|
+
);
|
|
200
203
|
const url = `${upstream.provider.baseUrl}/alpha/search`;
|
|
201
204
|
const timeoutMs = config.search?.timeoutMs ?? SEARCH_UPSTREAM_TIMEOUT_MS;
|
|
202
205
|
const linkedSignal = signalWithTimeout(timeoutMs, req.signal);
|
|
@@ -207,7 +210,9 @@ export async function handleSearch(
|
|
|
207
210
|
upstreamResponse = await fetch(url, {
|
|
208
211
|
method: "POST",
|
|
209
212
|
headers,
|
|
210
|
-
body: JSON.stringify(
|
|
213
|
+
body: JSON.stringify(isolateCodexPoolClientMetadata(
|
|
214
|
+
relayBody, upstream.authContext.kind === "pool" ? upstream.authContext.chatgptAccountId : undefined,
|
|
215
|
+
)),
|
|
211
216
|
signal: linkedSignal.signal,
|
|
212
217
|
// Credential-bearing: do not follow a cross-origin 3xx. Bun strips `Authorization`
|
|
213
218
|
// across origins but forwards nonstandard headers such as `chatgpt-account-id`,
|
|
@@ -232,6 +237,10 @@ export async function handleSearch(
|
|
|
232
237
|
if (contentType) relayHeaders["content-type"] = contentType;
|
|
233
238
|
return new Response(observed.bytes, { status: upstreamResponse.status, headers: relayHeaders });
|
|
234
239
|
} catch (err) {
|
|
240
|
+
if (err instanceof CodexInstallationIdUnavailableError) {
|
|
241
|
+
upstream.releaseProbeLease?.();
|
|
242
|
+
return formatErrorResponse(503, "server_busy", err.message);
|
|
243
|
+
}
|
|
235
244
|
if (req.signal.aborted) {
|
|
236
245
|
return formatErrorResponse(499, "client_closed_request", "search request canceled by client");
|
|
237
246
|
}
|