mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-12-05 00:47:15 +08:00
- Batch A: fix ObserveAntigravitySafetySignals for results[]/embeddingVerdicts/numeric 2/snake_case with structured logrus fields, align used_claude_conservative OR-latch and subagent_type underscore sanitization, unify Anthropic model detection (claude/fable-/opus-/sonnet-/haiku-) across all 11 core sites with C4 linear adjacent-user merge and unified signature provider/cache group resolution, add legObservedPayload continuation retry guard, strip request.stream/snake_case/duplicate toolConfig, and cap non-2xx/unary response reads - Batch B: enforce 1 MiB OAuth refresh body cap and pre-RTT expiry, add compare-and-delete invalidateAICodeAccessToken on AICode 401 and broad refresh, harden sdk/cliproxy AICode token minter (Antigravity User-Agent, pre-RTT, non-cancelable singleflight, 400 invalid_grant AuthError, 401 retry-once, stale metadata suppression isolated from broad-bearer suppression), tighten status-code-aware NEW-06 scope gating, and pool/cache /v1internal:rewriteUri grounding URL resolution - Batch C: complete 4 hard-quota 429 substrings, 240s retry ceiling, numeric gRPC 8/14 and missing error.status handling, retry-after-ms header precedence, PayGo X-Goog-User-Project omission helper, 5 snake_case GenerationConfig aliases, BlockReason 5->6 normalization, read-only post-FinalizePayloadDoc GOOGLE_ONE_HELIUM rejection, remaining Mendel cutover flags and rate-limited sign-out-missing-aicode-scope warnings, tieredModelIds + M-04 disabled model filtering, telemetry JSON label scrubbing across all request types, shared bare-token/plt redaction, and allowlisted OAuth error parsing preserving typed 403 TOS/validation metadata - Batch D: reject empty access_token and non-positive expires_in with proxy/epoch-scoped OAuth singleflight, wire AdaptiveThinking/ThoughtCirculation/DeferredToolLoading/TieredModelIDs through sdk/cliproxy, harden credits quota admission guards, map FormatAntigravity to "antigravity" with mixed-pool LCP mirroring and dual rollback generations, upgrade signature ownership to Get() LRU recency + Home KV SSOT with millisecond PX backfill and NX lease protection, and add bounded 32-leg unary Execute continuation loop
2001 lines
76 KiB
Go
2001 lines
76 KiB
Go
package executor
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/MoeForge/moego/ojson"
|
|
"github.com/google/uuid"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/internal/auth/antigravity"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/internal/cache"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/internal/misc"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/internal/registry"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps"
|
|
antigravitygemini "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/antigravity/gemini"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/internal/util"
|
|
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
|
|
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
|
cliproxysession "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session"
|
|
sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
type antigravityRequestOptionsContextKey struct{}
|
|
|
|
type antigravityRequestOptions struct {
|
|
headers http.Header
|
|
preserveSafetySettings bool
|
|
crossAccountFailover bool
|
|
isNativeContinuation bool
|
|
}
|
|
|
|
func withAntigravityRequestOptions(ctx context.Context, opts cliproxyexecutor.Options, req cliproxyexecutor.Request) context.Context {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
source := opts.OriginalRequest
|
|
if len(source) == 0 {
|
|
source = req.Payload
|
|
}
|
|
preserveSafety := opts.SourceFormat == sdktranslator.FormatAntigravity
|
|
if !preserveSafety && opts.SourceFormat == sdktranslator.FormatGemini {
|
|
preserveSafety = ojson.GetBytesNoCopy(source, "safetySettings").Exists() ||
|
|
ojson.GetBytesNoCopy(source, "request.safetySettings").Exists()
|
|
}
|
|
isNativeContinuation := (opts.SourceFormat == sdktranslator.FormatGemini || opts.SourceFormat == sdktranslator.FormatAntigravity) &&
|
|
helps.HasAntigravityContinuationTokenBytes(source)
|
|
return context.WithValue(ctx, antigravityRequestOptionsContextKey{}, antigravityRequestOptions{
|
|
headers: opts.Headers,
|
|
preserveSafetySettings: preserveSafety,
|
|
crossAccountFailover: isAntigravityCrossAccountFailover(opts, req),
|
|
isNativeContinuation: isNativeContinuation,
|
|
})
|
|
}
|
|
|
|
func antigravityRequestOptionsFromContext(ctx context.Context) antigravityRequestOptions {
|
|
if ctx == nil {
|
|
return antigravityRequestOptions{}
|
|
}
|
|
v, _ := ctx.Value(antigravityRequestOptionsContextKey{}).(antigravityRequestOptions)
|
|
return v
|
|
}
|
|
|
|
func isAntigravityAgentRequestType(reqType string) bool {
|
|
switch strings.TrimSpace(reqType) {
|
|
case "agent", "custom_agent":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func isValidAntigravityRequestType(reqType string) bool {
|
|
switch strings.TrimSpace(reqType) {
|
|
case "chat", "eval", "plan", "agent", "mquery", "command", "fastapply", "checkpoint",
|
|
"custom_agent", "context_check", "agent_monitoring", "antigravity_review", "generate_commit_message":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func isAntigravityPromptCacheKeepaliveDoc(doc *ojson.Doc) bool {
|
|
return helps.IsAntigravityPromptCacheKeepaliveDoc(doc)
|
|
}
|
|
|
|
func isAntigravityPromptCacheKeepalivePayload(raw []byte) bool {
|
|
return cliproxysession.IsAntigravityPromptCacheKeepalivePayload(raw)
|
|
}
|
|
|
|
func antigravityPayloadHasUsageMetadata(raw []byte) bool {
|
|
if len(raw) == 0 {
|
|
return false
|
|
}
|
|
if u := ojson.GetBytesNoCopy(raw, "response.usageMetadata"); u.Exists() && u.Type != ojson.Null {
|
|
return true
|
|
}
|
|
if u := ojson.GetBytesNoCopy(raw, "usageMetadata"); u.Exists() && u.Type != ojson.Null {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
type antigravityPreparedRequest struct {
|
|
model helps.AntigravityRequestModel
|
|
auth *cliproxyauth.Auth
|
|
token string
|
|
originalPayload []byte
|
|
originalTranslated []byte
|
|
translated []byte
|
|
cooldownRejected bool
|
|
}
|
|
|
|
func (e *AntigravityExecutor) prepareAntigravityRequest(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, baseModel string, stream, countTokens bool) (antigravityPreparedRequest, error) {
|
|
source := opts.OriginalRequest
|
|
if len(source) == 0 {
|
|
source = req.Payload
|
|
}
|
|
from, to := opts.SourceFormat, sdktranslator.FormatAntigravity
|
|
prepared := antigravityPreparedRequest{auth: auth}
|
|
useCredits := !countTokens && antigravityShouldBypassShortCooldown(ctx, e.cfg)
|
|
rejectCooldown := func(model string, err error) error {
|
|
prepared.cooldownRejected = true
|
|
if model != baseModel {
|
|
return cliproxyauth.RejectAntigravityTarget(err)
|
|
}
|
|
return err
|
|
}
|
|
translate := func(credential *cliproxyauth.Auth) error {
|
|
translateCtx := cache.WithSignatureCacheScope(ctx, antigravitySignatureCacheScope(credential))
|
|
model := helps.SelectAntigravityRequestModel(translateCtx, e.cfg, credential, req.Model, baseModel, from.String(), source, countTokens)
|
|
if model.ID != baseModel {
|
|
if errCooldown := cliproxyauth.CheckAntigravityTargetModel(ctx, credential, model.ID, time.Now(), useCredits); errCooldown != nil {
|
|
return rejectCooldown(model.ID, errCooldown)
|
|
}
|
|
} else if useCredits {
|
|
if errCooldown := cliproxyauth.CheckAntigravityDirectCreditsModel(ctx, credential, model.ID, time.Now()); errCooldown != nil {
|
|
prepared.cooldownRejected = true
|
|
return cliproxyauth.RejectAntigravityTarget(errCooldown)
|
|
}
|
|
}
|
|
if errCooldown := e.checkAntigravityRequestCooldown(ctx, credential, model.ID, countTokens); errCooldown != nil {
|
|
return rejectCooldown(model.ID, errCooldown)
|
|
}
|
|
original, errValidate := validateAntigravityRequestSignatures(translateCtx, model.ID, from, source)
|
|
if errValidate != nil {
|
|
return errValidate
|
|
}
|
|
prepared.model, prepared.originalPayload = model, original
|
|
if !countTokens && (from == sdktranslator.FormatGemini || from == sdktranslator.FormatAntigravity) {
|
|
if compact, ok := helps.BuildCompactAntigravityContinuationPayload(original, model.ID); ok {
|
|
prepared.translated = compact
|
|
prepared.originalTranslated = append([]byte(nil), compact...)
|
|
return nil
|
|
}
|
|
}
|
|
envelope := sdktranslator.RequestEnvelope{Format: from, Model: model.ID, Body: original, Stream: stream, ModelInfo: model.TranslationModelInfo(req, baseModel, from)}
|
|
if countTokens {
|
|
translated := helps.TranslateRequestEnvelopeWithCodexMultiAgentV2(translateCtx, opts.Headers, e.cfg, from, to, envelope)
|
|
if translated.Err != nil {
|
|
return translated.Err
|
|
}
|
|
prepared.translated = translated.Body
|
|
prepared.originalTranslated = append([]byte(nil), translated.Body...)
|
|
return nil
|
|
}
|
|
var errTranslate error
|
|
prepared.originalTranslated, prepared.translated, errTranslate = helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(translateCtx, opts.Headers, e.cfg, from, to, envelope, original, original)
|
|
return errTranslate
|
|
}
|
|
// A translation refusal must precede token refresh and any upstream request.
|
|
if errTranslate := translate(auth); errTranslate != nil {
|
|
return prepared, errTranslate
|
|
}
|
|
token, updatedAuth, errToken := e.ensureAccessToken(ctx, auth)
|
|
if errToken != nil {
|
|
return antigravityPreparedRequest{}, errToken
|
|
}
|
|
if updatedAuth != nil {
|
|
// A changed catalog identity, exclusion policy, or signature scope invalidates this attempt's snapshot.
|
|
if !cliproxyauth.SameAntigravityModelCatalogScope(auth, updatedAuth) || antigravitySignatureCacheScope(auth) != antigravitySignatureCacheScope(updatedAuth) {
|
|
if errTranslate := translate(updatedAuth); errTranslate != nil {
|
|
return prepared, errTranslate
|
|
}
|
|
} else if prepared.model.ID != baseModel {
|
|
if errCooldown := cliproxyauth.CheckAntigravityTargetModel(ctx, updatedAuth, prepared.model.ID, time.Now(), useCredits); errCooldown != nil {
|
|
err := rejectCooldown(prepared.model.ID, errCooldown)
|
|
return prepared, err
|
|
}
|
|
} else if useCredits {
|
|
if errCooldown := cliproxyauth.CheckAntigravityDirectCreditsModel(ctx, updatedAuth, prepared.model.ID, time.Now()); errCooldown != nil {
|
|
prepared.cooldownRejected = true
|
|
return prepared, cliproxyauth.RejectAntigravityTarget(errCooldown)
|
|
}
|
|
}
|
|
prepared.auth = updatedAuth
|
|
}
|
|
prepared.token = token
|
|
if prepared.model.ID != baseModel {
|
|
cliproxyexecutor.SetUpstreamAttemptModel(ctx, prepared.model.ID)
|
|
}
|
|
return prepared, nil
|
|
}
|
|
|
|
func (e *AntigravityExecutor) checkAntigravityRequestCooldown(ctx context.Context, auth *cliproxyauth.Auth, model string, countTokens bool) error {
|
|
if antigravityCoolingDisabled(auth, e.cfg) {
|
|
return nil
|
|
}
|
|
inCooldown, remaining, errCooldown := antigravityIsInShortCooldownRequired(ctx, auth, model, time.Now())
|
|
if errCooldown != nil {
|
|
return homeKVUnavailableStatusErr(errCooldown)
|
|
}
|
|
if inCooldown && (countTokens || !antigravityShouldBypassShortCooldown(ctx, e.cfg)) {
|
|
log.Debugf("antigravity executor: auth %s in short cooldown for model %s (%s remaining), returning 429 to switch auth", antigravityAuthID(auth), model, remaining)
|
|
return statusErr{code: http.StatusTooManyRequests, msg: fmt.Sprintf("auth in short cooldown, %s remaining", remaining), retryAfter: &remaining}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (e *AntigravityExecutor) buildRequest(ctx context.Context, auth *cliproxyauth.Auth, token, modelName string, payload []byte, stream bool, alt, baseURL string, derivedSessionIDs ...string) (*http.Request, error) {
|
|
doc := ojson.NewDoc(payload)
|
|
httpReq, _, err := e.buildRequestDoc(ctx, auth, token, modelName, doc, stream, alt, baseURL, derivedSessionIDs...)
|
|
return httpReq, err
|
|
}
|
|
|
|
func (e *AntigravityExecutor) buildRequestDoc(ctx context.Context, auth *cliproxyauth.Auth, token, modelName string, doc *ojson.Doc, stream bool, alt, baseURL string, derivedSessionIDs ...string) (*http.Request, []byte, error) {
|
|
selection := cliproxyauth.SelectAntigravityModel(ctx, auth, modelName, "", e.cfg)
|
|
return e.buildRequestForModelDoc(ctx, auth, token, selection, doc, stream, alt, baseURL, derivedSessionIDs...)
|
|
}
|
|
|
|
func (e *AntigravityExecutor) buildRequestForModelDoc(ctx context.Context, auth *cliproxyauth.Auth, token string, selection cliproxyauth.AntigravityModelSelection, doc *ojson.Doc, stream bool, alt, baseURL string, derivedSessionIDs ...string) (*http.Request, []byte, error) {
|
|
httpReq, finalPayload, _, errBuild := e.buildRequestForModelDocInternal(ctx, auth, token, selection, doc, stream, alt, baseURL, false, derivedSessionIDs...)
|
|
return httpReq, finalPayload, errBuild
|
|
}
|
|
|
|
func (e *AntigravityExecutor) buildRequestForModelDocWithBase(ctx context.Context, auth *cliproxyauth.Auth, token string, selection cliproxyauth.AntigravityModelSelection, doc *ojson.Doc, stream bool, alt, baseURL string, derivedSessionIDs ...string) (*http.Request, []byte, []byte, error) {
|
|
return e.buildRequestForModelDocInternal(ctx, auth, token, selection, doc, stream, alt, baseURL, true, derivedSessionIDs...)
|
|
}
|
|
|
|
const (
|
|
antigravityAICodeStreamPath = "/v1alpha:streamGenerateContent"
|
|
antigravityAICodeGeneratePath = "/v1alpha:generateContent"
|
|
)
|
|
|
|
type antigravityBuiltRequest struct {
|
|
httpReq *http.Request
|
|
payload []byte
|
|
unfinalizedBase []byte
|
|
canonicalReqPayload []byte
|
|
|
|
usingAICode bool
|
|
aicodeExperimentFlags map[string]bool
|
|
|
|
// Pre-finalized v1internal fallback context (populated when usingAICode == true)
|
|
// so same-request fallback on 403/400 ACCESS_TOKEN_SCOPE_INSUFFICIENT applies
|
|
// v1internal project_id + Claude VALIDATED mode and runs FinalizePayloadDoc
|
|
// cleanly once on the unconfigured base document.
|
|
fallbackBaseURL string
|
|
fallbackToken string
|
|
fallbackUnfinalizedBase []byte
|
|
fallbackApplyValidated bool
|
|
fallbackIsAgent bool
|
|
fallbackStream bool
|
|
fallbackAlt string
|
|
fallbackStagedExperience string
|
|
fallbackDefaultExperience string
|
|
fallbackSuppressPaidCredits bool
|
|
}
|
|
|
|
// stagedExperienceForV1InternalDoc returns the experience to stage onto
|
|
// request.aicode.experience before FinalizePayloadDoc on v1internal fallback
|
|
// and continuation paths so Exist: ["aicode.experience"] rules match
|
|
// identically to v1alpha without leaking aicode onto the wire.
|
|
func (b antigravityBuiltRequest) stagedExperienceForV1InternalDoc(doc *ojson.Doc) string {
|
|
if exp := strings.TrimSpace(b.fallbackStagedExperience); exp != "" {
|
|
return exp
|
|
}
|
|
if helps.AntigravityDocHasInitialPaidCredits(doc) {
|
|
if defExp := strings.TrimSpace(b.fallbackDefaultExperience); defExp != "" {
|
|
return defExp
|
|
}
|
|
return helps.AntigravityAICodeFallbackCreditExperience
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (b antigravityBuiltRequest) canonicalPayload() []byte {
|
|
if len(b.canonicalReqPayload) > 0 {
|
|
return b.canonicalReqPayload
|
|
}
|
|
return b.payload
|
|
}
|
|
|
|
// resolveAntigravityAICodeTarget resolves the effective AICode endpoint mode,
|
|
// whether v1alpha inference should be attempted, and whether Mendel preprod
|
|
// routing applies. USE_AICODE env overrides antigravity.aicode-endpoint-mode;
|
|
// "auto" mode is gated by Mendel flags (use-aicode-jetski-endpoint,
|
|
// enable-inference-traffic-migration, and use-aicode-preprod-endpoint) loaded
|
|
// into selection.
|
|
func resolveAntigravityAICodeTarget(cfg *config.Config, _ *cliproxyauth.Auth, selection cliproxyauth.AntigravityModelSelection) (mode string, useAICode bool, usePreprod bool) {
|
|
if envVal := strings.TrimSpace(os.Getenv("USE_AICODE")); envVal != "" {
|
|
if b, errParse := strconv.ParseBool(envVal); errParse == nil {
|
|
if b {
|
|
return config.AntigravityAICodeEndpointModeV1Alpha, true, selection.AICodeFlagsLoaded && selection.AICodePreprodEnabled
|
|
}
|
|
return config.AntigravityAICodeEndpointModeV1Internal, false, false
|
|
}
|
|
}
|
|
if cfg != nil {
|
|
if norm, ok := config.NormalizeAntigravityAICodeEndpointMode(cfg.Antigravity.AICodeEndpointMode); ok {
|
|
switch norm {
|
|
case config.AntigravityAICodeEndpointModeV1Alpha:
|
|
return norm, true, selection.AICodeFlagsLoaded && selection.AICodePreprodEnabled
|
|
case config.AntigravityAICodeEndpointModeAuto:
|
|
usePreprod = selection.AICodeFlagsLoaded && selection.AICodePreprodEnabled
|
|
trafficMigration := selection.AICodeTrafficMigrationEnabled ||
|
|
selection.AICodeExperimentFlags[cliproxyauth.AntigravityAICodeFlagEnableInferenceTrafficMigration]
|
|
useAICode = selection.AICodeFlagsLoaded && (selection.AICodeJetskiEnabled || trafficMigration || selection.AICodePreprodEnabled)
|
|
return norm, useAICode, usePreprod
|
|
}
|
|
}
|
|
}
|
|
return config.AntigravityAICodeEndpointModeV1Internal, false, false
|
|
}
|
|
|
|
func resolveAntigravityAICodeBaseURL(auth *cliproxyauth.Auth) (string, bool) {
|
|
return helps.ResolveAntigravityAICodeBaseURLForAuth(os.Getenv("AICODE_ENDPOINT_URL"), auth)
|
|
}
|
|
|
|
func resolveAntigravityAICodeBaseURLWithPreprod(auth *cliproxyauth.Auth, usePreprod bool) (string, bool) {
|
|
return helps.ResolveAntigravityAICodeBaseURLWithPreprodForAuth(os.Getenv("AICODE_ENDPOINT_URL"), auth, usePreprod)
|
|
}
|
|
|
|
func resolveAntigravityCCPAFallbackBaseURL(auth *cliproxyauth.Auth, explicitBaseURL string) string {
|
|
aicodeBaseURL, _ := resolveAntigravityAICodeBaseURL(auth)
|
|
return helps.ResolveAntigravityCCPAFallbackBaseURL(explicitBaseURL, resolveCustomAntigravityBaseURL(auth), aicodeBaseURL, antigravityBaseURLDaily)
|
|
}
|
|
|
|
func (e *AntigravityExecutor) buildAntigravityUpstreamHTTPRequest(
|
|
ctx context.Context,
|
|
auth *cliproxyauth.Auth,
|
|
base string,
|
|
path string,
|
|
stream bool,
|
|
alt string,
|
|
token string,
|
|
payload []byte,
|
|
reqOpts antigravityRequestOptions,
|
|
quotaProject string,
|
|
extraHeaders http.Header,
|
|
) (*http.Request, error) {
|
|
fullURL := helps.FormatAntigravityRequestURL(base, path, stream, alt)
|
|
var (
|
|
bodyReader io.Reader = bytes.NewReader(payload)
|
|
payloadLog []byte
|
|
)
|
|
if e.cfg != nil && e.cfg.RequestLog {
|
|
payloadLog = append([]byte(nil), payload...)
|
|
}
|
|
|
|
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bodyReader)
|
|
if errReq != nil {
|
|
return nil, errReq
|
|
}
|
|
// Deliberately no httpReq.Close: the native Antigravity client omits the
|
|
// Connection header and keeps its HTTP/1.1 connections alive, so forcing
|
|
// "Connection: close" would both deviate from that fingerprint and defeat the
|
|
// shared connection pool by discarding every established TCP + TLS session.
|
|
httpReq.Header.Set("Content-Type", "application/json")
|
|
httpReq.Header.Set("Authorization", "Bearer "+token)
|
|
httpReq.Header.Set("User-Agent", resolveUserAgent(auth))
|
|
if host := resolveHost(base); host != "" {
|
|
httpReq.Host = host
|
|
}
|
|
if qp := strings.TrimSpace(quotaProject); qp != "" && !strings.ContainsAny(qp, "\r\n") &&
|
|
!helps.ShouldOmitAntigravityUserProjectHeader(auth, fullURL) {
|
|
httpReq.Header.Set("X-Goog-User-Project", qp)
|
|
}
|
|
helps.ForwardAntigravityNativeHeaders(httpReq.Header, reqOpts.headers)
|
|
for name, values := range extraHeaders {
|
|
for _, value := range values {
|
|
if trimmed := strings.TrimSpace(value); trimmed != "" && !strings.ContainsAny(trimmed, "\r\n") {
|
|
httpReq.Header.Set(name, trimmed)
|
|
}
|
|
}
|
|
}
|
|
var attrs map[string]string
|
|
if auth != nil {
|
|
attrs = auth.Attributes
|
|
}
|
|
util.ApplyCustomHeadersFromAttrs(httpReq, attrs)
|
|
if helps.ShouldOmitAntigravityUserProjectHeader(auth, fullURL) {
|
|
httpReq.Header.Del("X-Goog-User-Project")
|
|
}
|
|
|
|
var authID, authLabel, authType, authValue string
|
|
if auth != nil {
|
|
authID = auth.ID
|
|
authLabel = auth.Label
|
|
authType, authValue = auth.AccountInfo()
|
|
}
|
|
helps.RecordAPIRequest(ctx, e.cfg, helps.UpstreamRequestLog{
|
|
URL: fullURL,
|
|
Method: http.MethodPost,
|
|
Headers: httpReq.Header.Clone(),
|
|
Body: payloadLog,
|
|
Provider: e.Identifier(),
|
|
AuthID: authID,
|
|
AuthLabel: authLabel,
|
|
AuthType: authType,
|
|
AuthValue: authValue,
|
|
})
|
|
return httpReq, nil
|
|
}
|
|
|
|
// validateAntigravityPostFinalizeCredits performs read-only post-finalization
|
|
// credit validation so user payload overrides that re-inject non-CreditType
|
|
// upgrade enum GOOGLE_ONE_HELIUM (4) are rejected locally with a non-retryable
|
|
// HTTP 400 error instead of mutating user rules or transmitting invalid credits.
|
|
func validateAntigravityPostFinalizeCredits(ctx context.Context, finalizedDoc, wireDoc *ojson.Doc) error {
|
|
if finalizedDoc != nil && !helps.AntigravityPayloadFiltersCredits(ctx) {
|
|
if errCredits := helps.ValidateAntigravityFinalCreditTypesDoc(finalizedDoc); errCredits != nil {
|
|
return statusErr{
|
|
code: http.StatusBadRequest,
|
|
msg: errCredits.Error(),
|
|
requestScoped: true,
|
|
requestStop: true,
|
|
}
|
|
}
|
|
}
|
|
if wireDoc != nil {
|
|
if errWire := helps.ValidateAntigravityFinalCreditTypesDoc(wireDoc); errWire != nil {
|
|
return statusErr{
|
|
code: http.StatusBadRequest,
|
|
msg: errWire.Error(),
|
|
requestScoped: true,
|
|
requestStop: true,
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (e *AntigravityExecutor) buildFallbackV1InternalRequest(ctx context.Context, auth *cliproxyauth.Auth, built antigravityBuiltRequest) (*http.Request, []byte, []byte, error) {
|
|
projectID, errProject := e.projectIDForRequest(ctx, auth, built.fallbackToken, true)
|
|
if errProject != nil {
|
|
return nil, nil, nil, errProject
|
|
}
|
|
fbDoc := ojson.NewDoc(built.fallbackUnfinalizedBase)
|
|
helps.HoistAntigravityAICodeInitialCreditsDoc(fbDoc)
|
|
helps.StripAntigravityAICodeOnlyFieldsDoc(fbDoc)
|
|
helps.SetStringIfDifferentDoc(fbDoc, "project", projectID)
|
|
if built.fallbackApplyValidated {
|
|
canonicalizeAntigravityToolConfigForValidatedDoc(fbDoc)
|
|
_ = fbDoc.Set("request.toolConfig.functionCallingConfig.mode", "VALIDATED")
|
|
}
|
|
hadInitialPaidCredits := helps.AntigravityDocHasInitialPaidCredits(fbDoc)
|
|
if built.fallbackSuppressPaidCredits {
|
|
fbDoc = helps.SuppressAntigravityV1InternalPaidCreditsDoc(fbDoc)
|
|
}
|
|
fbUnfinalizedBase := bytes.Clone(fbDoc.Bytes())
|
|
fbStagedCredits := helps.StageAntigravityV1InternalCreditsDoc(fbDoc, built.stagedExperienceForV1InternalDoc(fbDoc))
|
|
fbStagedCredits.SuppressedInitialPaidCredits = built.fallbackSuppressPaidCredits && hadInitialPaidCredits
|
|
helps.FinalizePayloadDoc(ctx, fbDoc)
|
|
fbIsAgent := built.fallbackIsAgent
|
|
if fbIsAgent {
|
|
requestType := fbDoc.Get("requestType")
|
|
fbIsAgent = !requestType.Exists() || isAntigravityAgentRequestType(requestType.String())
|
|
}
|
|
fbWireDoc := helps.FrameAntigravityV1InternalDocForContext(ctx, fbDoc, fbStagedCredits)
|
|
if errCredits := validateAntigravityPostFinalizeCredits(ctx, fbDoc, fbWireDoc); errCredits != nil {
|
|
return nil, nil, nil, errCredits
|
|
}
|
|
fbPayload := helps.SerializeAntigravityPayload(fbWireDoc, fbIsAgent)
|
|
|
|
path := antigravityGeneratePath
|
|
if built.fallbackStream {
|
|
path = antigravityStreamPath
|
|
}
|
|
reqOpts := antigravityRequestOptionsFromContext(ctx)
|
|
ccpaBase := resolveAntigravityCCPAFallbackBaseURL(auth, built.fallbackBaseURL)
|
|
httpReq, errReq := e.buildAntigravityUpstreamHTTPRequest(
|
|
ctx,
|
|
auth,
|
|
ccpaBase,
|
|
path,
|
|
built.fallbackStream,
|
|
built.fallbackAlt,
|
|
built.fallbackToken,
|
|
fbPayload,
|
|
reqOpts,
|
|
"",
|
|
nil,
|
|
)
|
|
if errReq != nil {
|
|
return nil, nil, nil, errReq
|
|
}
|
|
return httpReq, fbPayload, fbUnfinalizedBase, nil
|
|
}
|
|
|
|
func (e *AntigravityExecutor) buildContinuationV1InternalRequest(
|
|
ctx context.Context,
|
|
auth *cliproxyauth.Auth,
|
|
built antigravityBuiltRequest,
|
|
leg1BaseDoc *ojson.Doc,
|
|
continuationToken string,
|
|
modelID string,
|
|
) (*http.Request, []byte, *ojson.Doc, error) {
|
|
projectID, errProject := e.projectIDForRequest(ctx, auth, built.fallbackToken, true)
|
|
if errProject != nil {
|
|
return nil, nil, nil, errProject
|
|
}
|
|
// Build an updated unfinalized CCPA base doc so leg 3+ retains project_id,
|
|
// Claude VALIDATED mode, and CCPA envelope fields after switching from v1alpha.
|
|
var baseRaw []byte
|
|
if leg1BaseDoc != nil && leg1BaseDoc.Len() > 0 {
|
|
baseRaw = leg1BaseDoc.Bytes()
|
|
} else {
|
|
baseRaw = built.fallbackUnfinalizedBase
|
|
}
|
|
ccpaBaseDoc := ojson.NewDoc(baseRaw)
|
|
helps.HoistAntigravityAICodeInitialCreditsDoc(ccpaBaseDoc)
|
|
helps.StripAntigravityAICodeOnlyFieldsDoc(ccpaBaseDoc)
|
|
helps.SetStringIfDifferentDoc(ccpaBaseDoc, "project", projectID)
|
|
if built.fallbackApplyValidated {
|
|
canonicalizeAntigravityToolConfigForValidatedDoc(ccpaBaseDoc)
|
|
_ = ccpaBaseDoc.Set("request.toolConfig.functionCallingConfig.mode", "VALIDATED")
|
|
}
|
|
if built.fallbackSuppressPaidCredits {
|
|
ccpaBaseDoc = helps.SuppressAntigravityV1InternalPaidCreditsDoc(ccpaBaseDoc)
|
|
}
|
|
contDoc := helps.BuildAntigravityContinuationDoc(ccpaBaseDoc, continuationToken)
|
|
contStagedCredits := helps.StageAntigravityV1InternalCreditsDoc(contDoc, built.stagedExperienceForV1InternalDoc(contDoc))
|
|
helps.FinalizePayloadDoc(ctx, contDoc)
|
|
if !helps.HasAntigravityWireContinuationTokenDoc(contDoc) {
|
|
return nil, nil, nil, statusErr{code: http.StatusBadRequest, msg: "antigravity continuation aborted: continuationToken removed by payload configuration"}
|
|
}
|
|
legIsAgent := helps.AntigravityPayloadIsAgentOrder(contDoc, modelID)
|
|
contWireDoc := helps.FrameAntigravityV1InternalDocForContext(ctx, contDoc, contStagedCredits)
|
|
if errCredits := validateAntigravityPostFinalizeCredits(ctx, contDoc, contWireDoc); errCredits != nil {
|
|
return nil, nil, nil, errCredits
|
|
}
|
|
contPayload := helps.SerializeAntigravityPayload(contWireDoc, legIsAgent)
|
|
reqOpts := antigravityRequestOptionsFromContext(ctx)
|
|
ccpaBase := resolveAntigravityCCPAFallbackBaseURL(auth, built.fallbackBaseURL)
|
|
path := antigravityGeneratePath
|
|
if built.fallbackStream {
|
|
path = antigravityStreamPath
|
|
}
|
|
httpReq, errReq := e.buildAntigravityUpstreamHTTPRequest(
|
|
ctx,
|
|
auth,
|
|
ccpaBase,
|
|
path,
|
|
built.fallbackStream,
|
|
built.fallbackAlt,
|
|
built.fallbackToken,
|
|
contPayload,
|
|
reqOpts,
|
|
"",
|
|
nil,
|
|
)
|
|
if errReq != nil {
|
|
return nil, nil, nil, errReq
|
|
}
|
|
return httpReq, contPayload, ccpaBaseDoc, nil
|
|
}
|
|
|
|
func (e *AntigravityExecutor) buildRequestForModelDocRouted(
|
|
ctx context.Context,
|
|
auth *cliproxyauth.Auth,
|
|
token string,
|
|
selection cliproxyauth.AntigravityModelSelection,
|
|
doc *ojson.Doc,
|
|
stream bool,
|
|
alt, baseURL string,
|
|
captureUnfinalizedBase bool,
|
|
derivedSessionIDs ...string,
|
|
) (antigravityBuiltRequest, error) {
|
|
var out antigravityBuiltRequest
|
|
if token == "" {
|
|
return out, statusErr{code: http.StatusUnauthorized, msg: "missing access token"}
|
|
}
|
|
if doc == nil {
|
|
doc = ojson.NewDoc(nil)
|
|
}
|
|
// Structurally deduplicate duplicate object keys (first-wins) across payload
|
|
// containers before reading fields, applying the agent envelope, stripping
|
|
// service_account, or invoking FinalizePayloadDoc.
|
|
helps.DeduplicateAntigravityPayloadObjectKeysDoc(doc)
|
|
_ = doc.Delete("request.stream")
|
|
|
|
ccpaBase := resolveAntigravityCCPAFallbackBaseURL(auth, baseURL)
|
|
|
|
reqOpts := antigravityRequestOptionsFromContext(ctx)
|
|
// Continuation leg 2+ requests carry continuationToken and explicit VALIDATED
|
|
// function-calling requests rely on FunctionCallingConfig.Mode=VALIDATED;
|
|
// both are supported on v1internal CCPA only (absent from aicode v1alpha protos).
|
|
isContinuationReq := helps.HasAntigravityContinuationTokenDoc(doc) || reqOpts.isNativeContinuation
|
|
hasExplicitValidatedMode := antigravityToolChoiceModeIsValidatedDoc(doc)
|
|
_, wantAICode, usePreprod := resolveAntigravityAICodeTarget(e.cfg, auth, selection)
|
|
useAICode := false
|
|
aicodeToken := ""
|
|
if !isContinuationReq && !hasExplicitValidatedMode && wantAICode {
|
|
if !antigravityHasAICodeInferenceEntitlement(auth, selection, usePreprod) {
|
|
log.Debugf("antigravity executor: missing verified paidTier for %s, routing via v1internal", antigravityAuthID(auth))
|
|
} else if e.isAICodeLocationBlocked(auth) {
|
|
log.Debugf("antigravity executor: aicode location-blocked for %s, routing via v1internal", antigravityAuthID(auth))
|
|
} else if mintedToken, errMint := e.ensureAICodeAccessTokenWithFlags(ctx, auth, selection.AICodeExperimentFlags); errMint == nil && strings.TrimSpace(mintedToken) != "" {
|
|
useAICode = true
|
|
aicodeToken = mintedToken
|
|
} else if errors.Is(errMint, errAICodeScopeMissing) {
|
|
log.Debugf("antigravity executor: auth/aicode scope unavailable for %s, falling back to v1internal", antigravityAuthID(auth))
|
|
} else if errMint != nil {
|
|
return out, errMint
|
|
}
|
|
}
|
|
|
|
var projectID string
|
|
if useAICode {
|
|
projectID = antigravityProjectIDFromAuth(auth)
|
|
} else {
|
|
var errProject error
|
|
projectID, errProject = e.projectIDForRequest(ctx, auth, token, wantAICode)
|
|
if errProject != nil {
|
|
return out, errProject
|
|
}
|
|
}
|
|
modelName := selection.ID
|
|
// Normalize session_id / top-level sessionId and flat top-level labels
|
|
// aliases BEFORE envelope construction so incoming session IDs and caller
|
|
// labels (cascade_id, root_cascade_id, parent_cascade_id) are preserved
|
|
// rather than overwritten by freshly generated defaults.
|
|
helps.CanonicalizeAntigravitySessionIDDoc(doc)
|
|
helps.CanonicalizeAntigravityLabelsDoc(doc)
|
|
isAgent := geminiToAntigravityDocForAuthWithFailover(doc, selection, projectID, auth, reqOpts.preserveSafetySettings, reqOpts.crossAccountFailover, derivedSessionIDs...)
|
|
if useAICode {
|
|
if !reqOpts.preserveSafetySettings {
|
|
_ = doc.Delete("request.safety_settings")
|
|
_ = doc.Delete("safetySettings")
|
|
_ = doc.Delete("safety_settings")
|
|
}
|
|
// Fold snake_case and top-level duplicate aliases into canonical request.*
|
|
// paths BEFORE built-in transforms and FinalizePayloadDoc so user payload
|
|
// rules operate on a single canonical container and v1alpha framing cannot
|
|
// resurrect deleted fields.
|
|
helps.CanonicalizeAntigravityAICodeRequestDoc(doc)
|
|
}
|
|
if !isContinuationReq {
|
|
isContinuationReq = helps.HasAntigravityContinuationTokenDoc(doc)
|
|
}
|
|
promptStructuredOutput := false
|
|
if !isContinuationReq {
|
|
promptStructuredOutput = helps.PrepareAntigravityClaudeStructuredOutputDoc(modelName, doc)
|
|
}
|
|
antigravitygemini.NormalizeAntigravityRequestDoc(doc)
|
|
|
|
lowerModel := strings.ToLower(modelName)
|
|
useAntigravitySchema, isClaudeModel := antigravitySchemaSanitizationFlags(modelName)
|
|
shouldApplyClaudeValidated := false
|
|
|
|
// Continuation leg 2+ requests intentionally omit generationConfig, tools,
|
|
// contents, and systemInstruction; avoid re-synthesizing them.
|
|
if !isContinuationReq {
|
|
// A matched variant limits output using the same catalog as its ID and enum.
|
|
if selection.MaxOutputTokens > 0 {
|
|
helps.CapAntigravityMaxOutputTokensDoc(doc, selection.MaxOutputTokens, isClaudeModel)
|
|
} else if maxOut, ok := antigravityRequestedMaxOutputTokensDoc(doc); ok {
|
|
modelInfo := registry.LookupModelInfo(modelName, "antigravity")
|
|
if modelInfo == nil && lowerModel != modelName {
|
|
modelInfo = registry.LookupModelInfo(lowerModel, "antigravity")
|
|
}
|
|
if modelInfo != nil && modelInfo.MaxCompletionTokens > 0 && maxOut > modelInfo.MaxCompletionTokens {
|
|
helps.CapAntigravityMaxOutputTokensDoc(doc, modelInfo.MaxCompletionTokens, isClaudeModel)
|
|
}
|
|
}
|
|
if antigravityRequestNeedsSchemaSanitizationDoc(doc) {
|
|
sanitizeAntigravityRequestSchemasForModelDoc(doc, useAntigravitySchema, isClaudeModel)
|
|
}
|
|
if isClaudeModel {
|
|
if !promptStructuredOutput && !antigravityToolChoiceModeIsNoneDoc(doc) {
|
|
shouldApplyClaudeValidated = true
|
|
// VALIDATED mode is supported on v1internal CCPA only; aicode v1alpha
|
|
// FunctionCallingConfig.Mode enum does not include VALIDATED.
|
|
if !useAICode {
|
|
canonicalizeAntigravityToolConfigForValidatedDoc(doc)
|
|
_ = doc.Set("request.toolConfig.functionCallingConfig.mode", "VALIDATED")
|
|
}
|
|
}
|
|
} else if selection.MaxOutputTokens == 0 {
|
|
stripAntigravityMaxOutputTokensDoc(doc)
|
|
}
|
|
}
|
|
|
|
applyAntigravityNativeSignatureReplayIfNeededDoc(modelName, doc)
|
|
if useAICode {
|
|
helps.CanonicalizeAntigravityAICodeRequestDoc(doc)
|
|
}
|
|
var unfinalizedBase []byte
|
|
if captureUnfinalizedBase || useAICode {
|
|
// Snapshot the pure v1internal payload BEFORE staging v1alpha-only fields
|
|
// and BEFORE FinalizePayloadDoc so continuation leg 2+ and same-request
|
|
// v1internal fallback never leak v1alpha fields (parent, entitlement,
|
|
// aicode) and apply user payload rules exactly once as their final barrier.
|
|
baseDoc := ojson.NewDoc(bytes.Clone(doc.Bytes()))
|
|
helps.HoistAntigravityAICodeInitialCreditsDoc(baseDoc)
|
|
helps.StripAntigravityAICodeOnlyFieldsDoc(baseDoc)
|
|
unfinalizedBase = bytes.Clone(baseDoc.Bytes())
|
|
}
|
|
|
|
var (
|
|
aicodeBaseURL string
|
|
businessMode bool
|
|
quotaProject string
|
|
defaultExp = strings.TrimSpace(helps.AntigravityAICodeDefaultExperience(selection, doc.Get("requestType").String()))
|
|
resolvedV1Exp string
|
|
stagedAICode helps.AICodeStagedState
|
|
stagedV1Credits helps.V1InternalCreditsStagedState
|
|
)
|
|
if useAICode {
|
|
if errSafety := helps.NormalizeAntigravityAICodeSafetySettingsDoc(doc); errSafety != nil {
|
|
return out, statusErr{
|
|
code: http.StatusBadRequest,
|
|
msg: errSafety.Error(),
|
|
requestScoped: true,
|
|
requestStop: true,
|
|
}
|
|
}
|
|
aicodeBaseURL, _ = resolveAntigravityAICodeBaseURLWithPreprod(auth, usePreprod)
|
|
businessMode = helps.IsAntigravityBusinessAICodeHost(aicodeBaseURL)
|
|
experience := helps.AntigravityAICodeExperienceWithSelection(auth, selection)
|
|
userTier := resolveAntigravityUserTierWithSelection(auth, selection)
|
|
quotaProject = helps.AntigravityAICodeQuotaProject(auth, reqOpts.headers, projectID)
|
|
businessParent := ""
|
|
if businessMode {
|
|
businessParent = helps.FormatAntigravityBusinessParent(quotaProject)
|
|
}
|
|
stagedAICode = helps.StageAntigravityAICodeDefaultsDoc(doc, helps.AICodeFramingOptions{
|
|
Experience: experience,
|
|
DefaultExperience: defaultExp,
|
|
UserTier: userTier,
|
|
BusinessMode: businessMode,
|
|
Parent: businessParent,
|
|
})
|
|
} else {
|
|
resolvedV1Exp = helps.ExtractAntigravityAICodeExperienceDoc(doc)
|
|
if resolvedV1Exp == "" {
|
|
resolvedV1Exp = helps.AntigravityAICodeExperienceWithSelection(auth, selection)
|
|
}
|
|
// Direct v1internal paths (including compact continuations, explicit
|
|
// VALIDATED tool mode, and non-AICode mode) strip incoming v1alpha-only
|
|
// fields before FinalizePayloadDoc, then stage enabledCreditTypes (and
|
|
// resolved aicode.experience when present, including the credit-fallback
|
|
// experience for unmapped models with initial GOOGLE_ONE_AI credits)
|
|
// under request.* so Payload.Filter/Override rules (including
|
|
// Exist: ["aicode.experience"]) apply uniformly across v1alpha and
|
|
// v1internal before FrameAntigravityV1InternalDocForContext strips
|
|
// request.aicode.
|
|
helps.HoistAntigravityAICodeInitialCreditsDoc(doc)
|
|
helps.StripAntigravityAICodeOnlyFieldsDoc(doc)
|
|
if resolvedV1Exp == "" && helps.AntigravityDocHasInitialPaidCredits(doc) {
|
|
if defaultExp != "" {
|
|
resolvedV1Exp = defaultExp
|
|
} else {
|
|
resolvedV1Exp = helps.AntigravityAICodeFallbackCreditExperience
|
|
}
|
|
}
|
|
stagedV1Credits = helps.StageAntigravityV1InternalCreditsDoc(doc, resolvedV1Exp)
|
|
}
|
|
|
|
helps.FinalizePayloadDoc(ctx, doc)
|
|
if isContinuationReq && !helps.HasAntigravityWireContinuationTokenDoc(doc) {
|
|
return out, statusErr{
|
|
code: http.StatusBadRequest,
|
|
msg: "antigravity continuation aborted: continuationToken removed by payload configuration",
|
|
}
|
|
}
|
|
if isAgent {
|
|
// A filtered requestType is not reinserted. If a rule explicitly selected
|
|
// another request type, keep that protocol's serialization unchanged.
|
|
requestType := doc.Get("requestType")
|
|
isAgent = !requestType.Exists() || isAntigravityAgentRequestType(requestType.String())
|
|
}
|
|
|
|
if !useAICode {
|
|
v1InternalWireDoc := helps.FrameAntigravityV1InternalDocForContext(ctx, doc, stagedV1Credits)
|
|
if errCredits := validateAntigravityPostFinalizeCredits(ctx, doc, v1InternalWireDoc); errCredits != nil {
|
|
return out, errCredits
|
|
}
|
|
v1InternalWirePayload := helps.SerializeAntigravityPayload(v1InternalWireDoc, isAgent)
|
|
path := antigravityGeneratePath
|
|
if stream {
|
|
path = antigravityStreamPath
|
|
}
|
|
httpReq, errReq := e.buildAntigravityUpstreamHTTPRequest(
|
|
ctx, auth, ccpaBase, path, stream, alt, token, v1InternalWirePayload, reqOpts, "", nil,
|
|
)
|
|
if errReq != nil {
|
|
return out, errReq
|
|
}
|
|
return antigravityBuiltRequest{
|
|
httpReq: httpReq,
|
|
payload: v1InternalWirePayload,
|
|
unfinalizedBase: unfinalizedBase,
|
|
canonicalReqPayload: v1InternalWirePayload,
|
|
fallbackStagedExperience: resolvedV1Exp,
|
|
fallbackDefaultExperience: defaultExp,
|
|
}, nil
|
|
}
|
|
|
|
v1InternalPayload := helps.SerializeAntigravityPayload(doc, isAgent)
|
|
|
|
// Structural transport framing AFTER FinalizePayloadDoc preserves the final
|
|
// semantic barrier: all v1alpha defaults were staged pre-finalization so
|
|
// framing honors Payload.Override and Payload.Filter in both directions.
|
|
aicodeFiltered := helps.PayloadFiltersPath(ctx, "aicode") || helps.PayloadFiltersPath(ctx, "aicode.experience")
|
|
creditsFiltered := helps.AntigravityPayloadFiltersCredits(ctx)
|
|
experienceOverridden := helps.PayloadOverridesPath(ctx, "aicode.experience") || helps.PayloadOverridesPath(ctx, "aicode")
|
|
if errCredits := validateAntigravityPostFinalizeCredits(ctx, doc, nil); errCredits != nil {
|
|
return out, errCredits
|
|
}
|
|
aicodeDoc, extraHeaders, errFrame := helps.ToAICodeGenerateContentDocWithOptions(doc, helps.AICodeFramingOptions{
|
|
DefaultExperience: defaultExp,
|
|
BusinessMode: businessMode,
|
|
Staged: &stagedAICode,
|
|
AICodeFiltered: aicodeFiltered,
|
|
CreditsFiltered: creditsFiltered,
|
|
ExperienceOverridden: experienceOverridden,
|
|
})
|
|
if errFrame != nil {
|
|
return out, statusErr{code: http.StatusBadRequest, msg: errFrame.Error()}
|
|
}
|
|
if errCredits := validateAntigravityPostFinalizeCredits(ctx, nil, aicodeDoc); errCredits != nil {
|
|
return out, errCredits
|
|
}
|
|
v1alphaAllowedPaidCredits := helps.AntigravityAICodeDocHasPaidCredits(aicodeDoc)
|
|
aicodePayload := helps.SerializeAntigravityPayload(aicodeDoc, false)
|
|
|
|
aicodePath := antigravityAICodeGeneratePath
|
|
if stream {
|
|
aicodePath = antigravityAICodeStreamPath
|
|
}
|
|
httpReq, errReq := e.buildAntigravityUpstreamHTTPRequest(
|
|
ctx, auth, aicodeBaseURL, aicodePath, stream, alt, aicodeToken, aicodePayload, reqOpts, quotaProject, extraHeaders,
|
|
)
|
|
if errReq != nil {
|
|
return out, errReq
|
|
}
|
|
var capturedBase []byte
|
|
if captureUnfinalizedBase {
|
|
capturedBase = unfinalizedBase
|
|
}
|
|
return antigravityBuiltRequest{
|
|
httpReq: httpReq,
|
|
payload: aicodePayload,
|
|
unfinalizedBase: capturedBase,
|
|
canonicalReqPayload: v1InternalPayload,
|
|
usingAICode: true,
|
|
aicodeExperimentFlags: selection.AICodeExperimentFlags,
|
|
fallbackBaseURL: ccpaBase,
|
|
fallbackToken: token,
|
|
fallbackUnfinalizedBase: unfinalizedBase,
|
|
fallbackApplyValidated: shouldApplyClaudeValidated,
|
|
fallbackIsAgent: isAgent,
|
|
fallbackStream: stream,
|
|
fallbackAlt: alt,
|
|
fallbackStagedExperience: stagedAICode.StagedExperience,
|
|
fallbackDefaultExperience: defaultExp,
|
|
fallbackSuppressPaidCredits: !v1alphaAllowedPaidCredits,
|
|
}, nil
|
|
}
|
|
|
|
func (e *AntigravityExecutor) buildRequestForModelDocInternal(ctx context.Context, auth *cliproxyauth.Auth, token string, selection cliproxyauth.AntigravityModelSelection, doc *ojson.Doc, stream bool, alt, baseURL string, captureUnfinalizedBase bool, derivedSessionIDs ...string) (*http.Request, []byte, []byte, error) {
|
|
built, errBuild := e.buildRequestForModelDocRouted(ctx, auth, token, selection, doc, stream, alt, baseURL, captureUnfinalizedBase, derivedSessionIDs...)
|
|
if errBuild != nil {
|
|
return nil, nil, nil, errBuild
|
|
}
|
|
return built.httpReq, built.payload, built.unfinalizedBase, nil
|
|
}
|
|
|
|
// antigravityToolChoiceModeIsValidatedDoc reports whether the request already
|
|
// sets function calling mode to VALIDATED under either camelCase or snake_case,
|
|
// nested or top-level proto-JSON paths. VALIDATED is supported on v1internal
|
|
// CCPA only and absent from the aicode v1alpha proto enum.
|
|
func antigravityToolChoiceModeIsValidatedDoc(doc *ojson.Doc) bool {
|
|
if doc == nil {
|
|
return false
|
|
}
|
|
for _, container := range []string{"request.toolConfig", "request.tool_config", "toolConfig", "tool_config"} {
|
|
for _, key := range []string{"functionCallingConfig", "function_calling_config"} {
|
|
mode := doc.Get(container + "." + key + ".mode")
|
|
if (mode.Type == ojson.String && strings.EqualFold(strings.TrimSpace(mode.String()), "VALIDATED")) ||
|
|
(mode.Type == ojson.Number && mode.Int() == 4) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// antigravityToolChoiceModeIsNoneDoc reports whether the request already sets
|
|
// function calling mode to NONE under either camelCase or snake_case proto-JSON
|
|
// paths, canonicalizing non-canonical casing or surrounding whitespace in place.
|
|
func antigravityToolChoiceModeIsNoneDoc(doc *ojson.Doc) bool {
|
|
if doc == nil {
|
|
return false
|
|
}
|
|
for _, container := range []string{"request.toolConfig", "request.tool_config"} {
|
|
for _, key := range []string{"functionCallingConfig", "function_calling_config"} {
|
|
modePath := container + "." + key + ".mode"
|
|
mode := doc.Get(modePath)
|
|
if mode.Type == ojson.String && strings.EqualFold(strings.TrimSpace(mode.String()), "NONE") {
|
|
if mode.String() != "NONE" {
|
|
_ = doc.Set(modePath, "NONE")
|
|
}
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// canonicalizeAntigravityToolConfigForValidatedDoc merges snake_case tool_config
|
|
// and function_calling_config containers into their camelCase canonical paths before
|
|
// setting VALIDATED mode, preserving non-conflicting fields while preventing
|
|
// duplicate proto-JSON keys on upstream requests.
|
|
func canonicalizeAntigravityToolConfigForValidatedDoc(doc *ojson.Doc) {
|
|
if doc == nil {
|
|
return
|
|
}
|
|
canonicalizeAntigravityFunctionCallingConfigDoc(doc)
|
|
if snakeToolConfig := doc.Get("request.tool_config"); snakeToolConfig.Exists() {
|
|
if snakeToolConfig.IsObject() {
|
|
if !doc.Get("request.toolConfig").IsObject() {
|
|
_ = doc.SetRaw("request.toolConfig", snakeToolConfig.Raw)
|
|
canonicalizeAntigravityFunctionCallingConfigDoc(doc)
|
|
} else {
|
|
helps.MergeAntigravityProtoObjectDoc(doc, "request.toolConfig", snakeToolConfig, "functioncallingconfig")
|
|
if fcc := snakeToolConfig.Get("functionCallingConfig"); fcc.IsObject() {
|
|
helps.MergeAntigravityProtoObjectDoc(doc, "request.toolConfig.functionCallingConfig", fcc)
|
|
}
|
|
if fccSnake := snakeToolConfig.Get("function_calling_config"); fccSnake.IsObject() {
|
|
helps.MergeAntigravityProtoObjectDoc(doc, "request.toolConfig.functionCallingConfig", fccSnake)
|
|
}
|
|
}
|
|
}
|
|
_ = doc.Delete("request.tool_config")
|
|
}
|
|
}
|
|
|
|
func canonicalizeAntigravityFunctionCallingConfigDoc(doc *ojson.Doc) {
|
|
if doc == nil {
|
|
return
|
|
}
|
|
snakeFCC := doc.Get("request.toolConfig.function_calling_config")
|
|
if !snakeFCC.Exists() {
|
|
return
|
|
}
|
|
if snakeFCC.IsObject() {
|
|
helps.MergeAntigravityProtoObjectDoc(doc, "request.toolConfig.functionCallingConfig", snakeFCC)
|
|
}
|
|
_ = doc.Delete("request.toolConfig.function_calling_config")
|
|
}
|
|
|
|
// stripAntigravityMaxOutputTokensDoc removes maxOutputTokens and its snake_case
|
|
// aliases under both generationConfig and generation_config containers, pruning
|
|
// an emptied generation_config container and merging mixed containers when both
|
|
// generationConfig and generation_config remain present.
|
|
func stripAntigravityMaxOutputTokensDoc(doc *ojson.Doc) {
|
|
if doc == nil {
|
|
return
|
|
}
|
|
_ = doc.Delete("request.generationConfig.maxOutputTokens")
|
|
_ = doc.Delete("request.generationConfig.max_output_tokens")
|
|
deletedSnakeGenConfig := false
|
|
for _, path := range []string{
|
|
"request.generation_config.maxOutputTokens",
|
|
"request.generation_config.max_output_tokens",
|
|
} {
|
|
if doc.Get(path).Exists() && doc.Delete(path) == nil {
|
|
deletedSnakeGenConfig = true
|
|
}
|
|
}
|
|
if deletedSnakeGenConfig {
|
|
if gc := doc.Get("request.generation_config"); gc.Exists() && gc.IsObject() && len(gc.Map()) == 0 {
|
|
_ = doc.Delete("request.generation_config")
|
|
}
|
|
}
|
|
if doc.Get("request.generation_config").Exists() && doc.Get("request.generationConfig").Exists() {
|
|
helps.CanonicalizeAntigravityGenerationConfigDoc(doc)
|
|
}
|
|
}
|
|
|
|
// sanitizeAntigravityRequestSchemas cleans the JSON schemas carried by an Antigravity request.
|
|
//
|
|
// Cleaning is applied only to the payload locations that actually hold a JSON schema. The schema
|
|
// cleaner rewrites keys such as "title", "format", "default" and "const", which are also ordinary
|
|
// data keys inside functionCall arguments replayed from conversation history. Running it over the
|
|
// whole document silently mutated that history, so tools lost required argument fields and the
|
|
// model imitated the corrupted examples on later turns.
|
|
// sanitizeAntigravityRequestSchemas cleans with union-preserving (Gemini) tool semantics.
|
|
// Claude tool unions are flattened only when the caller supplies the model flag via
|
|
// sanitizeAntigravityRequestSchemasForModel; the placeholder group alone must not decide it,
|
|
// because gemini-3-pro models share that group and accept preserved unions.
|
|
func sanitizeAntigravityRequestSchemas(payloadStr string, useAntigravitySchema bool) string {
|
|
return sanitizeAntigravityRequestSchemasForModel(payloadStr, useAntigravitySchema, false)
|
|
}
|
|
|
|
// sanitizeAntigravityRequestSchemasForModel applies sanitizeAntigravityRequestSchemas with an
|
|
// explicit Antigravity Claude flag. Antigravity Claude tool schemas additionally flatten
|
|
// multi-branch anyOf/oneOf unions, which the Claude-side upstream rejects (Issue 3662).
|
|
func sanitizeAntigravityRequestSchemasForModel(payloadStr string, useAntigravitySchema, isClaudeModel bool) string {
|
|
payloadStr = sanitizeAntigravityToolSchemasForModel(payloadStr, useAntigravitySchema, isClaudeModel)
|
|
return sanitizeAntigravityGenerationSchemas(payloadStr)
|
|
}
|
|
|
|
func antigravitySchemaSanitizationFlags(modelName string) (useAntigravitySchema, isClaudeModel bool) {
|
|
lowerModel := strings.ToLower(modelName)
|
|
isClaudeModel = helps.IsAntigravityAnthropicModel(modelName)
|
|
useAntigravitySchema = isClaudeModel || strings.Contains(lowerModel, "gemini-3-pro") || strings.Contains(lowerModel, "gemini-3.1-pro")
|
|
return useAntigravitySchema, isClaudeModel
|
|
}
|
|
|
|
func sanitizeAntigravityRequestSchemasForModelIfNeededDoc(modelName string, doc *ojson.Doc) bool {
|
|
if !antigravityRequestNeedsSchemaSanitizationDoc(doc) {
|
|
return false
|
|
}
|
|
useAntigravitySchema, isClaudeModel := antigravitySchemaSanitizationFlags(modelName)
|
|
return sanitizeAntigravityRequestSchemasForModelDoc(doc, useAntigravitySchema, isClaudeModel)
|
|
}
|
|
|
|
func sanitizeAntigravityRequestSchemasForModelDoc(doc *ojson.Doc, useAntigravitySchema, isClaudeModel bool) bool {
|
|
if doc == nil {
|
|
return false
|
|
}
|
|
changed := sanitizeAntigravityToolSchemasForModelDoc(doc, useAntigravitySchema, isClaudeModel)
|
|
if sanitizeAntigravityGenerationSchemasDoc(doc) {
|
|
changed = true
|
|
}
|
|
return changed
|
|
}
|
|
|
|
// sanitizeAntigravityToolSchemas applies the existing declaration rewrites to
|
|
// a small document containing only request.tools, then replaces that subtree
|
|
// once. This preserves rewrite order and bytes without copying the full request
|
|
// for every declaration schema.
|
|
func sanitizeAntigravityToolSchemas(payloadStr string, useAntigravitySchema bool) string {
|
|
return sanitizeAntigravityToolSchemasForModel(payloadStr, useAntigravitySchema, false)
|
|
}
|
|
|
|
func sanitizeAntigravityToolSchemasForModel(payloadStr string, useAntigravitySchema, isClaudeModel bool) string {
|
|
tools := ojson.Get(payloadStr, "request.tools")
|
|
if !tools.IsArray() {
|
|
return payloadStr
|
|
}
|
|
|
|
toolDocument := `{"request":{"tools":` + tools.Raw + `}}`
|
|
toolDocument = sanitizeAntigravityToolSchemaDocumentForModel(toolDocument, useAntigravitySchema, isClaudeModel)
|
|
cleanedTools := ojson.Get(toolDocument, "request.tools")
|
|
if !cleanedTools.IsArray() || cleanedTools.Raw == tools.Raw {
|
|
return payloadStr
|
|
}
|
|
updated, errSet := ojson.SetRawBytes([]byte(payloadStr), "request.tools", []byte(cleanedTools.Raw))
|
|
if errSet != nil {
|
|
log.Debugf("antigravity: failed to write cleaned request.tools: %v", errSet)
|
|
return payloadStr
|
|
}
|
|
return string(updated)
|
|
}
|
|
|
|
func sanitizeAntigravityToolSchemasForModelDoc(doc *ojson.Doc, useAntigravitySchema, isClaudeModel bool) bool {
|
|
if doc == nil {
|
|
return false
|
|
}
|
|
tools := doc.Get("request.tools")
|
|
if !tools.IsArray() {
|
|
return false
|
|
}
|
|
|
|
toolDocument := `{"request":{"tools":` + tools.Raw + `}}`
|
|
toolDocument = sanitizeAntigravityToolSchemaDocumentForModel(toolDocument, useAntigravitySchema, isClaudeModel)
|
|
cleanedTools := ojson.Get(toolDocument, "request.tools")
|
|
if !cleanedTools.IsArray() || cleanedTools.Raw == tools.Raw {
|
|
return false
|
|
}
|
|
if errSet := doc.SetRawBytes("request.tools", []byte(cleanedTools.Raw)); errSet != nil {
|
|
log.Debugf("antigravity: failed to write cleaned request.tools: %v", errSet)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func sanitizeAntigravityToolSchemaDocument(payloadStr string, useAntigravitySchema bool) string {
|
|
return sanitizeAntigravityToolSchemaDocumentForModel(payloadStr, useAntigravitySchema, false)
|
|
}
|
|
|
|
// antigravityDeclarationContainers lists both spellings of the declarations
|
|
// array a tool may carry.
|
|
var antigravityDeclarationContainers = []string{"functionDeclarations", "function_declarations"}
|
|
|
|
// sanitizeAntigravityToolSchemaDocumentForModel renames and cleans every
|
|
// declaration schema in the tools-only document. Each declaration is edited
|
|
// on its own raw bytes and the results are spliced back into the tools array
|
|
// in a single pass, so the cost stays linear in the document size instead of
|
|
// scaling with declarations x document size (Issue 6714). The emitted bytes
|
|
// match the previous whole-document edits: changed elements are spliced at
|
|
// their original offsets, so untouched bytes (including whitespace around
|
|
// array elements) survive verbatim, and changed nodes go through the same
|
|
// sjson edits, scoped to one declaration.
|
|
func sanitizeAntigravityToolSchemaDocumentForModel(payloadStr string, useAntigravitySchema, isClaudeModel bool) string {
|
|
toolSchemaCleaner := func(schema string, isParameterSchema bool) string {
|
|
// Only declaration parameter schemas become Claude custom.input_schema upstream,
|
|
// so only they need Claude union flattening. Function return schemas keep the
|
|
// union-preserving cleaning like every other response-side schema.
|
|
if isClaudeModel && isParameterSchema {
|
|
return util.CleanJSONSchemaForAntigravityClaudeTool(schema, useAntigravitySchema)
|
|
}
|
|
return util.CleanJSONSchemaForAntigravityTool(schema, useAntigravitySchema)
|
|
}
|
|
cleanNestedToolSchema := func(schemaRaw string, isParameterSchema bool) string {
|
|
return cleanNestedSchema(func(schema string) string {
|
|
return toolSchemaCleaner(schema, isParameterSchema)
|
|
}, schemaRaw)
|
|
}
|
|
|
|
tools := ojson.Parse(payloadStr).Get("request.tools")
|
|
if !tools.IsArray() {
|
|
return payloadStr
|
|
}
|
|
elements := make([]ojson.Result, 0)
|
|
edits := make([]antigravityElementEdit, 0)
|
|
tools.ForEach(func(_, tool ojson.Result) bool {
|
|
elements = append(elements, tool)
|
|
if !tool.IsObject() {
|
|
return true
|
|
}
|
|
var toolDoc *ojson.Doc
|
|
toolChanged := false
|
|
for _, declKey := range antigravityDeclarationContainers {
|
|
decls := tool.Get(declKey)
|
|
if !decls.IsArray() {
|
|
continue
|
|
}
|
|
cleanedDecls, declsChanged := sanitizeAntigravityDeclarations(decls, cleanNestedToolSchema)
|
|
if !declsChanged {
|
|
continue
|
|
}
|
|
if toolDoc == nil {
|
|
toolDoc = ojson.NewDoc([]byte(tool.Raw))
|
|
}
|
|
if errSet := toolDoc.SetRawBytes(declKey, []byte(cleanedDecls)); errSet != nil {
|
|
log.Debugf("antigravity: failed to write cleaned %s: %v", declKey, errSet)
|
|
continue
|
|
}
|
|
toolChanged = true
|
|
}
|
|
if toolChanged && toolDoc != nil {
|
|
toolRaw := string(toolDoc.Bytes())
|
|
if toolRaw != tool.Raw {
|
|
edits = append(edits, antigravityElementEdit{offset: tool.Index - tools.Index, raw: tool.Raw, replacement: toolRaw})
|
|
}
|
|
}
|
|
return true
|
|
})
|
|
if len(edits) == 0 {
|
|
return payloadStr
|
|
}
|
|
updated, errSet := ojson.SetRawBytes([]byte(payloadStr), "request.tools", []byte(applyAntigravityElementEdits(tools.Raw, tools.Index, elements, edits)))
|
|
if errSet != nil {
|
|
log.Debugf("antigravity: failed to write cleaned request.tools: %v", errSet)
|
|
return payloadStr
|
|
}
|
|
return string(updated)
|
|
}
|
|
|
|
// antigravityElementEdit replaces one array element (raw, at offset within
|
|
// the array's raw bytes) with replacement.
|
|
type antigravityElementEdit struct {
|
|
offset int
|
|
raw string
|
|
replacement string
|
|
}
|
|
|
|
// applyAntigravityElementEdits splices element replacements into an array's
|
|
// raw bytes in offset order, keeping every other byte (commas, whitespace,
|
|
// unchanged elements) verbatim. Edits whose offsets do not line up with the
|
|
// array bytes fall back to joining the elements with commas: still valid
|
|
// and semantically identical, just without the original separators. gjson
|
|
// reports element offsets into the parsed document, so offsets here are
|
|
// relative to the array start.
|
|
func applyAntigravityElementEdits(arrayRaw string, arrayIndex int, elements []ojson.Result, edits []antigravityElementEdit) string {
|
|
var rebuilt strings.Builder
|
|
rebuilt.Grow(len(arrayRaw))
|
|
cursor := 0
|
|
for _, edit := range edits {
|
|
if edit.offset < cursor || edit.offset+len(edit.raw) > len(arrayRaw) || arrayRaw[edit.offset:edit.offset+len(edit.raw)] != edit.raw {
|
|
return joinAntigravityElements(arrayIndex, elements, edits)
|
|
}
|
|
rebuilt.WriteString(arrayRaw[cursor:edit.offset])
|
|
rebuilt.WriteString(edit.replacement)
|
|
cursor = edit.offset + len(edit.raw)
|
|
}
|
|
rebuilt.WriteString(arrayRaw[cursor:])
|
|
return rebuilt.String()
|
|
}
|
|
|
|
// joinAntigravityElements rebuilds an array by joining element bytes with
|
|
// commas, substituting replacements where recorded. It is the fallback for
|
|
// applyAntigravityElementEdits when splice offsets cannot be trusted.
|
|
func joinAntigravityElements(arrayIndex int, elements []ojson.Result, edits []antigravityElementEdit) string {
|
|
replacements := make(map[int]string, len(edits))
|
|
for _, edit := range edits {
|
|
replacements[edit.offset] = edit.replacement
|
|
}
|
|
var rebuilt strings.Builder
|
|
rebuilt.WriteByte('[')
|
|
for i, element := range elements {
|
|
if i > 0 {
|
|
rebuilt.WriteByte(',')
|
|
}
|
|
if replacement, ok := replacements[element.Index-arrayIndex]; ok {
|
|
rebuilt.WriteString(replacement)
|
|
} else {
|
|
rebuilt.WriteString(element.Raw)
|
|
}
|
|
}
|
|
rebuilt.WriteByte(']')
|
|
return rebuilt.String()
|
|
}
|
|
|
|
// sanitizeAntigravityDeclarations rebuilds one declarations array, applying
|
|
// the rename and schema cleaning to each declaration in isolation. It
|
|
// reports whether any declaration actually changed so callers can keep the
|
|
// original bytes when the array is already clean.
|
|
func sanitizeAntigravityDeclarations(decls ojson.Result, clean func(schemaRaw string, isParameterSchema bool) string) (string, bool) {
|
|
elements := make([]ojson.Result, 0)
|
|
edits := make([]antigravityElementEdit, 0)
|
|
decls.ForEach(func(_, decl ojson.Result) bool {
|
|
elements = append(elements, decl)
|
|
if !decl.IsObject() {
|
|
return true
|
|
}
|
|
cleanedDecl := sanitizeAntigravityDeclaration(decl, clean)
|
|
if cleanedDecl != decl.Raw {
|
|
edits = append(edits, antigravityElementEdit{offset: decl.Index - decls.Index, raw: decl.Raw, replacement: cleanedDecl})
|
|
}
|
|
return true
|
|
})
|
|
if len(edits) == 0 {
|
|
return "", false
|
|
}
|
|
return applyAntigravityElementEdits(decls.Raw, decls.Index, elements, edits), true
|
|
}
|
|
|
|
// sanitizeAntigravityDeclaration applies the declaration-level edits that
|
|
// used to run against the whole tools document: parametersJsonSchema is
|
|
// renamed onto parameters first, then every object schema is cleaned in
|
|
// place. Failed edits keep the declaration as-is and are only logged.
|
|
func sanitizeAntigravityDeclaration(decl ojson.Result, clean func(schemaRaw string, isParameterSchema bool) string) string {
|
|
declRaw := decl.Raw
|
|
if decl.Get("parametersJsonSchema").Exists() {
|
|
renamed, errRename := util.RenameKey(declRaw, "parametersJsonSchema", "parameters")
|
|
if errRename != nil {
|
|
log.Debugf("antigravity: failed to rename parametersJsonSchema: %v", errRename)
|
|
} else {
|
|
declRaw = renamed
|
|
decl = ojson.Parse(declRaw)
|
|
}
|
|
}
|
|
var declDoc *ojson.Doc
|
|
changed := false
|
|
for _, key := range antigravityDeclarationSchemaKeys {
|
|
schema := decl.Get(key)
|
|
if !schema.IsObject() {
|
|
continue
|
|
}
|
|
cleanedSchema := clean(schema.Raw, isParameterSchemaPath(key))
|
|
if cleanedSchema == schema.Raw {
|
|
continue
|
|
}
|
|
if declDoc == nil {
|
|
declDoc = ojson.NewDoc([]byte(declRaw))
|
|
}
|
|
if errSet := declDoc.SetRawBytes(key, []byte(cleanedSchema)); errSet != nil {
|
|
log.Debugf("antigravity: failed to write cleaned schema at %s: %v", key, errSet)
|
|
continue
|
|
}
|
|
changed = true
|
|
}
|
|
if changed && declDoc != nil {
|
|
return string(declDoc.Bytes())
|
|
}
|
|
return declRaw
|
|
}
|
|
|
|
// sanitizeAntigravityGenerationSchemas batches every schema edit within one
|
|
// generation config before replacing that config in the full request.
|
|
func sanitizeAntigravityGenerationSchemas(payloadStr string) string {
|
|
doc := ojson.NewDoc([]byte(payloadStr))
|
|
if !sanitizeAntigravityGenerationSchemasDoc(doc) {
|
|
return payloadStr
|
|
}
|
|
return string(doc.Bytes())
|
|
}
|
|
|
|
func sanitizeAntigravityGenerationSchemasDoc(doc *ojson.Doc) bool {
|
|
if doc == nil {
|
|
return false
|
|
}
|
|
changed := false
|
|
for _, container := range antigravityGenerationConfigContainers {
|
|
generationConfig := doc.Get(container)
|
|
if !generationConfig.IsObject() {
|
|
continue
|
|
}
|
|
var configDoc *ojson.Doc
|
|
configChanged := false
|
|
for _, key := range antigravityGenerationSchemaKeys {
|
|
schema := generationConfig.Get(key)
|
|
if !schema.IsObject() {
|
|
continue
|
|
}
|
|
cleanedSchema := util.CleanJSONSchemaForAntigravityResponse(schema.Raw)
|
|
if cleanedSchema == schema.Raw {
|
|
continue
|
|
}
|
|
if configDoc == nil {
|
|
configDoc = ojson.NewDoc([]byte(generationConfig.Raw))
|
|
}
|
|
if errSet := configDoc.SetRawBytes(key, []byte(cleanedSchema)); errSet != nil {
|
|
log.Debugf("antigravity: failed to write cleaned schema at %s.%s: %v", container, key, errSet)
|
|
continue
|
|
}
|
|
configChanged = true
|
|
}
|
|
if !configChanged || configDoc == nil {
|
|
continue
|
|
}
|
|
cleanedConfig := configDoc.Bytes()
|
|
if string(cleanedConfig) == generationConfig.Raw {
|
|
continue
|
|
}
|
|
if errSet := doc.SetRawBytes(container, cleanedConfig); errSet != nil {
|
|
log.Debugf("antigravity: failed to write cleaned %s: %v", container, errSet)
|
|
continue
|
|
}
|
|
changed = true
|
|
}
|
|
return changed
|
|
}
|
|
|
|
// isParameterSchemaPath reports whether a declaration schema path holds tool input
|
|
// parameters rather than a function return schema.
|
|
func isParameterSchemaPath(schemaPath string) bool {
|
|
key := schemaPath
|
|
if idx := strings.LastIndex(schemaPath, "."); idx >= 0 {
|
|
key = schemaPath[idx+1:]
|
|
}
|
|
return strings.HasPrefix(key, "parameters")
|
|
}
|
|
|
|
func cleanAntigravitySchemasAtPaths(payloadStr string, schemaPaths []string, clean func(string) string) string {
|
|
var doc *ojson.Doc
|
|
changed := false
|
|
for _, schemaPath := range schemaPaths {
|
|
schema := ojson.Get(payloadStr, schemaPath)
|
|
if !schema.Exists() {
|
|
continue
|
|
}
|
|
cleanedSchema := clean(schema.Raw)
|
|
if cleanedSchema == schema.Raw {
|
|
continue
|
|
}
|
|
if doc == nil {
|
|
doc = ojson.NewDoc([]byte(payloadStr))
|
|
}
|
|
if errSet := doc.SetRawBytes(schemaPath, []byte(cleanedSchema)); errSet != nil {
|
|
log.Debugf("antigravity: failed to write cleaned schema at %s: %v", schemaPath, errSet)
|
|
continue
|
|
}
|
|
changed = true
|
|
}
|
|
if !changed || doc == nil {
|
|
return payloadStr
|
|
}
|
|
return string(doc.Bytes())
|
|
}
|
|
|
|
// antigravitySchemaWrapperKey nests a schema during cleaning. It is never sent upstream.
|
|
const antigravitySchemaWrapperKey = "schema"
|
|
|
|
// cleanNestedSchema cleans a schema with it nested one level down, then unwraps it.
|
|
//
|
|
// The cleaner deliberately skips placeholder insertion for a top-level schema, but Claude's
|
|
// VALIDATED mode needs every tool schema to declare at least one required property. Whole-payload
|
|
// cleaning always saw tool schemas nested inside the request, so nesting is reproduced here to keep
|
|
// the emitted schema byte-identical to the previous behaviour.
|
|
func cleanNestedSchema(clean func(string) string, schemaRaw string) string {
|
|
schemaRaw = util.NormalizeJSONSchemaNumericConstraints(schemaRaw)
|
|
wrappedDoc := ojson.NewDocString("{}")
|
|
if errWrap := wrappedDoc.SetRaw(antigravitySchemaWrapperKey, schemaRaw); errWrap != nil {
|
|
return clean(schemaRaw)
|
|
}
|
|
if unwrapped := ojson.Get(clean(wrappedDoc.String()), antigravitySchemaWrapperKey); unwrapped.Exists() {
|
|
return unwrapped.Raw
|
|
}
|
|
return clean(schemaRaw)
|
|
}
|
|
|
|
// antigravityFunctionDeclarationPaths returns the path of every function declaration in the request.
|
|
// Both the camelCase and snake_case spellings are accepted because callers reach this executor
|
|
// through different translators.
|
|
func antigravityFunctionDeclarationPaths(payloadStr string) []string {
|
|
tools := ojson.Get(payloadStr, "request.tools")
|
|
if !tools.IsArray() {
|
|
return nil
|
|
}
|
|
paths := make([]string, 0, len(tools.Array()))
|
|
for i, tool := range tools.Array() {
|
|
for _, declKey := range []string{"functionDeclarations", "function_declarations"} {
|
|
decls := tool.Get(declKey)
|
|
if !decls.IsArray() {
|
|
continue
|
|
}
|
|
for j := range decls.Array() {
|
|
paths = append(paths, fmt.Sprintf("request.tools.%d.%s.%d", i, declKey, j))
|
|
}
|
|
}
|
|
}
|
|
return paths
|
|
}
|
|
|
|
// antigravitySchemaPaths returns every payload path that holds a JSON schema document.
|
|
// A function declaration may carry a schema for its parameters and for its result, so all of
|
|
// them must be cleaned; anything omitted here reaches the upstream API uncleaned.
|
|
func antigravitySchemaPaths(payloadStr string) []string {
|
|
paths := antigravityDeclarationSchemaPaths(payloadStr)
|
|
return append(paths, antigravityGenerationSchemaPaths(payloadStr)...)
|
|
}
|
|
|
|
func antigravityDeclarationSchemaPaths(payloadStr string) []string {
|
|
paths := make([]string, 0, 8)
|
|
for _, base := range antigravityFunctionDeclarationPaths(payloadStr) {
|
|
for _, key := range antigravityDeclarationSchemaKeys {
|
|
if ojson.Get(payloadStr, base+"."+key).IsObject() {
|
|
paths = append(paths, base+"."+key)
|
|
}
|
|
}
|
|
}
|
|
return paths
|
|
}
|
|
|
|
func antigravityGenerationSchemaPaths(payloadStr string) []string {
|
|
paths := make([]string, 0, len(antigravityGenerationConfigContainers)*len(antigravityGenerationSchemaKeys))
|
|
for _, container := range antigravityGenerationConfigContainers {
|
|
for _, key := range antigravityGenerationSchemaKeys {
|
|
path := container + "." + key
|
|
if ojson.Get(payloadStr, path).IsObject() {
|
|
paths = append(paths, path)
|
|
}
|
|
}
|
|
}
|
|
return paths
|
|
}
|
|
|
|
// The upstream API is proto-JSON and accepts either spelling, and the Gemini translator forwards
|
|
// whichever one the client sent. Both are therefore cleaned where they sit rather than renamed:
|
|
// renaming would alter the body the client asked for, and only the unsupported keywords inside a
|
|
// schema cause upstream errors. The one exception is parametersJsonSchema, renamed onto parameters
|
|
// above because whole-payload cleaning did the same.
|
|
var (
|
|
antigravityDeclarationSchemaKeys = []string{
|
|
"parameters", "parametersJsonSchema", "parameters_json_schema",
|
|
"response", "responseJsonSchema", "response_json_schema",
|
|
}
|
|
antigravityGenerationConfigContainers = []string{
|
|
"request.generationConfig", "request.generation_config",
|
|
}
|
|
antigravityGenerationSchemaKeys = []string{
|
|
"responseSchema", "responseJsonSchema", "response_schema", "response_json_schema",
|
|
}
|
|
)
|
|
|
|
func antigravityRequestNeedsSchemaSanitization(payload []byte) bool {
|
|
if ojson.GetBytesNoCopy(payload, "request.tools.0").Exists() {
|
|
return true
|
|
}
|
|
for _, container := range antigravityGenerationConfigContainers {
|
|
for _, key := range antigravityGenerationSchemaKeys {
|
|
if ojson.GetBytesNoCopy(payload, container+"."+key).Exists() {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func antigravityRequestNeedsSchemaSanitizationDoc(doc *ojson.Doc) bool {
|
|
if doc == nil {
|
|
return false
|
|
}
|
|
if doc.Get("request.tools.0").Exists() {
|
|
return true
|
|
}
|
|
for _, container := range antigravityGenerationConfigContainers {
|
|
for _, key := range antigravityGenerationSchemaKeys {
|
|
if doc.Get(container + "." + key).Exists() {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// resolveAntigravityRequestBaseURL selects one request endpoint without cross-tier fallback.
|
|
// Consumer credentials default to daily; enterprise/GCP credentials can set base_url explicitly.
|
|
func resolveAntigravityRequestBaseURL(auth *cliproxyauth.Auth) string {
|
|
return resolveAntigravityCCPAFallbackBaseURL(auth, "")
|
|
}
|
|
|
|
func antigravityLoadCodeAssistBaseURL(auth *cliproxyauth.Auth) string {
|
|
return resolveAntigravityRequestBaseURL(auth)
|
|
}
|
|
|
|
// withAntigravityUserProjectRedirectGuard returns a shallow copy of client
|
|
// whose CheckRedirect hook re-evaluates Hub 2.36.0 X-Goog-User-Project omission
|
|
// rules on every redirect hop while preserving any previously installed
|
|
// CheckRedirect policy.
|
|
func withAntigravityUserProjectRedirectGuard(client *http.Client, auth *cliproxyauth.Auth) *http.Client {
|
|
if client == nil {
|
|
return nil
|
|
}
|
|
authMode := helps.AntigravityAuthMode(auth)
|
|
copied := *client
|
|
previous := copied.CheckRedirect
|
|
copied.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
|
if req != nil && req.URL != nil && antigravity.ShouldOmitAntigravityUserProjectHeader(authMode, req.URL.String()) {
|
|
req.Header.Del("X-Goog-User-Project")
|
|
}
|
|
if previous != nil {
|
|
return previous(req, via)
|
|
}
|
|
if len(via) >= 10 {
|
|
return errors.New("stopped after 10 redirects")
|
|
}
|
|
return nil
|
|
}
|
|
return &copied
|
|
}
|
|
|
|
func resolveHost(base string) string {
|
|
parsed, errParse := url.Parse(base)
|
|
if errParse != nil {
|
|
return ""
|
|
}
|
|
if parsed.Host != "" {
|
|
return parsed.Host
|
|
}
|
|
return strings.TrimPrefix(strings.TrimPrefix(base, "https://"), "http://")
|
|
}
|
|
|
|
func resolveUserAgent(auth *cliproxyauth.Auth) string {
|
|
return misc.AntigravityRequestUserAgent(antigravityConfiguredUserAgent(auth))
|
|
}
|
|
|
|
func resolveLoadCodeAssistUserAgent(auth *cliproxyauth.Auth) string {
|
|
return misc.AntigravityLoadCodeAssistUserAgent(antigravityConfiguredUserAgent(auth))
|
|
}
|
|
|
|
func antigravityConfiguredUserAgent(auth *cliproxyauth.Auth) string {
|
|
raw := ""
|
|
if auth != nil {
|
|
if auth.Attributes != nil {
|
|
if ua := strings.TrimSpace(auth.Attributes["user_agent"]); ua != "" {
|
|
raw = ua
|
|
}
|
|
}
|
|
if raw == "" && auth.Metadata != nil {
|
|
if ua, ok := auth.Metadata["user_agent"].(string); ok && strings.TrimSpace(ua) != "" {
|
|
raw = strings.TrimSpace(ua)
|
|
}
|
|
}
|
|
}
|
|
return raw
|
|
}
|
|
|
|
func resolveCustomAntigravityBaseURL(auth *cliproxyauth.Auth) string {
|
|
if auth == nil {
|
|
return ""
|
|
}
|
|
if auth.Attributes != nil {
|
|
if v := strings.TrimSpace(auth.Attributes["base_url"]); v != "" {
|
|
return strings.TrimSuffix(v, "/")
|
|
}
|
|
}
|
|
if auth.Metadata != nil {
|
|
if v, ok := auth.Metadata["base_url"].(string); ok {
|
|
v = strings.TrimSpace(v)
|
|
if v != "" {
|
|
return strings.TrimSuffix(v, "/")
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func antigravityAuthID(auth *cliproxyauth.Auth) string {
|
|
if auth == nil {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(auth.ID)
|
|
}
|
|
|
|
const (
|
|
antigravitySignatureGrantScopeMetadataKey = "cpa_signature_cache_grant"
|
|
antigravitySignatureGrantBindingMetadataKey = "cpa_signature_cache_grant_binding"
|
|
antigravitySignatureGrantHomeBindingMetadataKey = "cpa_signature_cache_grant_home_binding"
|
|
)
|
|
|
|
func antigravitySignatureGrantBinding(auth *cliproxyauth.Auth) string {
|
|
if auth == nil || auth.Metadata == nil {
|
|
return ""
|
|
}
|
|
refresh := strings.TrimSpace(metaStringValue(auth.Metadata, "refresh_token"))
|
|
access := strings.TrimSpace(metaStringValue(auth.Metadata, "access_token"))
|
|
if refresh == "" && access == "" {
|
|
return ""
|
|
}
|
|
return antigravityCredentialScope("grant:", refresh+"\x00"+access)
|
|
}
|
|
|
|
func antigravitySignatureGrantHomeBinding(auth *cliproxyauth.Auth) string {
|
|
if auth == nil || auth.Attributes == nil || strings.TrimSpace(metaStringValue(auth.Metadata, "refresh_token")) != "" {
|
|
return ""
|
|
}
|
|
homeScope := strings.TrimSpace(auth.Attributes[cliproxyauth.AntigravityModelEnumHomeScopeAttribute])
|
|
if homeScope == "" {
|
|
return ""
|
|
}
|
|
return antigravityCredentialScope("home-bind:", homeScope)
|
|
}
|
|
|
|
func antigravityHasValidSignatureGrant(auth *cliproxyauth.Auth) bool {
|
|
if auth == nil || auth.Metadata == nil {
|
|
return false
|
|
}
|
|
retained := strings.TrimSpace(metaStringValue(auth.Metadata, antigravitySignatureGrantScopeMetadataKey))
|
|
if retained == "" {
|
|
return false
|
|
}
|
|
tokenBinding := antigravitySignatureGrantBinding(auth)
|
|
if tokenBinding == "" {
|
|
return false
|
|
}
|
|
binding := strings.TrimSpace(metaStringValue(auth.Metadata, antigravitySignatureGrantBindingMetadataKey))
|
|
if binding != "" && binding == tokenBinding {
|
|
return true
|
|
}
|
|
homeBinding := strings.TrimSpace(metaStringValue(auth.Metadata, antigravitySignatureGrantHomeBindingMetadataKey))
|
|
if homeBinding != "" {
|
|
if expected := antigravitySignatureGrantHomeBinding(auth); expected != "" && homeBinding == expected {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func antigravitySignatureGrantIdentity(auth *cliproxyauth.Auth) string {
|
|
if auth == nil {
|
|
return ""
|
|
}
|
|
binding := antigravitySignatureGrantBinding(auth)
|
|
if binding == "" {
|
|
return ""
|
|
}
|
|
if antigravityHasValidSignatureGrant(auth) {
|
|
return strings.TrimSpace(metaStringValue(auth.Metadata, antigravitySignatureGrantScopeMetadataKey))
|
|
}
|
|
if auth.Attributes != nil && strings.TrimSpace(metaStringValue(auth.Metadata, "refresh_token")) == "" {
|
|
if homeScope := strings.TrimSpace(auth.Attributes[cliproxyauth.AntigravityModelEnumHomeScopeAttribute]); homeScope != "" {
|
|
return antigravityCredentialScope("home-grant:", homeScope)
|
|
}
|
|
}
|
|
return binding
|
|
}
|
|
|
|
func antigravitySignatureCacheScope(auth *cliproxyauth.Auth) string {
|
|
if auth == nil {
|
|
return ""
|
|
}
|
|
scope := strings.TrimSpace(auth.ID)
|
|
if scope != "" {
|
|
scope = "id:" + scope
|
|
} else if auth.Attributes != nil {
|
|
if path := strings.TrimSpace(auth.Attributes[cliproxyauth.AttributePath]); path != "" {
|
|
scope = "path:" + path
|
|
} else if source := strings.TrimSpace(auth.Attributes[cliproxyauth.AttributeSource]); source != "" {
|
|
scope = "source:" + source
|
|
}
|
|
}
|
|
grantIdentity := antigravitySignatureGrantIdentity(auth)
|
|
if grantIdentity == "" {
|
|
return ""
|
|
}
|
|
scope += "\x00" + grantIdentity
|
|
if auth.Metadata != nil {
|
|
if projectID, ok := auth.Metadata["project_id"].(string); ok {
|
|
if projectID = strings.TrimSpace(projectID); projectID != "" {
|
|
scope += "\x00" + projectID
|
|
}
|
|
}
|
|
}
|
|
return scope
|
|
}
|
|
|
|
// geminiToAntigravityDocForAuth builds the upstream envelope and reports whether
|
|
// it used the agent protocol.
|
|
func geminiToAntigravityDocForAuth(doc *ojson.Doc, selection cliproxyauth.AntigravityModelSelection, projectID string, auth *cliproxyauth.Auth, derivedSessionIDs ...string) bool {
|
|
return geminiToAntigravityDocForAuthWithOptions(doc, selection, projectID, auth, false, derivedSessionIDs...)
|
|
}
|
|
|
|
func geminiToAntigravityDocForAuthWithOptions(doc *ojson.Doc, selection cliproxyauth.AntigravityModelSelection, projectID string, auth *cliproxyauth.Auth, preserveSafetySettings bool, derivedSessionIDs ...string) bool {
|
|
return geminiToAntigravityDocForAuthWithFailover(doc, selection, projectID, auth, preserveSafetySettings, false, derivedSessionIDs...)
|
|
}
|
|
|
|
func geminiToAntigravityDocForAuthWithFailover(doc *ojson.Doc, selection cliproxyauth.AntigravityModelSelection, projectID string, auth *cliproxyauth.Auth, preserveSafetySettings, crossAccountFailover bool, derivedSessionIDs ...string) bool {
|
|
if doc == nil {
|
|
return false
|
|
}
|
|
helps.DeduplicateAntigravityPayloadObjectKeysDoc(doc)
|
|
modelName := selection.ID
|
|
helps.SetStringIfDifferentDoc(doc, "model", modelName)
|
|
helps.SetStringIfDifferentDoc(doc, "userAgent", "antigravity")
|
|
|
|
isImageModel := strings.Contains(strings.ToLower(modelName), "image")
|
|
reqTypeRes := doc.Get("requestType")
|
|
deleteAllRequestTypes := func() {
|
|
for doc.Get("requestType").Exists() {
|
|
beforeLen := doc.Len()
|
|
if errDel := doc.Delete("requestType"); errDel != nil || doc.Len() >= beforeLen {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
reqType := ""
|
|
switch {
|
|
case !reqTypeRes.Exists() || (reqTypeRes.Type == ojson.String && strings.TrimSpace(reqTypeRes.Str) == ""):
|
|
if isImageModel {
|
|
reqType = "image_gen"
|
|
} else {
|
|
reqType = "agent"
|
|
}
|
|
if reqTypeRes.Exists() {
|
|
deleteAllRequestTypes()
|
|
}
|
|
_ = doc.Set("requestType", reqType)
|
|
case reqTypeRes.Type != ojson.String:
|
|
log.Warnf("antigravity executor: invalid non-string requestType type=%s", reqTypeRes.Type.String())
|
|
deleteAllRequestTypes()
|
|
reqType = ""
|
|
default:
|
|
reqType = strings.TrimSpace(reqTypeRes.Str)
|
|
validReqType := reqType == "image_gen" || reqType == "web_search" || isValidAntigravityRequestType(reqType)
|
|
if validReqType {
|
|
if reqTypeRes.Str != reqType {
|
|
deleteAllRequestTypes()
|
|
_ = doc.Set("requestType", reqType)
|
|
}
|
|
} else {
|
|
log.Warnf("antigravity executor: unknown requestType: %q", reqType)
|
|
deleteAllRequestTypes()
|
|
reqType = ""
|
|
}
|
|
}
|
|
helps.CanonicalizeAntigravityLabelsDoc(doc)
|
|
helps.ScrubAntigravityForbiddenLabelsDoc(doc)
|
|
if !isImageModel && reqType == "agent" && helps.ShouldPromoteAntigravitySubagentRequestTypeDoc(doc) {
|
|
reqType = "custom_agent"
|
|
_ = doc.Set("requestType", reqType)
|
|
}
|
|
|
|
if projectID != "" {
|
|
helps.SetStringIfDifferentDoc(doc, "project", projectID)
|
|
} else {
|
|
_ = doc.Delete("project")
|
|
}
|
|
|
|
helps.CanonicalizeAntigravitySessionIDDoc(doc)
|
|
authID := antigravityAuthID(auth)
|
|
incomingSessionID := strings.TrimSpace(doc.Get("request.sessionId").String())
|
|
derivedSessionID := ""
|
|
if len(derivedSessionIDs) > 0 {
|
|
derivedSessionID = strings.TrimSpace(derivedSessionIDs[0])
|
|
}
|
|
|
|
switch {
|
|
case isImageModel:
|
|
if strings.TrimSpace(doc.Get("requestId").String()) == "" {
|
|
_ = doc.Set("requestId", generateImageGenRequestID())
|
|
}
|
|
if incomingSessionID != "" && authID != "" {
|
|
_ = doc.Set("request.sessionId", scopeIncomingAntigravitySessionID(authID, incomingSessionID, derivedSessionID))
|
|
}
|
|
case reqType == "web_search":
|
|
if incomingSessionID != "" && authID != "" {
|
|
_ = doc.Set("request.sessionId", scopeIncomingAntigravitySessionID(authID, incomingSessionID, derivedSessionID))
|
|
}
|
|
default:
|
|
incomingCascadeID := strings.TrimSpace(doc.Get("request.labels.cascade_id").String())
|
|
var sessionID string
|
|
if authID != "" {
|
|
if derivedSessionID != "" || incomingSessionID != "" {
|
|
sessionID = scopeIncomingAntigravitySessionID(authID, incomingSessionID, derivedSessionID)
|
|
} else if incomingCascadeID != "" {
|
|
sessionID = helps.ScopeAntigravitySessionIDForAuth(authID, incomingCascadeID)
|
|
}
|
|
} else {
|
|
sessionID = incomingSessionID
|
|
if sessionID == "" {
|
|
sessionID = derivedSessionID
|
|
}
|
|
if sessionID == "" {
|
|
sessionID = incomingCascadeID
|
|
}
|
|
}
|
|
if sessionID == "" {
|
|
sessionID = generateStableSessionIDDocForAuth(doc, authID)
|
|
}
|
|
_ = doc.Set("request.sessionId", sessionID)
|
|
if isAntigravityAgentRequestType(reqType) {
|
|
helps.ApplyAntigravityAgentEnvelopeWithOptions(doc, auth, sessionID, modelName, selection.Enum, crossAccountFailover)
|
|
if authID != "" {
|
|
if effectiveCascade := strings.TrimSpace(doc.Get("request.labels.cascade_id").String()); effectiveCascade != "" {
|
|
_ = doc.Set("request.sessionId", helps.HashAntigravitySessionID([]byte(effectiveCascade)))
|
|
}
|
|
}
|
|
} else {
|
|
if strings.TrimSpace(doc.Get("request.labels.request_id").String()) == "" {
|
|
if aicodeReqID := strings.TrimSpace(doc.Get("request.labels." + ojson.Escape("X-Aicode-Request-Id")).String()); aicodeReqID != "" {
|
|
_ = doc.Set("request.labels.request_id", aicodeReqID)
|
|
}
|
|
}
|
|
if strings.TrimSpace(doc.Get("requestId").String()) == "" {
|
|
prefix := reqType
|
|
if prefix == "" {
|
|
prefix = "agent"
|
|
}
|
|
_ = doc.Set("requestId", prefix+"/"+uuid.NewString())
|
|
}
|
|
}
|
|
}
|
|
|
|
// Strip ALL client-supplied service_account occurrences (including
|
|
// duplicate raw JSON keys) unconditionally before FinalizePayloadDoc
|
|
// (matching Hub 2.36.0 ccpahttp.shallowCloneAndStamp).
|
|
for _, saPath := range []string{"request.service_account", "request.serviceAccount", "service_account", "serviceAccount"} {
|
|
for doc.Get(saPath).Exists() {
|
|
beforeLen := doc.Len()
|
|
if errDel := doc.Delete(saPath); errDel != nil || doc.Len() >= beforeLen {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if !preserveSafetySettings {
|
|
_ = doc.Delete("request.safetySettings")
|
|
_ = doc.Delete("request.safety_settings")
|
|
}
|
|
if toolConfig := doc.Get("toolConfig"); toolConfig.Exists() {
|
|
if !doc.Get("request.toolConfig").Exists() && !doc.Get("request.tool_config").Exists() {
|
|
_ = doc.SetRawBytes("request.toolConfig", []byte(toolConfig.Raw))
|
|
}
|
|
_ = doc.Delete("toolConfig")
|
|
}
|
|
if toolConfigSnake := doc.Get("tool_config"); toolConfigSnake.Exists() {
|
|
if !doc.Get("request.toolConfig").Exists() && !doc.Get("request.tool_config").Exists() {
|
|
_ = doc.SetRawBytes("request.toolConfig", []byte(toolConfigSnake.Raw))
|
|
}
|
|
_ = doc.Delete("tool_config")
|
|
}
|
|
return !isImageModel && isAntigravityAgentRequestType(reqType)
|
|
}
|
|
|
|
func scopeIncomingAntigravitySessionID(authID, incomingSessionID, derivedSessionID string) string {
|
|
if derivedSessionID != "" {
|
|
return derivedSessionID
|
|
}
|
|
return helps.ScopeAntigravitySessionIDForAuth(authID, incomingSessionID)
|
|
}
|
|
|
|
func generateImageGenRequestID() string {
|
|
return fmt.Sprintf("image_gen/%d/%s/0", time.Now().UnixMilli(), uuid.NewString())
|
|
}
|
|
|
|
func generateSessionID() string {
|
|
randSourceMutex.Lock()
|
|
n := int64(randSource.Uint64())
|
|
randSourceMutex.Unlock()
|
|
return strconv.FormatInt(n, 10)
|
|
}
|
|
|
|
func generateStableSessionID(payload []byte) string {
|
|
contents := util.GetGJSONBytesNoCopy(payload, "request.contents")
|
|
if !contents.IsArray() {
|
|
contents = util.GetGJSONBytesNoCopy(payload, "contents")
|
|
}
|
|
return generateStableSessionIDFromContents(contents)
|
|
}
|
|
|
|
func generateStableSessionIDDoc(doc *ojson.Doc) string {
|
|
return generateStableSessionIDDocForAuth(doc, "")
|
|
}
|
|
|
|
func generateStableSessionIDDocForAuth(doc *ojson.Doc, authID string) string {
|
|
if doc == nil {
|
|
return generateSessionID()
|
|
}
|
|
contents := doc.Get("request.contents")
|
|
if !contents.IsArray() {
|
|
contents = doc.Get("contents")
|
|
}
|
|
return generateStableSessionIDFromContentsForAuth(contents, authID)
|
|
}
|
|
|
|
func generateStableSessionIDFromContents(contents ojson.Result) string {
|
|
return generateStableSessionIDFromContentsForAuth(contents, "")
|
|
}
|
|
|
|
func generateStableSessionIDFromContentsForAuth(contents ojson.Result, authID string) string {
|
|
if !contents.IsArray() {
|
|
return generateSessionID()
|
|
}
|
|
|
|
authID = strings.TrimSpace(authID)
|
|
stableID := ""
|
|
contents.ForEach(func(_, content ojson.Result) bool {
|
|
if content.Get("role").String() != "user" {
|
|
return true
|
|
}
|
|
text := ""
|
|
if parts := content.Get("parts"); parts.IsArray() {
|
|
parts.ForEach(func(_, part ojson.Result) bool {
|
|
if candidate := part.Get("text").String(); candidate != "" {
|
|
text = candidate
|
|
return false
|
|
}
|
|
return true
|
|
})
|
|
}
|
|
if text == "" {
|
|
return true
|
|
}
|
|
var hashInput []byte
|
|
if authID != "" {
|
|
// Place variable text and authID before the fixed domain suffix so trailing-byte
|
|
// changes avalanche into the sign bit of FNV-1a.
|
|
hashInput = []byte(text + "\x00" + authID + "\x00cli-proxy-api:antigravity:content-session")
|
|
} else {
|
|
hashInput = []byte(text)
|
|
}
|
|
stableID = helps.HashAntigravitySessionID(hashInput)
|
|
return false
|
|
})
|
|
if stableID != "" {
|
|
return stableID
|
|
}
|
|
return generateSessionID()
|
|
}
|
|
|
|
func antigravityRequestedMaxOutputTokensDoc(doc *ojson.Doc) (int, bool) {
|
|
if doc == nil {
|
|
return 0, false
|
|
}
|
|
maxOut := 0
|
|
found := false
|
|
for _, path := range []string{
|
|
"request.generationConfig.maxOutputTokens",
|
|
"request.generationConfig.max_output_tokens",
|
|
"request.generation_config.maxOutputTokens",
|
|
"request.generation_config.max_output_tokens",
|
|
} {
|
|
val := doc.Get(path)
|
|
if val.Exists() && val.Type == ojson.Number {
|
|
n := int(val.Int())
|
|
if !found || n > maxOut {
|
|
maxOut = n
|
|
found = true
|
|
}
|
|
}
|
|
}
|
|
return maxOut, found
|
|
}
|