@bitkyc08/opencodex 2.7.43-preview.20260728 → 2.8.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/README.md +8 -1
- package/bin/ocx.mjs +47 -22
- package/gui/dist/assets/index-BDjpkcRN.js +67 -0
- package/gui/dist/assets/index-BHsKRFh9.css +1 -0
- package/gui/dist/index.html +2 -2
- package/package.json +1 -1
- package/src/AGENTS.md +28 -0
- package/src/adapters/anthropic.ts +15 -6
- package/src/adapters/cursor/discovery.ts +4 -1
- package/src/adapters/cursor/effort-map.ts +3 -0
- package/src/adapters/cursor/native-exec-shell.ts +18 -6
- package/src/adapters/cursor/protobuf-events.ts +24 -2
- package/src/adapters/cursor/protobuf-request.ts +1 -2
- package/src/adapters/cursor/tool-definitions.ts +68 -29
- package/src/adapters/google-wire-compiler.ts +4 -0
- package/src/adapters/google.ts +128 -2
- package/src/adapters/identity.ts +12 -2
- package/src/adapters/kiro.ts +64 -7
- package/src/adapters/mimo-free.ts +2 -0
- package/src/adapters/openai-responses.ts +246 -59
- package/src/claude/agents-inject.ts +5 -0
- package/src/claude/alias.ts +94 -14
- package/src/claude/inbound.ts +26 -9
- package/src/claude/outbound.ts +6 -3
- package/src/cli/account-auth.ts +1 -1
- package/src/cli/agent-driven.ts +37 -0
- package/src/cli/catalog-prewarm.ts +24 -0
- package/src/cli/claude.ts +35 -10
- package/src/cli/doctor.ts +71 -19
- package/src/cli/help.ts +42 -6
- package/src/cli/index.ts +93 -19
- package/src/cli/interactive-confirm.ts +133 -0
- package/src/cli/opencode.ts +701 -0
- package/src/cli/provider-runtime.ts +3 -0
- package/src/cli/provider.ts +31 -10
- package/src/cli/star-prompt.ts +79 -18
- package/src/cli/status.ts +47 -13
- package/src/cli/v2.ts +10 -1
- package/src/codex/account-id.ts +34 -0
- package/src/codex/account-lifecycle.ts +4 -1
- package/src/codex/account-namespace-match.ts +63 -0
- package/src/codex/account-namespaces.ts +149 -0
- package/src/codex/account-pause.ts +20 -0
- package/src/codex/account-store.ts +2 -0
- package/src/codex/account-usability.ts +6 -1
- package/src/codex/app-server-processes.ts +511 -0
- package/src/codex/auth-api.ts +293 -34
- package/src/codex/auth-collision.ts +2 -1
- package/src/codex/auth-context.ts +60 -17
- package/src/codex/catalog/bundled.ts +9 -2
- package/src/codex/catalog/parsing.ts +42 -2
- package/src/codex/catalog/provider-fetch.ts +264 -70
- package/src/codex/catalog/sync.ts +45 -8
- package/src/codex/catalog.ts +2 -2
- package/src/codex/features.ts +524 -5
- package/src/codex/history-provider.ts +145 -1
- package/src/codex/inject.ts +114 -14
- package/src/codex/main-account.ts +2 -8
- package/src/codex/pool-rotation.ts +186 -0
- package/src/codex/quota.ts +92 -2
- package/src/codex/routing.ts +695 -106
- package/src/codex/runtime.ts +10 -1
- package/src/codex/shim.ts +4 -1
- package/src/codex/subagent-defaults.ts +550 -0
- package/src/codex/subagent-model-fallback.ts +2 -0
- package/src/codex/sync.ts +3 -0
- package/src/config.ts +574 -25
- package/src/generated/jawcode-model-metadata.ts +12 -12
- package/src/github/star-state.ts +191 -0
- package/src/images/artifacts.ts +516 -0
- package/src/images/fulfill-video.ts +163 -0
- package/src/images/fulfill.ts +111 -0
- package/src/images/index.ts +4 -0
- package/src/images/loop.ts +789 -0
- package/src/images/plan.ts +133 -0
- package/src/images/synthetic-tool.ts +133 -0
- package/src/images/types.ts +41 -0
- package/src/images/xai-client.ts +141 -0
- package/src/images/xai-video-client.ts +163 -0
- package/src/lib/admin-secrets.ts +25 -0
- package/src/lib/bun-binary-validator.d.mts +3 -0
- package/src/lib/bun-binary-validator.mjs +18 -0
- package/src/lib/bun-runtime.ts +6 -20
- package/src/lib/config-ownership.ts +327 -0
- package/src/lib/crash-guard.ts +2 -0
- package/src/lib/destination-policy.ts +132 -7
- package/src/lib/pinned-http.ts +151 -0
- package/src/lib/process-control.ts +2 -2
- package/src/lib/provider-outbound.ts +167 -0
- package/src/lib/provider-url.ts +14 -0
- package/src/lib/proxy-env.ts +18 -0
- package/src/lib/shadow-call.ts +30 -0
- package/src/lib/test-home-guard.ts +90 -0
- package/src/lib/win-exec.ts +12 -2
- package/src/lib/windows-elevation.ts +81 -3
- package/src/lib/windows-secret-acl.ts +189 -12
- package/src/lib/winsw.ts +2 -0
- package/src/oauth/anthropic-routing.ts +570 -0
- package/src/oauth/health.ts +6 -0
- package/src/oauth/index.ts +310 -75
- package/src/oauth/key-providers.ts +38 -8
- package/src/oauth/kimi.ts +2 -0
- package/src/oauth/kiro-credentials.ts +373 -12
- package/src/oauth/kiro.ts +424 -43
- package/src/oauth/login-cli.ts +33 -6
- package/src/oauth/store.ts +56 -4
- package/src/oauth/types.ts +11 -0
- package/src/providers/alibaba-region-migration.ts +16 -3
- package/src/providers/antigravity-models.ts +3 -0
- package/src/providers/api-keys.ts +13 -6
- package/src/providers/derive.ts +8 -2
- package/src/providers/key-failover.ts +24 -4
- package/src/providers/model-discovery.ts +356 -0
- package/src/providers/quota.ts +233 -29
- package/src/providers/registry.ts +125 -3
- package/src/responses/parser.ts +11 -0
- package/src/responses/state.ts +22 -8
- package/src/responses/tool-groups.ts +19 -0
- package/src/router.ts +19 -7
- package/src/server/auth-cors.ts +114 -24
- package/src/server/claude-messages.ts +8 -1
- package/src/server/gui-static.ts +30 -6
- package/src/server/images.ts +303 -9
- package/src/server/index.ts +77 -9
- package/src/server/lifecycle.ts +25 -1
- package/src/server/live.ts +75 -25
- package/src/server/management/agent-settings-routes.ts +106 -8
- package/src/server/management/combo-routes.ts +7 -0
- package/src/server/management/config-routes.ts +22 -7
- package/src/server/management/context.ts +11 -1
- package/src/server/management/logs-usage-routes.ts +167 -3
- package/src/server/management/model-routes.ts +46 -13
- package/src/server/management/oauth-account-routes.ts +163 -17
- package/src/server/management/provider-routes.ts +73 -10
- package/src/server/management/shared.ts +2 -2
- package/src/server/management/sidebar-routes.ts +39 -0
- package/src/server/management/system-restart.ts +172 -0
- package/src/server/management/system-routes.ts +33 -10
- package/src/server/management-api.ts +5 -3
- package/src/server/management-auth.ts +216 -0
- package/src/server/proxy-liveness.ts +14 -3
- package/src/server/responses/compact.ts +21 -13
- package/src/server/responses/core.ts +614 -172
- package/src/server/responses/upstream-error.ts +48 -0
- package/src/server/responses-image-gen-repair.ts +118 -0
- package/src/server/responses-item-id-repair.ts +10 -85
- package/src/server/sse-payload-rewrite.ts +116 -0
- package/src/server/startup-action-control.ts +30 -14
- package/src/server/system-env.ts +28 -10
- package/src/service.ts +284 -19
- package/src/storage/cleanup-job.ts +57 -0
- package/src/storage/cleanup.ts +1504 -28
- package/src/storage/policy-job.ts +387 -0
- package/src/storage/policy-scheduler.ts +40 -0
- package/src/storage/policy-worker.ts +53 -0
- package/src/storage/policy.ts +522 -0
- package/src/storage/restore-job.ts +253 -0
- package/src/storage/restore-worker.ts +52 -0
- package/src/storage/storage-mutation-coordinator.ts +109 -0
- package/src/storage/worker-lifecycle.ts +81 -0
- package/src/tray/windows.ts +34 -4
- package/src/types.ts +107 -1
- package/src/update/badge.ts +72 -0
- package/src/update/index.ts +36 -18
- package/src/update/job.ts +111 -16
- package/src/update/npm-invocation.d.mts +23 -0
- package/src/update/npm-invocation.mjs +94 -0
- package/src/usage/debug.ts +2 -0
- package/src/usage/expected-prices.ts +6 -5
- package/src/usage/log.ts +12 -0
- package/src/web-search/loop.ts +57 -16
- package/gui/dist/assets/index-CjKFJHSC.js +0 -65
- package/gui/dist/assets/index-DfVGuN88.css +0 -1
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
import { FORWARD_HEADERS } from "../adapters/openai-responses";
|
|
10
10
|
import { enforceAnthropicImageLimits } from "../adapters/anthropic-image-guard";
|
|
11
11
|
import { normalizeAnthropicImages } from "../adapters/anthropic-image-normalize";
|
|
12
|
-
import { AnthropicRequestError, anthropicToResponsesTranslation, extractOcxRouteDirective, resolveInboundModel, type ClaudeCacheKeySource } from "../claude/inbound";
|
|
12
|
+
import { AnthropicRequestError, anthropicToResponsesTranslation, extractOcxEffortDirective, extractOcxRouteDirective, resolveInboundModel, type ClaudeCacheKeySource } from "../claude/inbound";
|
|
13
13
|
import { resolveDesktop3pAlias } from "../claude/desktop-3p";
|
|
14
14
|
import { recordDesktopRequest } from "../claude/desktop-health";
|
|
15
15
|
import { stripOneMillionMarker } from "../claude/context-windows";
|
|
@@ -523,6 +523,7 @@ export async function handleClaudeMessages(
|
|
|
523
523
|
let anthropicBody: unknown;
|
|
524
524
|
let internalBody: Rec;
|
|
525
525
|
let cacheKeySource: ClaudeCacheKeySource = null;
|
|
526
|
+
let effortOverride: ReturnType<typeof extractOcxEffortDirective> = null;
|
|
526
527
|
try {
|
|
527
528
|
anthropicBody = await readAnthropicBody(req);
|
|
528
529
|
// Defensive [1m] strip (devlog 138): clients normally remove the context-variant
|
|
@@ -539,6 +540,7 @@ export async function handleClaudeMessages(
|
|
|
539
540
|
const routeOverride = extractOcxRouteDirective(anthropicBody);
|
|
540
541
|
if (routeOverride && typeof anthropicBody.model === "string") {
|
|
541
542
|
anthropicBody.model = stripOneMillionMarker(routeOverride);
|
|
543
|
+
effortOverride = extractOcxEffortDirective(anthropicBody);
|
|
542
544
|
}
|
|
543
545
|
}
|
|
544
546
|
// Debug capture (opt-in allowlist scalars) BEFORE the passthrough branch so
|
|
@@ -567,6 +569,10 @@ export async function handleClaudeMessages(
|
|
|
567
569
|
if (isRec(anthropicBody) && wantsNativePassthrough(req, config, anthropicBody.model)) {
|
|
568
570
|
return await anthropicNativePassthrough(req, config, logCtx, logIds, anthropicBody, "/v1/messages");
|
|
569
571
|
}
|
|
572
|
+
if (isRec(anthropicBody) && effortOverride) {
|
|
573
|
+
anthropicBody.output_config = { effort: effortOverride };
|
|
574
|
+
delete anthropicBody.thinking;
|
|
575
|
+
}
|
|
570
576
|
const translation = anthropicToResponsesTranslation(anthropicBody, config.claudeCode);
|
|
571
577
|
internalBody = translation.body;
|
|
572
578
|
cacheKeySource = translation.cacheKeySource;
|
|
@@ -678,6 +684,7 @@ export async function handleClaudeMessages(
|
|
|
678
684
|
};
|
|
679
685
|
const upstream = await handleResponses(internalReq, buildClaudeReplayConfig(config), logCtx, {
|
|
680
686
|
abortSignal: req.signal,
|
|
687
|
+
promptCacheKeyIsSharedCohort: cacheKeySource === "system",
|
|
681
688
|
...(logIds ? { onFirstOutput: () => recordFirstOutput(logCtx, logIds.start) } : {}),
|
|
682
689
|
onNativePassthroughTerminal: status => finalizeNativeLog(httpStatusForTerminalStatus(status), { terminalStatus: status, closeReason: "terminal" }),
|
|
683
690
|
onNativePassthroughCancel: () => finalizeNativeLog(499, { closeReason: "client_cancel" }),
|
package/src/server/gui-static.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
2
|
import { extname, isAbsolute, join, relative, resolve } from "node:path";
|
|
3
|
+
import { browserSecurityHeaders } from "./auth-cors";
|
|
4
|
+
import type { GuiSessionBootstrap } from "./management-auth";
|
|
3
5
|
|
|
4
6
|
/** opencodex version, read from the packaged package.json (same source as the server bootstrap). */
|
|
5
7
|
const VERSION = (() => {
|
|
@@ -54,8 +56,31 @@ function isFile(path: string): boolean {
|
|
|
54
56
|
}
|
|
55
57
|
}
|
|
56
58
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
+
function htmlResponse(path: string, session?: GuiSessionBootstrap): Response {
|
|
60
|
+
let html = readFileSync(path, "utf8");
|
|
61
|
+
if (session) {
|
|
62
|
+
const bootstrap = [
|
|
63
|
+
`<meta name="opencodex-session-token" content="${session.token}">`,
|
|
64
|
+
`<meta name="opencodex-session-csrf" content="${session.csrfToken}">`,
|
|
65
|
+
`<meta name="opencodex-session-origin" content="${session.origin}">`,
|
|
66
|
+
].join("");
|
|
67
|
+
html = html.includes("</head>") ? html.replace("</head>", `${bootstrap}</head>`) : `${bootstrap}${html}`;
|
|
68
|
+
}
|
|
69
|
+
return new Response(html, {
|
|
70
|
+
headers: {
|
|
71
|
+
"Content-Type": "text/html",
|
|
72
|
+
"Cache-Control": "no-store",
|
|
73
|
+
Pragma: "no-cache",
|
|
74
|
+
...browserSecurityHeaders(),
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function serveGuiFile(
|
|
80
|
+
pathname: string,
|
|
81
|
+
guiDist = findGuiDist(),
|
|
82
|
+
session?: GuiSessionBootstrap,
|
|
83
|
+
): Response | null {
|
|
59
84
|
if (!guiDist) return null;
|
|
60
85
|
const filePath = resolveGuiFilePath(guiDist, pathname);
|
|
61
86
|
if (!filePath) return null;
|
|
@@ -64,9 +89,7 @@ export function serveGuiFile(pathname: string): Response | null {
|
|
|
64
89
|
if (!extname(pathname)) {
|
|
65
90
|
const indexPath = join(guiDist, "index.html");
|
|
66
91
|
if (isFile(indexPath)) {
|
|
67
|
-
return
|
|
68
|
-
headers: { "Content-Type": "text/html" },
|
|
69
|
-
});
|
|
92
|
+
return htmlResponse(indexPath, session);
|
|
70
93
|
}
|
|
71
94
|
}
|
|
72
95
|
return null;
|
|
@@ -74,8 +97,9 @@ export function serveGuiFile(pathname: string): Response | null {
|
|
|
74
97
|
|
|
75
98
|
const ext = extname(filePath);
|
|
76
99
|
const contentType = MIME_TYPES[ext] || "application/octet-stream";
|
|
100
|
+
if (ext === ".html") return htmlResponse(filePath, session);
|
|
77
101
|
return new Response(Bun.file(filePath), {
|
|
78
|
-
headers: { "Content-Type": contentType },
|
|
102
|
+
headers: { "Content-Type": contentType, ...browserSecurityHeaders() },
|
|
79
103
|
});
|
|
80
104
|
}
|
|
81
105
|
|
package/src/server/images.ts
CHANGED
|
@@ -25,10 +25,16 @@ import { signalWithTimeout } from "../lib/abort";
|
|
|
25
25
|
import { sidecarEnter } from "../lib/sidecar-tracker";
|
|
26
26
|
import type { OcxConfig } from "../types";
|
|
27
27
|
import { resolveFirstUsableOpenAiSidecar, selectImagesProvider } from "../providers/openai-sidecar";
|
|
28
|
+
import { getProviderRegistryEntry } from "../providers/registry";
|
|
28
29
|
import { readJsonRequestBody } from "./request-decompress";
|
|
29
30
|
import { ForwardAdmissionCredentialError, validateForwardAdmissionCredential } from "./auth-cors";
|
|
30
31
|
import type { RequestLogContext } from "./request-log";
|
|
31
32
|
import { codexLogAccountId, decodeRequestErrorResponse } from "./responses";
|
|
33
|
+
import { getValidAccessToken, getOAuthCredentialProjectId } from "../oauth/index";
|
|
34
|
+
import { safeAntigravityHttpErrorMessage } from "../adapters/google-errors";
|
|
35
|
+
import { sanitizeUpstreamErrorText } from "../adapters/upstream-http-error";
|
|
36
|
+
import { ANTIGRAVITY_REQUEST_UA } from "../adapters/google-antigravity-wire";
|
|
37
|
+
import { decodeValidatedImageBase64, MAX_ENCODED_BYTES_PER_IMAGE } from "../images/artifacts";
|
|
32
38
|
|
|
33
39
|
export type ImagesEndpoint = "generations" | "edits";
|
|
34
40
|
|
|
@@ -42,6 +48,276 @@ const IMAGES_UPSTREAM_TIMEOUT_MS = 300_000;
|
|
|
42
48
|
*/
|
|
43
49
|
const IMAGES_RESPONSE_MAX_BYTES = 100 * 1024 * 1024;
|
|
44
50
|
|
|
51
|
+
const CCA_IMAGE_MODEL = "gemini-3.1-flash-image";
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Google Gemini finishReasons that indicate a permanent content/safety block.
|
|
55
|
+
* When any of these is present, the same prompt will always fail — retrying
|
|
56
|
+
* wastes paid quota. The response is surfaced as 400 (non-retryable) instead
|
|
57
|
+
* of 502 (which codex retries up to 5 times).
|
|
58
|
+
*/
|
|
59
|
+
const CCA_BLOCKING_FINISH_REASONS: ReadonlySet<string> = new Set([
|
|
60
|
+
"SAFETY",
|
|
61
|
+
"BLOCKLIST",
|
|
62
|
+
"PROHIBITED_CONTENT",
|
|
63
|
+
"SPII",
|
|
64
|
+
"RECITATION",
|
|
65
|
+
]);
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Race a promise against an abort signal. If the signal aborts first, reject
|
|
69
|
+
* immediately — our code stops awaiting the underlying operation even though
|
|
70
|
+
* the HTTP request behind it may still complete. Used to make the non-cancellable
|
|
71
|
+
* OAuth refresh chain responsive to client cancellation and deadline expiry.
|
|
72
|
+
*/
|
|
73
|
+
function abortableRace<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
74
|
+
if (signal.aborted) {
|
|
75
|
+
return Promise.reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
|
|
76
|
+
}
|
|
77
|
+
return new Promise<T>((resolve, reject) => {
|
|
78
|
+
const onAbort = () => reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
|
|
79
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
80
|
+
promise.then(
|
|
81
|
+
(val) => { signal.removeEventListener("abort", onAbort); resolve(val); },
|
|
82
|
+
(err) => { signal.removeEventListener("abort", onAbort); reject(err); },
|
|
83
|
+
);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function tryCcaImageGeneration(
|
|
88
|
+
body: unknown,
|
|
89
|
+
config: OcxConfig,
|
|
90
|
+
logCtx: RequestLogContext,
|
|
91
|
+
signal: AbortSignal,
|
|
92
|
+
endpoint: ImagesEndpoint,
|
|
93
|
+
): Promise<Response | undefined> {
|
|
94
|
+
if (endpoint !== "generations") return undefined;
|
|
95
|
+
const provider = config.providers?.["google-antigravity"];
|
|
96
|
+
if (!provider || provider.disabled) return undefined;
|
|
97
|
+
|
|
98
|
+
const prompt = (body as { prompt?: unknown })?.prompt;
|
|
99
|
+
if (typeof prompt !== "string" || !prompt.trim()) {
|
|
100
|
+
return formatErrorResponse(400, "invalid_request_error", "prompt is required and must not be empty");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const nRaw = (body as { n?: unknown })?.n;
|
|
104
|
+
if (nRaw !== undefined && nRaw !== null) {
|
|
105
|
+
const n = typeof nRaw === "number" ? nRaw : Number(nRaw);
|
|
106
|
+
if (!Number.isInteger(n) || n !== 1) {
|
|
107
|
+
return formatErrorResponse(400, "invalid_request_error", "CCA image generation supports n=1 only");
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Create the deadline before credential resolution so the timeout covers
|
|
112
|
+
// OAuth token refresh and project discovery, not just the upstream fetch.
|
|
113
|
+
const timeoutMs = config.images?.timeoutMs ?? IMAGES_UPSTREAM_TIMEOUT_MS;
|
|
114
|
+
const linkedSignal = signalWithTimeout(timeoutMs, signal);
|
|
115
|
+
let token: string;
|
|
116
|
+
try {
|
|
117
|
+
// Race the OAuth refresh against the deadline signal. getValidAccessToken
|
|
118
|
+
// chains through 4 layers (resolveAccessSnapshotForAccount →
|
|
119
|
+
// refreshAndPersistAccessToken → refreshGenericAccountWithLock →
|
|
120
|
+
// def.refresh()) that do HTTP calls without accepting a signal. Rather than
|
|
121
|
+
// threading signal through the entire chain, race the whole call against
|
|
122
|
+
// linkedSignal: when the signal aborts we stop awaiting and surface the
|
|
123
|
+
// cancellation immediately instead of hanging on the refresh HTTP call.
|
|
124
|
+
token = await abortableRace(getValidAccessToken("google-antigravity"), linkedSignal.signal);
|
|
125
|
+
} catch (err) {
|
|
126
|
+
linkedSignal.cleanup();
|
|
127
|
+
// abortableRace rejects immediately when the signal fires, so client
|
|
128
|
+
// cancellation and deadline expiry surface here. Parent abort propagates
|
|
129
|
+
// into the linked signal, so check parent first (499) before the linked
|
|
130
|
+
// signal (504).
|
|
131
|
+
if (signal.aborted) {
|
|
132
|
+
return formatErrorResponse(499, "client_closed_request", "CCA image request canceled by client");
|
|
133
|
+
}
|
|
134
|
+
if (linkedSignal.signal.aborted) {
|
|
135
|
+
return formatErrorResponse(504, "upstream_error", "CCA image generation timed out during authentication");
|
|
136
|
+
}
|
|
137
|
+
// Missing/revoked credential → 401 (re-login required); transient refresh/network → 502.
|
|
138
|
+
const errName = err instanceof Error ? err.name : "";
|
|
139
|
+
if (errName === "OAuthLoginRequiredError") {
|
|
140
|
+
return formatErrorResponse(401, "invalid_request_error", "Google Antigravity login required: run 'ocx login google-antigravity'");
|
|
141
|
+
}
|
|
142
|
+
return formatErrorResponse(502, "upstream_error", "CCA image generation failed: OAuth token refresh failed");
|
|
143
|
+
}
|
|
144
|
+
const project = getOAuthCredentialProjectId("google-antigravity");
|
|
145
|
+
if (!project) {
|
|
146
|
+
linkedSignal.cleanup();
|
|
147
|
+
return formatErrorResponse(
|
|
148
|
+
400,
|
|
149
|
+
"invalid_request_error",
|
|
150
|
+
"Antigravity requires a discovered Cloud Code Assist project id (re-run `ocx login google-antigravity`).",
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
logCtx.provider = "google-antigravity";
|
|
155
|
+
logCtx.model = CCA_IMAGE_MODEL;
|
|
156
|
+
|
|
157
|
+
// Pin to the registry endpoint — never use a config-level baseUrl override for OAuth token transmission.
|
|
158
|
+
const registryEntry = getProviderRegistryEntry("google-antigravity");
|
|
159
|
+
const baseUrl = registryEntry?.baseUrl ?? "https://daily-cloudcode-pa.googleapis.com";
|
|
160
|
+
const envelope = {
|
|
161
|
+
model: CCA_IMAGE_MODEL,
|
|
162
|
+
userAgent: "antigravity",
|
|
163
|
+
requestType: "agent",
|
|
164
|
+
project,
|
|
165
|
+
requestId: `agent-${crypto.randomUUID()}`,
|
|
166
|
+
request: {
|
|
167
|
+
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
|
168
|
+
generationConfig: { responseModalities: ["TEXT", "IMAGE"] },
|
|
169
|
+
sessionId: `ocx-img-${crypto.randomUUID().slice(0, 8)}`,
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
let upstream: Response;
|
|
173
|
+
try {
|
|
174
|
+
try {
|
|
175
|
+
upstream = await fetch(`${baseUrl}/v1internal:generateContent`, {
|
|
176
|
+
method: "POST",
|
|
177
|
+
headers: {
|
|
178
|
+
"Content-Type": "application/json",
|
|
179
|
+
"Authorization": `Bearer ${token}`,
|
|
180
|
+
"User-Agent": ANTIGRAVITY_REQUEST_UA,
|
|
181
|
+
},
|
|
182
|
+
body: JSON.stringify(envelope),
|
|
183
|
+
signal: linkedSignal.signal,
|
|
184
|
+
});
|
|
185
|
+
} catch (err) {
|
|
186
|
+
if (signal.aborted) return formatErrorResponse(499, "client_closed_request", "CCA image request canceled by client");
|
|
187
|
+
if (err instanceof Error && err.name === "TimeoutError") {
|
|
188
|
+
return formatErrorResponse(504, "upstream_error", "CCA image generation timed out");
|
|
189
|
+
}
|
|
190
|
+
// Network/DNS/runtime errors may embed the request URL or headers verbatim
|
|
191
|
+
// (e.g. "fetch failed: https://…/v1internal:generateContent"). The token
|
|
192
|
+
// lives in an Authorization header, not in the URL, but sanitize defensively
|
|
193
|
+
// so no upstream-rejected credential or query param can reach the client,
|
|
194
|
+
// and strip the internal base URL host from the surfaced message.
|
|
195
|
+
const rawMsg = err instanceof Error ? err.message : String(err);
|
|
196
|
+
const safeMsg = sanitizeUpstreamErrorText(rawMsg).replace(
|
|
197
|
+
/https?:\/\/[^\s"'<>]+/gi,
|
|
198
|
+
"[upstream-url]",
|
|
199
|
+
);
|
|
200
|
+
return formatErrorResponse(502, "upstream_error", `CCA image generation failed: ${safeMsg}`);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Stream the upstream body with a bounded reader so an oversized or malicious
|
|
204
|
+
// response is rejected mid-stream rather than after a full arrayBuffer() allocation.
|
|
205
|
+
let payload: Uint8Array;
|
|
206
|
+
try {
|
|
207
|
+
const reader = upstream.body?.getReader();
|
|
208
|
+
if (!reader) {
|
|
209
|
+
return formatErrorResponse(502, "upstream_error", "CCA image response had no body");
|
|
210
|
+
}
|
|
211
|
+
const chunks: Uint8Array[] = [];
|
|
212
|
+
let total = 0;
|
|
213
|
+
try {
|
|
214
|
+
for (;;) {
|
|
215
|
+
const { done, value } = await reader.read();
|
|
216
|
+
if (done) break;
|
|
217
|
+
total += value.byteLength;
|
|
218
|
+
if (total > IMAGES_RESPONSE_MAX_BYTES) {
|
|
219
|
+
await reader.cancel().catch(() => {});
|
|
220
|
+
return formatErrorResponse(502, "upstream_error", `CCA image response too large (exceeded ${IMAGES_RESPONSE_MAX_BYTES} bytes)`);
|
|
221
|
+
}
|
|
222
|
+
chunks.push(value);
|
|
223
|
+
}
|
|
224
|
+
} finally {
|
|
225
|
+
try { await reader.cancel(); } catch { /* ignore */ }
|
|
226
|
+
reader.releaseLock();
|
|
227
|
+
}
|
|
228
|
+
payload = new Uint8Array(total);
|
|
229
|
+
let offset = 0;
|
|
230
|
+
for (const chunk of chunks) {
|
|
231
|
+
payload.set(chunk, offset);
|
|
232
|
+
offset += chunk.byteLength;
|
|
233
|
+
}
|
|
234
|
+
} catch (err) {
|
|
235
|
+
// Body-read timeout/abort: when CCA returns headers then stalls, the linked
|
|
236
|
+
// signal's timeout aborts reader.read(), which rejects here. The rejection
|
|
237
|
+
// often surfaces as AbortError (not TimeoutError), so distinguish by signal
|
|
238
|
+
// state, not error name. Parent abort propagates into the linked signal, so
|
|
239
|
+
// check the parent first: parent abort → 499 (client cancelled); linked-only
|
|
240
|
+
// abort → 504 (upstream stall); anything else → 502 body-read failure.
|
|
241
|
+
if (signal.aborted) {
|
|
242
|
+
return formatErrorResponse(499, "client_closed_request", "CCA image request canceled by client");
|
|
243
|
+
}
|
|
244
|
+
if (linkedSignal.signal.aborted) {
|
|
245
|
+
return formatErrorResponse(504, "upstream_error", "CCA image response timed out during body read");
|
|
246
|
+
}
|
|
247
|
+
const rawMsg = err instanceof Error ? err.message : String(err);
|
|
248
|
+
const safeMsg = sanitizeUpstreamErrorText(rawMsg).replace(/https?:\/\/[^\s"'<>]+/gi, "[upstream-url]");
|
|
249
|
+
return formatErrorResponse(502, "upstream_error", `CCA image body read failed: ${safeMsg}`);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (!upstream.ok) {
|
|
253
|
+
// Preserve auth/rate-limit and other permanent 4xx signals so callers can
|
|
254
|
+
// distinguish retryable from permanent failures. Remaining 5xx collapse to 502.
|
|
255
|
+
const text = new TextDecoder().decode(payload);
|
|
256
|
+
const safeMsg = safeAntigravityHttpErrorMessage(upstream.status, text);
|
|
257
|
+
if (upstream.status >= 400 && upstream.status < 500) {
|
|
258
|
+
return formatErrorResponse(upstream.status, "upstream_error", safeMsg);
|
|
259
|
+
}
|
|
260
|
+
return formatErrorResponse(502, "upstream_error", safeMsg);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
let json: Record<string, unknown>;
|
|
264
|
+
try {
|
|
265
|
+
json = JSON.parse(new TextDecoder().decode(payload)) as Record<string, unknown>;
|
|
266
|
+
} catch {
|
|
267
|
+
return formatErrorResponse(502, "upstream_error", "CCA image response was not valid JSON");
|
|
268
|
+
}
|
|
269
|
+
const resp = (json.response ?? json) as {
|
|
270
|
+
candidates?: { content?: { parts?: { inlineData?: { mimeType?: string; data?: string }; text?: string }[] }; finishReason?: string }[];
|
|
271
|
+
promptFeedback?: { blockReason?: string };
|
|
272
|
+
};
|
|
273
|
+
// Safety blocks are permanent for the same prompt — return 400 (non-retryable)
|
|
274
|
+
// instead of 502 (which codex retries up to 5 times, wasting paid quota on a
|
|
275
|
+
// prompt that will never succeed). Two blocking signals exist in the Gemini
|
|
276
|
+
// API: promptFeedback.blockReason (prompt rejected before generation) and
|
|
277
|
+
// candidate.finishReason (generation cut off by a content filter).
|
|
278
|
+
const blockReason = resp.promptFeedback?.blockReason;
|
|
279
|
+
if (typeof blockReason === "string" && blockReason.trim()) {
|
|
280
|
+
return formatErrorResponse(400, "invalid_request_error", `CCA image generation blocked by safety filter (promptFeedback.blockReason: ${blockReason})`);
|
|
281
|
+
}
|
|
282
|
+
const candidate = resp.candidates?.[0];
|
|
283
|
+
const finishReason = candidate?.finishReason;
|
|
284
|
+
if (typeof finishReason === "string" && CCA_BLOCKING_FINISH_REASONS.has(finishReason)) {
|
|
285
|
+
return formatErrorResponse(400, "invalid_request_error", `CCA image generation blocked by safety filter (finishReason: ${finishReason})`);
|
|
286
|
+
}
|
|
287
|
+
const parts = candidate?.content?.parts;
|
|
288
|
+
if (!Array.isArray(parts)) {
|
|
289
|
+
return formatErrorResponse(502, "upstream_error", "CCA image response had no valid parts array");
|
|
290
|
+
}
|
|
291
|
+
const images: { b64_json: string }[] = [];
|
|
292
|
+
for (const part of parts) {
|
|
293
|
+
if (!part || typeof part !== "object") continue;
|
|
294
|
+
const data = part.inlineData?.data;
|
|
295
|
+
if (typeof data !== "string" || data.length === 0) continue;
|
|
296
|
+
if (data.length > MAX_ENCODED_BYTES_PER_IMAGE) {
|
|
297
|
+
return formatErrorResponse(502, "upstream_error", "CCA image payload exceeds per-image size cap");
|
|
298
|
+
}
|
|
299
|
+
try {
|
|
300
|
+
decodeValidatedImageBase64(data);
|
|
301
|
+
} catch {
|
|
302
|
+
return formatErrorResponse(502, "upstream_error", "CCA image payload failed base64/magic validation");
|
|
303
|
+
}
|
|
304
|
+
images.push({ b64_json: data });
|
|
305
|
+
}
|
|
306
|
+
if (images.length === 0) {
|
|
307
|
+
return formatErrorResponse(502, "upstream_error", "CCA image model returned no image data");
|
|
308
|
+
}
|
|
309
|
+
// Only `{created, data:[{b64_json}]}` is returned — no token, projectId, or
|
|
310
|
+
// upstream metadata leak through. The Authorization header is consumed by the
|
|
311
|
+
// fetch above and never copied onto this Response.
|
|
312
|
+
return new Response(JSON.stringify({ created: Math.floor(Date.now() / 1000), data: images }), {
|
|
313
|
+
status: 200,
|
|
314
|
+
headers: { "content-type": "application/json" },
|
|
315
|
+
});
|
|
316
|
+
} finally {
|
|
317
|
+
linkedSignal.cleanup();
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
45
321
|
export async function handleImages(
|
|
46
322
|
req: Request,
|
|
47
323
|
config: OcxConfig,
|
|
@@ -53,11 +329,18 @@ export async function handleImages(
|
|
|
53
329
|
return formatErrorResponse(400, "invalid_request_error", candidates.error);
|
|
54
330
|
}
|
|
55
331
|
const explicitKeyedProvider = config.images?.provider !== undefined && candidates.keyed !== undefined;
|
|
332
|
+
// Admission bearer is valid proxy auth (requireApiAuth already passed) but must never be
|
|
333
|
+
// forwarded as OpenAI ChatGPT credentials. When the caller sent it, skip OpenAI forward
|
|
334
|
+
// and allow CCA / keyed paths instead of rejecting the whole request.
|
|
335
|
+
let skipOpenAiForwardForAdmissionBearer = false;
|
|
56
336
|
if (!explicitKeyedProvider) {
|
|
57
337
|
try { validateForwardAdmissionCredential(req.headers, config); }
|
|
58
338
|
catch (err) {
|
|
59
|
-
if (err instanceof ForwardAdmissionCredentialError)
|
|
60
|
-
|
|
339
|
+
if (err instanceof ForwardAdmissionCredentialError) {
|
|
340
|
+
skipOpenAiForwardForAdmissionBearer = true;
|
|
341
|
+
} else {
|
|
342
|
+
throw err;
|
|
343
|
+
}
|
|
61
344
|
}
|
|
62
345
|
}
|
|
63
346
|
let body: unknown;
|
|
@@ -69,15 +352,19 @@ export async function handleImages(
|
|
|
69
352
|
const model = (body as { model?: unknown } | null)?.model;
|
|
70
353
|
if (typeof model === "string" && model) logCtx.model = model;
|
|
71
354
|
|
|
72
|
-
|
|
355
|
+
const canUseOpenAiForward = !skipOpenAiForwardForAdmissionBearer && candidates.forwardCandidates.length > 0;
|
|
356
|
+
|
|
357
|
+
if (!canUseOpenAiForward && !candidates.keyed) {
|
|
358
|
+
const ccaResponse = await tryCcaImageGeneration(body, config, logCtx, req.signal, endpoint);
|
|
359
|
+
if (ccaResponse) return ccaResponse;
|
|
73
360
|
// 400, not 5xx: codex retries every 5xx up to 5 total attempts, and this is a permanent
|
|
74
361
|
// configuration state that must surface on the first attempt.
|
|
75
362
|
return formatErrorResponse(
|
|
76
363
|
400,
|
|
77
364
|
"invalid_request_error",
|
|
78
|
-
"Built-in image generation needs an OpenAI upstream (ChatGPT login or an OpenAI API-key provider)
|
|
79
|
-
+ "
|
|
80
|
-
+ "
|
|
365
|
+
"Built-in image generation needs an OpenAI upstream (ChatGPT login or an OpenAI API-key provider) "
|
|
366
|
+
+ "or a logged-in Google Antigravity (Cloud Code Assist) provider, "
|
|
367
|
+
+ "but none is configured in opencodex. Add a provider or disable the tool with `codex features disable image_generation`.",
|
|
81
368
|
);
|
|
82
369
|
}
|
|
83
370
|
|
|
@@ -86,7 +373,7 @@ export async function handleImages(
|
|
|
86
373
|
// 429 image_gen while api.openai.com sits idle).
|
|
87
374
|
let forward: Awaited<ReturnType<typeof resolveFirstUsableOpenAiSidecar>>;
|
|
88
375
|
let forwardAuthError: Response | undefined;
|
|
89
|
-
if (
|
|
376
|
+
if (canUseOpenAiForward) {
|
|
90
377
|
try {
|
|
91
378
|
forward = await resolveFirstUsableOpenAiSidecar(candidates.forwardCandidates, req.headers, config);
|
|
92
379
|
if (forward) logCtx.provider = formatCodexProviderForLog(forward.providerName, codexLogAccountId(forward.authContext), config);
|
|
@@ -116,8 +403,12 @@ export async function handleImages(
|
|
|
116
403
|
// The ChatGPT codex backend takes bare paths (matches the adapter's `${baseUrl}/responses`).
|
|
117
404
|
url = `${provider.baseUrl}/images/${endpoint}`;
|
|
118
405
|
} else if (forwardAuthError) {
|
|
119
|
-
//
|
|
120
|
-
//
|
|
406
|
+
// Before surfacing the OpenAI auth failure, try CCA — the user may have a
|
|
407
|
+
// valid Google Antigravity login even though their OpenAI pool is broken.
|
|
408
|
+
const ccaResponse = await tryCcaImageGeneration(body, config, logCtx, req.signal, endpoint);
|
|
409
|
+
if (ccaResponse) return ccaResponse;
|
|
410
|
+
// No CCA either: a configured OpenAI pool mode owns its authentication failure.
|
|
411
|
+
// Do not hide a broken/expired pool behind separately billed API-key image generation.
|
|
121
412
|
return forwardAuthError;
|
|
122
413
|
} else if (candidates.keyed) {
|
|
123
414
|
const { provider, apiKey, providerName } = candidates.keyed;
|
|
@@ -127,6 +418,9 @@ export async function handleImages(
|
|
|
127
418
|
// Keyed providers tolerate baseUrl with or without /v1 (mirrors openai-responses.ts).
|
|
128
419
|
url = `${provider.baseUrl.replace(/\/v1\/?$/, "")}/v1/images/${endpoint}`;
|
|
129
420
|
} else {
|
|
421
|
+
// No usable OpenAI credential — try CCA before giving up.
|
|
422
|
+
const ccaResponse = await tryCcaImageGeneration(body, config, logCtx, req.signal, endpoint);
|
|
423
|
+
if (ccaResponse) return ccaResponse;
|
|
130
424
|
return formatErrorResponse(
|
|
131
425
|
401,
|
|
132
426
|
"authentication_error",
|