1910 lines · 62.2 KB · Go
RawDownload
// Package executor provides runtime execution capabilities for various AI service providers.// This file implements the Antigravity executor that proxies requests to the antigravity// upstream using OAuth credentials.package executor import (	"bufio"	"bytes"	"context"	"crypto/sha256"	"crypto/tls"	"encoding/binary"	"encoding/json"	"errors"	"fmt"	"io"	"math/rand"	"net/http"	"net/url"	"strconv"	"strings"	"sync"	"time" 	"github.com/google/uuid"	"github.com/router-for-me/CLIProxyAPI/v6/internal/config"	"github.com/router-for-me/CLIProxyAPI/v6/internal/runtime/executor/helps"	"github.com/router-for-me/CLIProxyAPI/v6/internal/thinking"	"github.com/router-for-me/CLIProxyAPI/v6/internal/util"	sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"	cliproxyauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"	cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/executor"	sdktranslator "github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"	log "github.com/sirupsen/logrus"	"github.com/tidwall/gjson"	"github.com/tidwall/sjson") const (	antigravityBaseURLDaily        = "https://daily-cloudcode-pa.googleapis.com"	antigravitySandboxBaseURLDaily = "https://daily-cloudcode-pa.sandbox.googleapis.com"	antigravityBaseURLProd         = "https://cloudcode-pa.googleapis.com"	antigravityCountTokensPath     = "/v1internal:countTokens"	antigravityStreamPath          = "/v1internal:streamGenerateContent"	antigravityGeneratePath        = "/v1internal:generateContent"	antigravityClientID            = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"	antigravityClientSecret        = "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"	defaultAntigravityAgent        = "antigravity/1.19.6 darwin/arm64"	antigravityAuthType            = "antigravity"	refreshSkew                    = 3000 * time.Second	antigravityCreditsRetryTTL     = 5 * time.Hour	// systemInstruction              = "You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.**Absolute paths only****Proactiveness**") type antigravity429Category string const (	antigravity429Unknown        antigravity429Category = "unknown"	antigravity429RateLimited    antigravity429Category = "rate_limited"	antigravity429QuotaExhausted antigravity429Category = "quota_exhausted") var (	randSource                        = rand.New(rand.NewSource(time.Now().UnixNano()))	randSourceMutex                   sync.Mutex	antigravityCreditsExhaustedByAuth sync.Map	antigravityPreferCreditsByModel   sync.Map	antigravityQuotaExhaustedKeywords = []string{		"quota_exhausted",		"quota exhausted",	}	antigravityCreditsExhaustedKeywords = []string{		"google_one_ai",		"insufficient credit",		"insufficient credits",		"not enough credit",		"not enough credits",		"credit exhausted",		"credits exhausted",		"credit balance",		"minimumcreditamountforusage",		"minimum credit amount for usage",		"minimum credit",		"resource has been exhausted",	}) // AntigravityExecutor proxies requests to the antigravity upstream.type AntigravityExecutor struct {	cfg *config.Config} // NewAntigravityExecutor creates a new Antigravity executor instance.//// Parameters://   - cfg: The application configuration//// Returns://   - *AntigravityExecutor: A new Antigravity executor instancefunc NewAntigravityExecutor(cfg *config.Config) *AntigravityExecutor {	return &AntigravityExecutor{cfg: cfg}} // antigravityTransport is a singleton HTTP/1.1 transport shared by all Antigravity requests.// It is initialized once via antigravityTransportOnce to avoid leaking a new connection pool// (and the goroutines managing it) on every request.var (	antigravityTransport     *http.Transport	antigravityTransportOnce sync.Once) func cloneTransportWithHTTP11(base *http.Transport) *http.Transport {	if base == nil {		return nil	} 	clone := base.Clone()	clone.ForceAttemptHTTP2 = false	// Wipe TLSNextProto to prevent implicit HTTP/2 upgrade.	clone.TLSNextProto = make(map[string]func(authority string, c *tls.Conn) http.RoundTripper)	if clone.TLSClientConfig == nil {		clone.TLSClientConfig = &tls.Config{}	} else {		clone.TLSClientConfig = clone.TLSClientConfig.Clone()	}	// Actively advertise only HTTP/1.1 in the ALPN handshake.	clone.TLSClientConfig.NextProtos = []string{"http/1.1"}	return clone} // initAntigravityTransport creates the shared HTTP/1.1 transport exactly once.func initAntigravityTransport() {	base, ok := http.DefaultTransport.(*http.Transport)	if !ok {		base = &http.Transport{}	}	antigravityTransport = cloneTransportWithHTTP11(base)} // newAntigravityHTTPClient creates an HTTP client specifically for Antigravity,// enforcing HTTP/1.1 by disabling HTTP/2 to perfectly mimic Node.js https defaults.// The underlying Transport is a singleton to avoid leaking connection pools.func newAntigravityHTTPClient(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, timeout time.Duration) *http.Client {	antigravityTransportOnce.Do(initAntigravityTransport) 	client := helps.NewProxyAwareHTTPClient(ctx, cfg, auth, timeout)	// If no transport is set, use the shared HTTP/1.1 transport.	if client.Transport == nil {		client.Transport = antigravityTransport		return client	} 	// Preserve proxy settings from proxy-aware transports while forcing HTTP/1.1.	if transport, ok := client.Transport.(*http.Transport); ok {		client.Transport = cloneTransportWithHTTP11(transport)	}	return client} // Identifier returns the executor identifier.func (e *AntigravityExecutor) Identifier() string { return antigravityAuthType } // PrepareRequest injects Antigravity credentials into the outgoing HTTP request.func (e *AntigravityExecutor) PrepareRequest(req *http.Request, auth *cliproxyauth.Auth) error {	if req == nil {		return nil	}	token, _, errToken := e.ensureAccessToken(req.Context(), auth)	if errToken != nil {		return errToken	}	if strings.TrimSpace(token) == "" {		return statusErr{code: http.StatusUnauthorized, msg: "missing access token"}	}	req.Header.Set("Authorization", "Bearer "+token)	return nil} // HttpRequest injects Antigravity credentials into the request and executes it.// It uses a whitelist approach: all incoming headers are stripped and only// the minimum set required by the Antigravity protocol is explicitly set.func (e *AntigravityExecutor) HttpRequest(ctx context.Context, auth *cliproxyauth.Auth, req *http.Request) (*http.Response, error) {	if req == nil {		return nil, fmt.Errorf("antigravity executor: request is nil")	}	if ctx == nil {		ctx = req.Context()	}	httpReq := req.WithContext(ctx) 	// --- Whitelist: save only the headers we need from the original request ---	contentType := httpReq.Header.Get("Content-Type") 	// Wipe ALL incoming headers	for k := range httpReq.Header {		delete(httpReq.Header, k)	} 	// --- Set only the headers Antigravity actually sends ---	if contentType != "" {		httpReq.Header.Set("Content-Type", contentType)	}	// Content-Length is managed automatically by Go's http.Client from the Body	httpReq.Header.Set("User-Agent", resolveUserAgent(auth))	httpReq.Close = true // sends Connection: close 	// Inject Authorization: Bearer <token>	if err := e.PrepareRequest(httpReq, auth); err != nil {		return nil, err	} 	httpClient := newAntigravityHTTPClient(ctx, e.cfg, auth, 0)	return httpClient.Do(httpReq)} func injectEnabledCreditTypes(payload []byte) []byte {	if len(payload) == 0 {		return nil	}	if !gjson.ValidBytes(payload) {		return nil	}	updated, err := sjson.SetRawBytes(payload, "enabledCreditTypes", []byte(`["GOOGLE_ONE_AI"]`))	if err != nil {		return nil	}	return updated} func classifyAntigravity429(body []byte) antigravity429Category {	if len(body) == 0 {		return antigravity429Unknown	}	lowerBody := strings.ToLower(string(body))	for _, keyword := range antigravityQuotaExhaustedKeywords {		if strings.Contains(lowerBody, keyword) {			return antigravity429QuotaExhausted		}	}	status := strings.TrimSpace(gjson.GetBytes(body, "error.status").String())	if !strings.EqualFold(status, "RESOURCE_EXHAUSTED") {		return antigravity429Unknown	}	details := gjson.GetBytes(body, "error.details")	if !details.Exists() || !details.IsArray() {		return antigravity429Unknown	}	for _, detail := range details.Array() {		if detail.Get("@type").String() != "type.googleapis.com/google.rpc.ErrorInfo" {			continue		}		reason := strings.TrimSpace(detail.Get("reason").String())		if strings.EqualFold(reason, "QUOTA_EXHAUSTED") {			return antigravity429QuotaExhausted		}		if strings.EqualFold(reason, "RATE_LIMIT_EXCEEDED") {			return antigravity429RateLimited		}	}	return antigravity429Unknown} func antigravityCreditsRetryEnabled(cfg *config.Config) bool {	return cfg != nil && cfg.QuotaExceeded.AntigravityCredits} func antigravityCreditsExhausted(auth *cliproxyauth.Auth, now time.Time) bool {	if auth == nil || strings.TrimSpace(auth.ID) == "" {		return false	}	value, ok := antigravityCreditsExhaustedByAuth.Load(auth.ID)	if !ok {		return false	}	until, ok := value.(time.Time)	if !ok || until.IsZero() {		antigravityCreditsExhaustedByAuth.Delete(auth.ID)		return false	}	if !until.After(now) {		antigravityCreditsExhaustedByAuth.Delete(auth.ID)		return false	}	return true} func markAntigravityCreditsExhausted(auth *cliproxyauth.Auth, now time.Time) {	if auth == nil || strings.TrimSpace(auth.ID) == "" {		return	}	antigravityCreditsExhaustedByAuth.Store(auth.ID, now.Add(antigravityCreditsRetryTTL))} func clearAntigravityCreditsExhausted(auth *cliproxyauth.Auth) {	if auth == nil || strings.TrimSpace(auth.ID) == "" {		return	}	antigravityCreditsExhaustedByAuth.Delete(auth.ID)} func antigravityPreferCreditsKey(auth *cliproxyauth.Auth, modelName string) string {	if auth == nil {		return ""	}	authID := strings.TrimSpace(auth.ID)	modelName = strings.TrimSpace(modelName)	if authID == "" || modelName == "" {		return ""	}	return authID + "|" + modelName} func antigravityShouldPreferCredits(auth *cliproxyauth.Auth, modelName string, now time.Time) bool {	key := antigravityPreferCreditsKey(auth, modelName)	if key == "" {		return false	}	value, ok := antigravityPreferCreditsByModel.Load(key)	if !ok {		return false	}	until, ok := value.(time.Time)	if !ok || until.IsZero() {		antigravityPreferCreditsByModel.Delete(key)		return false	}	if !until.After(now) {		antigravityPreferCreditsByModel.Delete(key)		return false	}	return true} func markAntigravityPreferCredits(auth *cliproxyauth.Auth, modelName string, now time.Time, retryAfter *time.Duration) {	key := antigravityPreferCreditsKey(auth, modelName)	if key == "" {		return	}	until := now.Add(antigravityCreditsRetryTTL)	if retryAfter != nil && *retryAfter > 0 {		until = now.Add(*retryAfter)	}	antigravityPreferCreditsByModel.Store(key, until)} func clearAntigravityPreferCredits(auth *cliproxyauth.Auth, modelName string) {	key := antigravityPreferCreditsKey(auth, modelName)	if key == "" {		return	}	antigravityPreferCreditsByModel.Delete(key)} func shouldMarkAntigravityCreditsExhausted(statusCode int, body []byte, reqErr error) bool {	if reqErr != nil || statusCode == 0 {		return false	}	if statusCode >= http.StatusInternalServerError || statusCode == http.StatusRequestTimeout {		return false	}	lowerBody := strings.ToLower(string(body))	for _, keyword := range antigravityCreditsExhaustedKeywords {		if strings.Contains(lowerBody, keyword) {			return true		}	}	return false} func newAntigravityStatusErr(statusCode int, body []byte) statusErr {	err := statusErr{code: statusCode, msg: string(body)}	if statusCode == http.StatusTooManyRequests {		if retryAfter, parseErr := parseRetryDelay(body); parseErr == nil && retryAfter != nil {			err.retryAfter = retryAfter		}	}	return err} func (e *AntigravityExecutor) attemptCreditsFallback(	ctx context.Context,	auth *cliproxyauth.Auth,	httpClient *http.Client,	token string,	modelName string,	payload []byte,	stream bool,	alt string,	baseURL string,	originalBody []byte,) (*http.Response, bool) {	if !antigravityCreditsRetryEnabled(e.cfg) {		return nil, false	}	if classifyAntigravity429(originalBody) != antigravity429QuotaExhausted {		return nil, false	}	now := time.Now()	if antigravityCreditsExhausted(auth, now) {		return nil, false	}	creditsPayload := injectEnabledCreditTypes(payload)	if len(creditsPayload) == 0 {		return nil, false	} 	httpReq, errReq := e.buildRequest(ctx, auth, token, modelName, creditsPayload, stream, alt, baseURL)	if errReq != nil {		helps.RecordAPIResponseError(ctx, e.cfg, errReq)		return nil, true	}	httpResp, errDo := httpClient.Do(httpReq)	if errDo != nil {		helps.RecordAPIResponseError(ctx, e.cfg, errDo)		return nil, true	}	if httpResp.StatusCode >= http.StatusOK && httpResp.StatusCode < http.StatusMultipleChoices {		retryAfter, _ := parseRetryDelay(originalBody)		markAntigravityPreferCredits(auth, modelName, now, retryAfter)		clearAntigravityCreditsExhausted(auth)		return httpResp, true	} 	helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone())	bodyBytes, errRead := io.ReadAll(httpResp.Body)	if errClose := httpResp.Body.Close(); errClose != nil {		log.Errorf("antigravity executor: close credits fallback response body error: %v", errClose)	}	if errRead != nil {		helps.RecordAPIResponseError(ctx, e.cfg, errRead)		return nil, true	}	helps.AppendAPIResponseChunk(ctx, e.cfg, bodyBytes)	if shouldMarkAntigravityCreditsExhausted(httpResp.StatusCode, bodyBytes, nil) {		clearAntigravityPreferCredits(auth, modelName)		markAntigravityCreditsExhausted(auth, now)	}	return nil, true} // Execute performs a non-streaming request to the Antigravity API.func (e *AntigravityExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) {	if opts.Alt == "responses/compact" {		return resp, statusErr{code: http.StatusNotImplemented, msg: "/responses/compact not supported"}	}	baseModel := thinking.ParseSuffix(req.Model).ModelName	isClaude := strings.Contains(strings.ToLower(baseModel), "claude") 	if isClaude || strings.Contains(baseModel, "gemini-3-pro") || strings.Contains(baseModel, "gemini-3.1-flash-image") {		return e.executeClaudeNonStream(ctx, auth, req, opts)	} 	token, updatedAuth, errToken := e.ensureAccessToken(ctx, auth)	if errToken != nil {		return resp, errToken	}	if updatedAuth != nil {		auth = updatedAuth	} 	reporter := helps.NewUsageReporter(ctx, e.Identifier(), baseModel, auth)	defer reporter.TrackFailure(ctx, &err) 	from := opts.SourceFormat	to := sdktranslator.FromString("antigravity") 	originalPayloadSource := req.Payload	if len(opts.OriginalRequest) > 0 {		originalPayloadSource = opts.OriginalRequest	}	originalPayload := originalPayloadSource	originalTranslated := sdktranslator.TranslateRequest(from, to, baseModel, originalPayload, false)	translated := sdktranslator.TranslateRequest(from, to, baseModel, req.Payload, false) 	translated, err = thinking.ApplyThinking(translated, req.Model, from.String(), to.String(), e.Identifier())	if err != nil {		return resp, err	} 	requestedModel := helps.PayloadRequestedModel(opts, req.Model)	translated = helps.ApplyPayloadConfigWithRoot(e.cfg, baseModel, "antigravity", "request", translated, originalTranslated, requestedModel) 	baseURLs := antigravityBaseURLFallbackOrder(auth)	httpClient := newAntigravityHTTPClient(ctx, e.cfg, auth, 0) 	attempts := antigravityRetryAttempts(auth, e.cfg) attemptLoop:	for attempt := 0; attempt < attempts; attempt++ {		var lastStatus int		var lastBody []byte		var lastErr error 		for idx, baseURL := range baseURLs {			requestPayload := translated			usedCreditsDirect := false			if antigravityCreditsRetryEnabled(e.cfg) && antigravityShouldPreferCredits(auth, baseModel, time.Now()) {				if creditsPayload := injectEnabledCreditTypes(translated); len(creditsPayload) > 0 {					requestPayload = creditsPayload					usedCreditsDirect = true

Lines 1–500 of 1910.