Files
CLIProxyAPI/internal/runtime/executor/helps/antigravity_aicode_codec.go

2035 lines
68 KiB
Go

package helps
import (
"bytes"
"context"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/MoeForge/moego/ojson"
"github.com/router-for-me/CLIProxyAPI/v8/internal/auth/antigravity"
"golang.org/x/net/http/httpguts"
)
// AntigravityAICodeFallbackCreditExperience is the fallback AICode experience ID
// used when GOOGLE_ONE_AI credits are enabled on an unmapped model and neither a
// per-model experience nor a SurfaceConfig default experience is available.
const AntigravityAICodeFallbackCreditExperience = "chat-gemini-3.1-pro-low"
// AICodeStagedState captures which v1alpha defaults were materialized by
// StageAntigravityAICodeDefaultsDoc before FinalizePayloadDoc so post-finalization
// framing can honor user Payload.Override and Payload.Filter edits on both
// enabledCreditTypes and aicode.* without re-evaluating rules or silently
// dropping aicode fields or paid credits.
type AICodeStagedState struct {
StagedAICode bool
StagedExperience string
StagedCreditFallback bool
StagedEnabledCredits bool
StagedEnabledCreditsRaw string
}
// AICodeFramingOptions configures structural v1alpha framing for
// ToAICodeGenerateContentDocWithOptions and StageAntigravityAICodeDefaultsDoc.
type AICodeFramingOptions struct {
Experience string
DefaultExperience string
UserTier string
BusinessMode bool
Parent string
// DisableCreditFallback suppresses automatic credit-fallback experience
// synthesis for callers that want strict explicit experience enforcement.
DisableCreditFallback bool
// Staged carries pre-finalization staging metadata returned by
// StageAntigravityAICodeDefaultsDoc so post-finalization framing respects
// Payload.Filter and Payload.Override rules in both directions.
Staged *AICodeStagedState
// AICodeFiltered indicates that a matching Payload.Filter rule targeted
// "aicode" (or "aicode.experience") during FinalizePayloadDoc, preventing
// post-finalization framing from reconstructing filtered aicode fields or
// credit-fallback experiences.
AICodeFiltered bool
// CreditsFiltered indicates that a matching Payload.Filter rule explicitly
// targeted any Antigravity credits path (enabledCreditTypes,
// enabled_credit_types, aicode.enabledCredits, or aicode.enabled_credits),
// disabling paid credits regardless of cross-alias overrides.
CreditsFiltered bool
// ExperienceOverridden indicates that a matching Payload.Override /
// OverrideRaw rule targeted "aicode.experience" (or "aicode") during
// FinalizePayloadDoc, preventing both synthetic credit-fallback retraction
// when the overridden value equals the fallback default string and default/
// fallback experience substitution when the user explicitly set an empty
// experience.
ExperienceOverridden bool
}
var aicodeCanonicalRequestHoistFields = []string{
"contents",
"systemInstruction",
"tools",
"toolConfig",
"labels",
"safetySettings",
"generationConfig",
"sessionId",
}
func escapeAICodeOJSONKey(key string) string {
if !strings.ContainsAny(key, ".\\*?:@!") {
return key
}
var b strings.Builder
b.Grow(len(key) + 4)
for i := 0; i < len(key); i++ {
ch := key[i]
switch ch {
case '.', '\\', '*', '?', ':', '@', '!':
b.WriteByte('\\')
}
b.WriteByte(ch)
}
return b.String()
}
func isGoogleOneAICreditItem(item ojson.Result) bool {
switch item.Type {
case ojson.String:
return strings.EqualFold(strings.TrimSpace(item.String()), "GOOGLE_ONE_AI")
case ojson.Number:
return item.Int() == 1
default:
return false
}
}
// isNonCreditTypeUpgradeEnumItem reports whether item represents Hub 2.36.0
// UserTier.UpgradeType GOOGLE_ONE_HELIUM (4), which is NOT a Credit.CreditType
// and must never be emitted into enabledCreditTypes or aicode.enabledCredits.
func isNonCreditTypeUpgradeEnumItem(item ojson.Result) bool {
switch item.Type {
case ojson.String:
trimmed := strings.TrimSpace(item.String())
return strings.EqualFold(trimmed, "GOOGLE_ONE_HELIUM") || trimmed == "4"
case ojson.Number:
if n, ok := antigravity.ParseExactJSONInt64(item); ok && n == 4 {
return true
}
return false
default:
return false
}
}
func filterValidCreditTypesArray(res ojson.Result) (*ojson.Doc, bool, bool) {
if !res.Exists() || !res.IsArray() {
return nil, false, false
}
arrDoc := ojson.NewDocString("[]")
removed := false
kept := 0
for _, item := range res.Array() {
if isNonCreditTypeUpgradeEnumItem(item) {
removed = true
continue
}
if raw := strings.TrimSpace(item.Raw); raw != "" {
_ = arrDoc.SetRawBytes("-1", []byte(raw))
kept++
}
}
if !removed {
return nil, false, false
}
if kept == 0 {
return nil, true, false
}
return arrDoc, true, true
}
var antigravityAllCreditFieldPaths = []string{
"enabledCreditTypes",
"enabled_credit_types",
"request.enabledCreditTypes",
"request.enabled_credit_types",
"aicode.enabledCredits",
"aicode.enabled_credits",
"request.aicode.enabledCredits",
"request.aicode.enabled_credits",
}
// ValidateAntigravityFinalCreditTypesDoc performs read-only post-finalization
// validation on doc, rejecting any credit field containing Hub 2.36.0
// UserTier.UpgradeType GOOGLE_ONE_HELIUM (4) without mutating user-configured
// payload rules.
func ValidateAntigravityFinalCreditTypesDoc(doc *ojson.Doc) error {
if doc == nil {
return nil
}
for _, path := range antigravityAllCreditFieldPaths {
val := doc.Get(path)
if !val.Exists() || val.Type == ojson.Null {
continue
}
if val.IsArray() {
for _, item := range val.Array() {
if isNonCreditTypeUpgradeEnumItem(item) {
return fmt.Errorf("antigravity request rejected: %s must not contain non-CreditType upgrade enum GOOGLE_ONE_HELIUM (4)", path)
}
}
continue
}
if isNonCreditTypeUpgradeEnumItem(val) {
return fmt.Errorf("antigravity request rejected: %s must not contain non-CreditType upgrade enum GOOGLE_ONE_HELIUM (4)", path)
}
}
return nil
}
func hasGoogleOneAICreditType(res ojson.Result) bool {
if !res.Exists() || !res.IsArray() {
return false
}
for _, item := range res.Array() {
if isGoogleOneAICreditItem(item) {
return true
}
}
return false
}
// AntigravityAICodeDocHasPaidCredits reports whether a framed v1alpha outbound
// GenerateContentRequest document enables paid GOOGLE_ONE_AI credits.
func AntigravityAICodeDocHasPaidCredits(doc *ojson.Doc) bool {
if doc == nil {
return false
}
return hasGoogleOneAICreditType(doc.Get("aicode.enabledCredits"))
}
func hasV1InternalInitialPaidCredits(doc *ojson.Doc) bool {
return hasGoogleOneAICreditType(doc.Get("request.enabledCreditTypes")) ||
hasGoogleOneAICreditType(doc.Get("enabledCreditTypes")) ||
hasGoogleOneAICreditType(doc.Get("request.enabled_credit_types")) ||
hasGoogleOneAICreditType(doc.Get("enabled_credit_types"))
}
func resolveCanonicalAICodeField(reqObj, topObj ojson.Result, field string) ojson.Result {
if reqObj.Exists() && reqObj.IsObject() {
if val := reqObj.Get(field); val.Exists() {
return val
}
}
if topObj.Exists() && topObj.IsObject() {
if val := topObj.Get(field); val.Exists() {
return val
}
}
return ojson.Result{}
}
// hasAICodeInitialPaidCredits mirrors CanonicalizeAntigravityAICodeRequestDoc
// 1:1 (exact-key merge of top-level aicode into request.aicode, followed by
// canonical enabledCredits over snake_case enabled_credits) so v1internal
// credit hoisting and v1alpha canonicalization agree on every alias combination.
func hasAICodeInitialPaidCredits(doc *ojson.Doc) bool {
reqAICode := doc.Get("request.aicode")
topAICode := doc.Get("aicode")
if canon := resolveCanonicalAICodeField(reqAICode, topAICode, "enabledCredits"); canon.Exists() && canon.Type != ojson.Null && canon.Raw != "" {
return hasGoogleOneAICreditType(canon)
}
if alias := resolveCanonicalAICodeField(reqAICode, topAICode, "enabled_credits"); alias.Exists() && alias.Type != ojson.Null && alias.Raw != "" {
return hasGoogleOneAICreditType(alias)
}
return false
}
// AntigravityDocHasInitialPaidCredits reports whether an unfinalized
// Antigravity request document carries initial GOOGLE_ONE_AI credits under any
// supported credit path (request.enabledCreditTypes, enabledCreditTypes,
// snake_case aliases, or request.aicode / top-level aicode enabledCredits and
// enabled_credits using CanonicalizeAntigravityAICodeRequestDoc precedence).
func AntigravityDocHasInitialPaidCredits(doc *ojson.Doc) bool {
if doc == nil {
return false
}
return hasV1InternalInitialPaidCredits(doc) || hasAICodeInitialPaidCredits(doc)
}
// readRequestEnabledCreditTypes reads the effective request credit types after
// FinalizePayloadDoc, honoring both canonical camelCase
// request.enabledCreditTypes and explicit snake_case
// request.enabled_credit_types overrides (including empty [] disabling staged
// credits).
func readRequestEnabledCreditTypes(doc *ojson.Doc, stagedRaw string) ojson.Result {
if doc == nil {
return ojson.Result{}
}
reqECT := doc.Get("request.enabledCreditTypes")
reqECTSnake := doc.Get("request.enabled_credit_types")
if !reqECTSnake.Exists() {
return reqECT
}
if !reqECT.Exists() || reqECT.Type == ojson.Null {
return reqECTSnake
}
// Both StageAntigravityV1InternalCreditsDoc and StageAntigravityAICodeDefaultsDoc
// delete request.enabled_credit_types prior to FinalizePayloadDoc, so an
// explicit snake_case value present here came from a payload rule.
if !isNonEmptyJSONArray(reqECTSnake) {
return reqECTSnake
}
if stagedRaw != "" && reqECT.Raw == stagedRaw {
return reqECTSnake
}
return reqECT
}
// ExtractAntigravityAICodeExperienceDoc returns a trimmed caller-provided
// aicode.experience from request.aicode.experience or top-level
// aicode.experience, or "" when absent.
func ExtractAntigravityAICodeExperienceDoc(doc *ojson.Doc) string {
if doc == nil {
return ""
}
for _, path := range []string{"request.aicode.experience", "aicode.experience"} {
if res := doc.Get(path); res.Type == ojson.String {
if trimmed := strings.TrimSpace(res.String()); trimmed != "" {
return trimmed
}
}
}
return ""
}
// readAICodeEnabledCredits reads the canonical camelCase aicode.enabledCredits
// field so v1alpha and v1internal credit resolution treat enabledCredits and
// non-canonical snake_case enabled_credits identically after FinalizePayloadDoc.
func readAICodeEnabledCredits(aicodeObj ojson.Result) ojson.Result {
if !aicodeObj.Exists() || !aicodeObj.IsObject() {
return ojson.Result{}
}
return aicodeObj.Get("enabledCredits")
}
func isActiveAICodeThinkingLevel(res ojson.Result) bool {
if !res.Exists() || res.Type == ojson.Null {
return false
}
switch res.Type {
case ojson.String:
trimmed := strings.TrimSpace(res.String())
return trimmed != "" && !strings.EqualFold(trimmed, "THINKING_LEVEL_UNSPECIFIED") && trimmed != "0"
case ojson.Number:
return res.Int() != 0
default:
return false
}
}
func canonicalizeAICodeFieldAliasesDoc(doc *ojson.Doc, canonicalPath string, aliasPaths ...string) {
if doc == nil {
return
}
canon := doc.Get(canonicalPath)
hasCanon := canon.Exists() && canon.Type != ojson.Null && canon.Raw != ""
for _, alias := range aliasPaths {
val := doc.Get(alias)
if !val.Exists() {
continue
}
if !hasCanon && val.Type != ojson.Null && val.Raw != "" {
_ = doc.SetRawBytes(canonicalPath, []byte(val.Raw))
hasCanon = true
}
_ = doc.Delete(alias)
}
}
func canonicalizeAICodeExactObjectAliasDoc(doc *ojson.Doc, dstPath, srcPath string) {
if doc == nil {
return
}
src := doc.Get(srcPath)
if !src.Exists() {
return
}
if src.IsObject() {
dst := doc.Get(dstPath)
if !dst.IsObject() {
_ = doc.SetRawBytes(dstPath, []byte(src.Raw))
} else {
existing := make(map[string]struct{})
dst.ForEach(func(k, _ ojson.Result) bool {
existing[k.String()] = struct{}{}
return true
})
src.ForEach(func(k, v ojson.Result) bool {
key := k.String()
if _, ok := existing[key]; ok {
return true
}
if v.Raw != "" {
_ = doc.SetRawBytes(dstPath+"."+escapeAntigravityOJSONKey(key), []byte(v.Raw))
existing[key] = struct{}{}
}
return true
})
}
}
_ = doc.Delete(srcPath)
}
func canonicalizeAICodeFunctionCallingConfigAtDoc(doc *ojson.Doc, toolConfigPath string) {
if doc == nil || !doc.Get(toolConfigPath).IsObject() {
return
}
fccPath := toolConfigPath + ".functionCallingConfig"
snakeFCCPath := toolConfigPath + ".function_calling_config"
if snakeFCC := doc.Get(snakeFCCPath); snakeFCC.Exists() {
if snakeFCC.IsObject() {
MergeAntigravityProtoObjectDoc(doc, fccPath, snakeFCC)
}
_ = doc.Delete(snakeFCCPath)
}
if doc.Get(fccPath).IsObject() {
canonicalizeAICodeFieldAliasesDoc(doc, fccPath+".allowedFunctionNames", fccPath+".allowed_function_names")
}
}
func canonicalizeAICodeToolConfigDoc(doc *ojson.Doc) {
if doc == nil {
return
}
const dstPath = "request.toolConfig"
canonicalizeAICodeFunctionCallingConfigAtDoc(doc, dstPath)
for _, aliasPath := range []string{"request.tool_config", "toolConfig", "tool_config"} {
alias := doc.Get(aliasPath)
if !alias.Exists() {
continue
}
if alias.IsObject() {
if !doc.Get(dstPath).IsObject() {
_ = doc.SetRawBytes(dstPath, []byte(alias.Raw))
canonicalizeAICodeFunctionCallingConfigAtDoc(doc, dstPath)
} else {
MergeAntigravityProtoObjectDoc(doc, dstPath, alias, "functioncallingconfig")
if fcc := alias.Get("functionCallingConfig"); fcc.IsObject() {
MergeAntigravityProtoObjectDoc(doc, dstPath+".functionCallingConfig", fcc)
}
if fccSnake := alias.Get("function_calling_config"); fccSnake.IsObject() {
MergeAntigravityProtoObjectDoc(doc, dstPath+".functionCallingConfig", fccSnake)
}
}
}
_ = doc.Delete(aliasPath)
}
canonicalizeAICodeFunctionCallingConfigAtDoc(doc, dstPath)
}
var aicodeGenerationConfigFieldAliases = [][2]string{
{"topP", "top_p"},
{"topK", "top_k"},
{"maxOutputTokens", "max_output_tokens"},
{"candidateCount", "candidate_count"},
{"stopSequences", "stop_sequences"},
{"responseMimeType", "response_mime_type"},
{"responseSchema", "response_schema"},
{"responseJsonSchema", "response_json_schema"},
{"presencePenalty", "presence_penalty"},
{"frequencyPenalty", "frequency_penalty"},
{"responseLogprobs", "response_logprobs"},
{"responseModalities", "response_modalities"},
{"mediaResolution", "media_resolution"},
}
func canonicalizeAICodeThinkingConfigAtDoc(doc *ojson.Doc, genConfigPath string) {
if doc == nil || !doc.Get(genConfigPath).IsObject() {
return
}
tcPath := genConfigPath + ".thinkingConfig"
snakeTCPath := genConfigPath + ".thinking_config"
if snakeTC := doc.Get(snakeTCPath); snakeTC.Exists() {
if snakeTC.IsObject() {
MergeAntigravityProtoObjectDoc(doc, tcPath, snakeTC)
}
_ = doc.Delete(snakeTCPath)
}
if doc.Get(tcPath).IsObject() {
canonicalizeAICodeFieldAliasesDoc(doc, tcPath+".thinkingLevel", tcPath+".thinking_level")
canonicalizeAICodeFieldAliasesDoc(doc, tcPath+".thinkingBudget", tcPath+".thinking_budget")
canonicalizeAICodeFieldAliasesDoc(doc, tcPath+".includeThoughts", tcPath+".include_thoughts")
}
}
func canonicalizeAICodeGenerationConfigFieldsAtDoc(doc *ojson.Doc, genConfigPath string) {
if doc == nil || !doc.Get(genConfigPath).IsObject() {
return
}
for _, pair := range aicodeGenerationConfigFieldAliases {
canonicalizeAICodeFieldAliasesDoc(doc, genConfigPath+"."+pair[0], genConfigPath+"."+pair[1])
}
canonicalizeAICodeThinkingConfigAtDoc(doc, genConfigPath)
}
func scrubAICodeThinkingConfigAtDoc(doc *ojson.Doc, genConfigPath string) {
if doc == nil {
return
}
tcPath := genConfigPath + ".thinkingConfig"
tc := doc.Get(tcPath)
if !tc.Exists() || !tc.IsObject() {
return
}
if isActiveAICodeThinkingLevel(tc.Get("thinkingLevel")) {
_ = doc.Delete(tcPath + ".thinkingBudget")
_ = doc.Delete(tcPath + ".thinking_budget")
_ = doc.Delete(tcPath + ".thinking_level")
} else {
_ = doc.Delete(tcPath + ".thinkingLevel")
_ = doc.Delete(tcPath + ".thinking_level")
}
}
func canonicalizeAICodeGenerationConfigDoc(doc *ojson.Doc) {
if doc == nil {
return
}
const dstPath = "request.generationConfig"
canonicalizeAICodeGenerationConfigFieldsAtDoc(doc, dstPath)
for _, aliasPath := range []string{"request.generation_config", "generationConfig", "generation_config"} {
alias := doc.Get(aliasPath)
if !alias.Exists() {
continue
}
if alias.IsObject() {
if !doc.Get(dstPath).IsObject() {
_ = doc.SetRawBytes(dstPath, []byte(alias.Raw))
canonicalizeAICodeGenerationConfigFieldsAtDoc(doc, dstPath)
} else {
MergeAntigravityProtoObjectDoc(doc, dstPath, alias, "thinkingconfig")
if tc := alias.Get("thinkingConfig"); tc.IsObject() {
MergeAntigravityProtoObjectDoc(doc, dstPath+".thinkingConfig", tc)
}
if tcSnake := alias.Get("thinking_config"); tcSnake.IsObject() {
MergeAntigravityProtoObjectDoc(doc, dstPath+".thinkingConfig", tcSnake)
}
}
}
_ = doc.Delete(aliasPath)
}
canonicalizeAICodeGenerationConfigFieldsAtDoc(doc, dstPath)
scrubAICodeThinkingConfigAtDoc(doc, dstPath)
}
// CanonicalizeAntigravitySessionIDDoc folds snake_case and top-level session ID
// aliases (request.session_id, sessionId, session_id) into canonical
// request.sessionId and removes all alias copies.
//
// Callers should invoke this BEFORE envelope construction so incoming session_id
// values are preserved rather than overwritten by a newly generated session ID.
func CanonicalizeAntigravitySessionIDDoc(doc *ojson.Doc) {
if doc == nil {
return
}
canon := doc.Get("request.sessionId")
hasCanon := canon.Exists() && canon.Type == ojson.String && strings.TrimSpace(canon.String()) != ""
for _, alias := range []string{"request.session_id", "sessionId", "session_id"} {
val := doc.Get(alias)
if !val.Exists() {
continue
}
if !hasCanon && val.Type == ojson.String {
if trimmed := strings.TrimSpace(val.String()); trimmed != "" {
_ = doc.Set("request.sessionId", trimmed)
hasCanon = true
}
}
_ = doc.Delete(alias)
}
}
// CanonicalizeAntigravityAICodeRequestDoc folds snake_case and top-level
// duplicate request fields into their single canonical request.* camelCase paths,
// scrubs built-in ThinkingConfig mutual exclusivity (thinkingLevel vs.
// thinkingBudget), and removes all alias copies.
//
// Callers MUST run this BEFORE FinalizePayloadDoc so user payload filter and
// override rules operate on the single canonical field set and subsequent
// v1alpha framing cannot resurrect deleted fields or overwrite user-configured
// values.
func canonicalizeAICodeMetadataFieldsDoc(doc *ojson.Doc) {
if doc == nil {
return
}
canonicalizeAICodeFieldAliasesDoc(doc, "request.parent", "parent")
canonicalizeAICodeExactObjectAliasDoc(doc, "request.entitlement", "entitlement")
if doc.Get("request.entitlement").IsObject() {
canonicalizeAICodeFieldAliasesDoc(doc, "request.entitlement.userTier", "request.entitlement.user_tier")
}
canonicalizeAICodeExactObjectAliasDoc(doc, "request.aicode", "aicode")
if doc.Get("request.aicode").IsObject() {
canonicalizeAICodeFieldAliasesDoc(doc, "request.aicode.enabledCredits", "request.aicode.enabled_credits")
}
}
// CanonicalizeAntigravityLabelsDoc merges flat top-level labels into canonical
// request.labels and removes the top-level labels alias. Callers should invoke
// this BEFORE agent envelope construction so caller-supplied top-level labels
// (such as cascade_id, root_cascade_id, parent_cascade_id) are preserved rather
// than overwritten by freshly generated defaults.
func CanonicalizeAntigravityLabelsDoc(doc *ojson.Doc) {
canonicalizeAICodeExactObjectAliasDoc(doc, "request.labels", "labels")
}
func CanonicalizeAntigravityAICodeRequestDoc(doc *ojson.Doc) {
if doc == nil {
return
}
canonicalizeAICodeFieldAliasesDoc(doc, "request.contents", "contents")
canonicalizeAICodeFieldAliasesDoc(doc, "request.systemInstruction", "request.system_instruction", "systemInstruction", "system_instruction")
canonicalizeAICodeFieldAliasesDoc(doc, "request.tools", "tools")
canonicalizeAICodeToolConfigDoc(doc)
CanonicalizeAntigravityLabelsDoc(doc)
canonicalizeAICodeFieldAliasesDoc(doc, "request.safetySettings", "request.safety_settings", "safetySettings", "safety_settings")
canonicalizeAICodeGenerationConfigDoc(doc)
CanonicalizeAntigravitySessionIDDoc(doc)
canonicalizeAICodeMetadataFieldsDoc(doc)
}
var aicodeOnlyFieldPaths = []string{
"parent", "request.parent",
"entitlement", "request.entitlement",
"aicode", "request.aicode",
}
// HoistAntigravityAICodeInitialCreditsDoc preserves initial GOOGLE_ONE_AI
// credits carried solely under request.aicode or top-level aicode
// (enabledCredits / enabled_credits with CanonicalizeAntigravityAICodeRequestDoc
// precedence) by normalizing them into enabledCreditTypes BEFORE
// StripAntigravityAICodeOnlyFieldsDoc deletes v1alpha-only aicode containers.
func HoistAntigravityAICodeInitialCreditsDoc(doc *ojson.Doc) {
if doc == nil || hasV1InternalInitialPaidCredits(doc) || !hasAICodeInitialPaidCredits(doc) {
return
}
for _, path := range []string{"enabledCreditTypes", "enabled_credit_types", "request.enabledCreditTypes", "request.enabled_credit_types"} {
val := doc.Get(path)
if !val.Exists() || val.Type == ojson.Null || val.Raw == "" {
continue
}
if val.IsArray() {
_ = doc.Set(path+".-1", "GOOGLE_ONE_AI")
return
}
break
}
_ = doc.SetRawBytes("enabledCreditTypes", []byte(`["GOOGLE_ONE_AI"]`))
}
// StripAntigravityAICodeOnlyFieldsDoc removes v1alpha-only fields (parent,
// entitlement, aicode) from both top-level and request.* containers so
// v1internal requests, fallback, and continuation snapshots remain pure v1internal.
func StripAntigravityAICodeOnlyFieldsDoc(doc *ojson.Doc) {
if doc == nil {
return
}
for _, path := range aicodeOnlyFieldPaths {
_ = doc.Delete(path)
}
}
var v1InternalCreditFieldPaths = []string{
"request.enabledCreditTypes",
"request.enabled_credit_types",
"enabledCreditTypes",
"enabled_credit_types",
}
// V1InternalCreditsStagedState captures whether StageAntigravityV1InternalCreditsDoc
// mirrored initial GOOGLE_ONE_AI credits onto request.aicode.enabledCredits
// alongside request.enabledCreditTypes before FinalizePayloadDoc so post-finalization
// v1internal framing applies the exact same dual-alias credit resolution as
// v1alpha before stripping v1alpha-only fields.
type V1InternalCreditsStagedState struct {
StagedEnabledCredits bool
StagedRaw string
StagedAICodeRaw string
SuppressedInitialPaidCredits bool
}
// StageAntigravityV1InternalCreditsDoc moves top-level enabledCreditTypes
// (and snake_case aliases) into request.enabledCreditTypes, mirrors
// GOOGLE_ONE_AI credits onto request.aicode.enabledCredits using the exact same
// normalized ["GOOGLE_ONE_AI"] slice as StageAntigravityAICodeDefaultsDoc,
// optionally stages a non-empty resolved experience onto
// request.aicode.experience, and deletes top-level and snake_case copies BEFORE
// FinalizePayloadDoc so user Payload.Filter and Payload.Override rules
// (including Exist: ["aicode.experience"] conditions and index filters like
// aicode.enabledCredits.0) evaluate identically across direct v1internal,
// continuation, and 403 v1alpha -> v1internal fallback paths before
// FrameAntigravityV1InternalDocForContext strips request.aicode.
func StageAntigravityV1InternalCreditsDoc(doc *ojson.Doc, experience ...string) V1InternalCreditsStagedState {
var staged V1InternalCreditsStagedState
if doc == nil {
return staged
}
var chosen ojson.Result
for _, path := range []string{"enabledCreditTypes", "enabled_credit_types", "request.enabledCreditTypes", "request.enabled_credit_types"} {
val := doc.Get(path)
if val.Exists() && val.Type != ojson.Null && val.Raw != "" {
chosen = val
break
}
}
_ = doc.Delete("enabledCreditTypes")
_ = doc.Delete("enabled_credit_types")
_ = doc.Delete("request.enabled_credit_types")
if doc.Get("request.aicode.enabled_credits").Exists() {
_ = doc.Delete("request.aicode.enabled_credits")
}
if chosen.Exists() && chosen.Type != ojson.Null && chosen.Raw != "" {
rawBytes := []byte(chosen.Raw)
hasEffective := true
if filteredDoc, changed, hasRemaining := filterValidCreditTypesArray(chosen); changed {
if hasRemaining {
rawBytes = filteredDoc.Bytes()
} else {
hasEffective = false
}
}
if hasEffective {
_ = doc.SetRawBytes("request.enabledCreditTypes", rawBytes)
effectiveECT := doc.Get("request.enabledCreditTypes")
staged.StagedRaw = effectiveECT.Raw
if hasGoogleOneAICreditType(effectiveECT) {
_ = doc.SetRawBytes("request.aicode.enabledCredits", []byte(`["GOOGLE_ONE_AI"]`))
staged.StagedEnabledCredits = true
staged.StagedAICodeRaw = doc.Get("request.aicode.enabledCredits").Raw
}
} else {
_ = doc.Delete("request.enabledCreditTypes")
}
}
if len(experience) > 0 {
if trimmedExp := strings.TrimSpace(experience[0]); trimmedExp != "" {
_ = doc.Set("request.aicode.experience", trimmedExp)
}
}
return staged
}
// AntigravityPayloadFiltersCredits reports whether a matching Payload.Filter
// rule recorded during FinalizePayloadDoc explicitly targeted any Antigravity
// credits alias (enabledCreditTypes, enabled_credit_types, aicode.enabledCredits,
// or aicode.enabled_credits). Filtering the ancestor "aicode" object alone does
// NOT trigger this helper so Filter:["aicode"] with active credits still rejects
// consistently instead of silently dropping paid credits.
func AntigravityPayloadFiltersCredits(ctx context.Context) bool {
return PayloadFiltersExactPath(ctx, "enabledCreditTypes") ||
PayloadFiltersExactPath(ctx, "enabled_credit_types") ||
PayloadFiltersExactPath(ctx, "aicode.enabledCredits") ||
PayloadFiltersExactPath(ctx, "aicode.enabled_credits")
}
// FrameAntigravityV1InternalDoc performs structural v1internal transport framing
// without mutating doc: it omits v1alpha-only protocol fields (parent,
// entitlement, aicode) that do not exist in the v1internal protobuf schema, and
// hoists request.enabledCreditTypes back out to top-level enabledCreditTypes
// when present and non-empty (deleting both top-level and nested copies when
// absent or empty so Payload.Filter/Override rules on enabledCreditTypes are
// honored identically on v1internal).
func FrameAntigravityV1InternalDoc(doc *ojson.Doc) *ojson.Doc {
return frameAntigravityV1InternalDoc(nil, doc, false, nil)
}
// FrameAntigravityV1InternalDocForContext performs structural v1internal
// transport framing without mutating doc, honoring dual-alias credit overrides
// and filters (e.g. Override:{"aicode.enabledCredits":[]},
// Filter:["aicode.enabledCredits.0"], Filter:["aicode.enabledCredits"])
// evaluated during FinalizePayloadDoc across direct v1internal, continuation,
// and 403 fallback before stripping v1alpha-only fields.
func FrameAntigravityV1InternalDocForContext(ctx context.Context, doc *ojson.Doc, staged V1InternalCreditsStagedState) *ojson.Doc {
return frameAntigravityV1InternalDoc(ctx, doc, AntigravityPayloadFiltersCredits(ctx), &staged)
}
// FrameAntigravityV1InternalCountTokensDoc performs structural v1internal
// CountTokens framing without mutating doc: per v1internal_prediction_service.proto,
// CountTokensRequest contains only "request" and must omit AICode-only fields
// as well as enabledCreditTypes at both top level and under request.*.
func FrameAntigravityV1InternalCountTokensDoc(doc *ojson.Doc) *ojson.Doc {
return frameAntigravityV1InternalDoc(nil, doc, true, nil)
}
func isNonEmptyJSONArray(res ojson.Result) bool {
return res.Exists() && res.IsArray() && len(res.Array()) > 0
}
func mergeAICodeCreditsWithNonPaid(reqECT, aicodeEC ojson.Result) ojson.Result {
if !isNonEmptyJSONArray(reqECT) || !isNonEmptyJSONArray(aicodeEC) {
return aicodeEC
}
arrDoc := ojson.NewDocString("[]")
seenRaw := make(map[string]struct{})
hasPaid := false
for _, item := range reqECT.Array() {
raw := strings.TrimSpace(item.Raw)
if raw == "" {
continue
}
if isGoogleOneAICreditItem(item) {
if hasPaid {
continue
}
hasPaid = true
}
if _, dup := seenRaw[raw]; dup {
continue
}
seenRaw[raw] = struct{}{}
_ = arrDoc.SetRawBytes("-1", []byte(raw))
}
for _, item := range aicodeEC.Array() {
raw := strings.TrimSpace(item.Raw)
if raw == "" {
continue
}
if isGoogleOneAICreditItem(item) {
if hasPaid {
continue
}
hasPaid = true
}
if _, dup := seenRaw[raw]; dup {
continue
}
seenRaw[raw] = struct{}{}
_ = arrDoc.SetRawBytes("-1", []byte(raw))
}
return ojson.ParseBytes(arrDoc.Bytes())
}
func resolveV1InternalEffectiveCredits(ctx context.Context, doc *ojson.Doc, omitCredits bool, staged *V1InternalCreditsStagedState) (ojson.Result, bool) {
if doc == nil || omitCredits {
return ojson.Result{}, false
}
stagedRaw := ""
if staged != nil {
stagedRaw = staged.StagedRaw
}
reqECT := readRequestEnabledCreditTypes(doc, stagedRaw)
reqAICode := doc.Get("request.aicode")
hasAICode := reqAICode.Exists() && reqAICode.IsObject()
aicodeEC := readAICodeEnabledCredits(reqAICode)
// Standalone framing without staging metadata inspects only request.enabledCreditTypes.
if staged == nil {
if isNonEmptyJSONArray(reqECT) {
if filteredDoc, changed, hasRemaining := filterValidCreditTypesArray(reqECT); changed {
if hasRemaining {
return ojson.ParseBytes(filteredDoc.Bytes()), true
}
return ojson.Result{}, false
}
return reqECT, true
}
return ojson.Result{}, false
}
aicodeOverridden := PayloadOverridesPath(ctx, "aicode.enabledCredits") ||
PayloadOverridesPath(ctx, "aicode.enabled_credits") ||
PayloadOverridesPath(ctx, "aicode")
ectOverridden := PayloadOverridesPath(ctx, "enabledCreditTypes") ||
PayloadOverridesPath(ctx, "enabled_credit_types")
if staged.StagedEnabledCredits {
// GOOGLE_ONE_AI credits were mirrored onto request.aicode.enabledCredits
// as normalized ["GOOGLE_ONE_AI"] alongside request.enabledCreditTypes
// before FinalizePayloadDoc. Clearing, emptying, or index-filtering
// either alias disables credits consistently with v1alpha; filtering the
// whole aicode object alone (!hasAICode) preserves
// request.enabledCreditTypes to stay consistent with v1alpha.
if !isNonEmptyJSONArray(reqECT) {
return ojson.Result{}, false
}
if hasAICode {
if !isNonEmptyJSONArray(aicodeEC) {
return ojson.Result{}, false
}
ectChanged := ectOverridden || (staged.StagedRaw != "" && reqECT.Raw != staged.StagedRaw)
aicodeBaseline := staged.StagedAICodeRaw
if aicodeBaseline == "" {
aicodeBaseline = staged.StagedRaw
}
aicodeChanged := aicodeOverridden || (aicodeBaseline != "" && aicodeEC.Raw != aicodeBaseline)
if aicodeChanged && !ectChanged {
if hasGoogleOneAICreditType(aicodeEC) {
return mergeAICodeCreditsWithNonPaid(reqECT, aicodeEC), true
}
return aicodeEC, true
}
if ectChanged && !aicodeChanged {
return reqECT, true
}
if hasGoogleOneAICreditType(reqECT) && !hasGoogleOneAICreditType(aicodeEC) {
return aicodeEC, true
}
}
return reqECT, true
}
// Credits were not staged onto request.aicode.enabledCredits before
// FinalizePayloadDoc (including 403 fallback when paid credits were
// suppressed on leg 1). Honor explicit aicode.enabledCredits writes via
// PayloadOverridesPath (merging with untouched non-paid enabledCreditTypes
// such as "OTHER" when enabling GOOGLE_ONE_AI), and keep index-0 filters on
// suppressed initial paid credits in parity with direct v1internal.
if hasAICode && aicodeEC.Exists() {
if !isNonEmptyJSONArray(aicodeEC) {
return ojson.Result{}, false
}
ectChanged := ectOverridden || (staged.StagedRaw != "" && reqECT.Raw != staged.StagedRaw)
if aicodeOverridden && !ectChanged && isNonEmptyJSONArray(reqECT) && hasGoogleOneAICreditType(aicodeEC) {
return mergeAICodeCreditsWithNonPaid(reqECT, aicodeEC), true
}
return aicodeEC, true
}
if staged.SuppressedInitialPaidCredits && !ectOverridden && !aicodeOverridden &&
(PayloadFiltersExactPath(ctx, "aicode.enabledCredits.0") || PayloadFiltersExactPath(ctx, "aicode.enabled_credits.0")) {
return ojson.Result{}, false
}
if isNonEmptyJSONArray(reqECT) {
return reqECT, true
}
return ojson.Result{}, false
}
func stripGoogleOneAICreditsFromArray(res ojson.Result) (*ojson.Doc, bool, bool) {
if !res.Exists() || !res.IsArray() {
return nil, false, false
}
arrDoc := ojson.NewDocString("[]")
removed := false
kept := 0
for _, item := range res.Array() {
if isGoogleOneAICreditItem(item) {
removed = true
continue
}
if raw := strings.TrimSpace(item.Raw); raw != "" {
_ = arrDoc.SetRawBytes("-1", []byte(raw))
kept++
}
}
if !removed {
return nil, false, false
}
if kept == 0 {
return nil, true, false
}
return arrDoc, true, true
}
// SuppressAntigravityV1InternalPaidCreditsDoc returns a v1internal document with
// GOOGLE_ONE_AI removed from enabledCreditTypes (and any snake_case or nested
// credit copies) without mutating doc. If no non-GOOGLE_ONE_AI credit entries
// remain, the field is deleted completely; all non-credit fields are preserved.
func SuppressAntigravityV1InternalPaidCreditsDoc(doc *ojson.Doc) *ojson.Doc {
if doc == nil {
return nil
}
needsEdit := false
for _, path := range v1InternalCreditFieldPaths {
if hasGoogleOneAICreditType(doc.Get(path)) {
needsEdit = true
break
}
}
if !needsEdit {
return doc
}
out := ojson.NewDoc(doc.Bytes())
for _, path := range v1InternalCreditFieldPaths {
filteredDoc, changed, hasRemaining := stripGoogleOneAICreditsFromArray(out.Get(path))
if !changed {
continue
}
if hasRemaining {
_ = out.SetRawBytes(path, filteredDoc.Bytes())
} else {
_ = out.Delete(path)
}
}
return out
}
func frameAntigravityV1InternalDoc(ctx context.Context, doc *ojson.Doc, omitCredits bool, staged *V1InternalCreditsStagedState) *ojson.Doc {
if doc == nil {
return nil
}
needsFrame := false
for _, path := range aicodeOnlyFieldPaths {
if doc.Get(path).Exists() {
needsFrame = true
break
}
}
if !needsFrame {
for _, path := range v1InternalCreditFieldPaths {
if doc.Get(path).Exists() {
needsFrame = true
break
}
}
}
if !needsFrame {
return doc
}
framed := ojson.NewDoc(doc.Bytes())
effectiveCredits, hasCredits := resolveV1InternalEffectiveCredits(ctx, framed, omitCredits, staged)
StripAntigravityAICodeOnlyFieldsDoc(framed)
_ = framed.Delete("request.enabledCreditTypes")
_ = framed.Delete("request.enabled_credit_types")
_ = framed.Delete("enabled_credit_types")
if hasCredits {
_ = framed.SetRawBytes("enabledCreditTypes", []byte(effectiveCredits.Raw))
} else {
_ = framed.Delete("enabledCreditTypes")
}
return framed
}
func aicodeHasNonCreditFields(aicodeObj ojson.Result) bool {
if !aicodeObj.Exists() || !aicodeObj.IsObject() {
return false
}
found := false
aicodeObj.ForEach(func(k, v ojson.Result) bool {
switch k.Str {
case "experience", "enabledCredits", "enabled_credits":
return true
}
if v.Exists() && v.Type != ojson.Null && strings.TrimSpace(v.Raw) != "" {
found = true
return false
}
return true
})
return found
}
func aicodeHasExplicitNonEmptyCredits(aicodeObj ojson.Result) bool {
res := readAICodeEnabledCredits(aicodeObj)
if !res.Exists() || res.Type == ojson.Null {
return false
}
if res.IsArray() {
for _, item := range res.Array() {
if !isNonCreditTypeUpgradeEnumItem(item) {
return true
}
}
return false
}
return strings.TrimSpace(res.Raw) != ""
}
// StageAntigravityAICodeDefaultsDoc materializes default v1alpha fields
// (request.enabledCreditTypes, request.aicode, request.entitlement,
// request.parent) on doc BEFORE FinalizePayloadDoc so user payload
// Default/Override/Filter rules (which target root "request") evaluate and
// finalize them as the last semantic barrier.
func StageAntigravityAICodeDefaultsDoc(doc *ojson.Doc, opts AICodeFramingOptions) AICodeStagedState {
var staged AICodeStagedState
if doc == nil {
return staged
}
trimmedExp := strings.TrimSpace(opts.Experience)
trimmedDefaultExp := strings.TrimSpace(opts.DefaultExperience)
trimmedTier := strings.TrimSpace(opts.UserTier)
existingAICode := doc.Get("request.aicode")
hasExistingAICode := existingAICode.Exists() && existingAICode.IsObject()
effectiveExp := ""
if hasExistingAICode {
if expRes := existingAICode.Get("experience"); expRes.Type == ojson.String {
effectiveExp = strings.TrimSpace(expRes.String())
}
}
if effectiveExp == "" {
effectiveExp = trimmedExp
}
hasGoogleOneCredit := AntigravityDocHasInitialPaidCredits(doc)
// Canonicalize credit signaling onto request.enabledCreditTypes (and delete
// top-level/snake_case copies) so user Payload.Filter/Override rules targeting
// either enabledCreditTypes or aicode.enabledCredits control credits cleanly.
_ = doc.Delete("enabledCreditTypes")
_ = doc.Delete("enabled_credit_types")
_ = doc.Delete("request.enabled_credit_types")
if doc.Get("request.aicode.enabled_credits").Exists() {
_ = doc.Delete("request.aicode.enabled_credits")
}
if hasGoogleOneCredit {
_ = doc.SetRawBytes("request.enabledCreditTypes", []byte(`["GOOGLE_ONE_AI"]`))
staged.StagedEnabledCredits = true
staged.StagedEnabledCreditsRaw = doc.Get("request.enabledCreditTypes").Raw
} else {
if existingECT := doc.Get("request.enabledCreditTypes"); existingECT.Exists() {
if filteredDoc, changed, hasRemaining := filterValidCreditTypesArray(existingECT); changed {
if hasRemaining {
_ = doc.SetRawBytes("request.enabledCreditTypes", filteredDoc.Bytes())
} else {
_ = doc.Delete("request.enabledCreditTypes")
}
}
}
if existingAICodeEC := doc.Get("request.aicode.enabledCredits"); existingAICodeEC.Exists() {
if filteredDoc, changed, hasRemaining := filterValidCreditTypesArray(existingAICodeEC); changed {
if hasRemaining {
_ = doc.SetRawBytes("request.aicode.enabledCredits", filteredDoc.Bytes())
} else {
_ = doc.Delete("request.aicode.enabledCredits")
}
}
}
}
if effectiveExp == "" && hasGoogleOneCredit && !opts.DisableCreditFallback {
if trimmedDefaultExp != "" {
effectiveExp = trimmedDefaultExp
} else {
effectiveExp = AntigravityAICodeFallbackCreditExperience
}
staged.StagedCreditFallback = true
}
if effectiveExp != "" {
_ = doc.Set("request.aicode.experience", effectiveExp)
staged.StagedAICode = true
staged.StagedExperience = effectiveExp
if hasGoogleOneCredit {
_ = doc.SetRawBytes("request.aicode.enabledCredits", []byte(`["GOOGLE_ONE_AI"]`))
} else if doc.Get("request.aicode.enabledCredits").Exists() {
_ = doc.Delete("request.aicode.enabledCredits")
}
}
if trimmedTier != "" {
if existingTier := doc.Get("request.entitlement.userTier"); !existingTier.Exists() || strings.TrimSpace(existingTier.String()) == "" {
_ = doc.Set("request.entitlement.userTier", trimmedTier)
}
}
if opts.BusinessMode {
existingParent := doc.Get("request.parent")
if !existingParent.Exists() || existingParent.Type != ojson.String || strings.TrimSpace(existingParent.String()) == "" {
if formattedParent := FormatAntigravityBusinessParent(opts.Parent); formattedParent != "" {
_ = doc.Set("request.parent", formattedParent)
}
}
} else {
_ = doc.Delete("request.parent")
}
return staged
}
// ToAICodeGenerateContentDoc converts a finalized v1internal request document
// into a flat aicode.googleapis.com (v1alpha) GenerateContentRequest *ojson.Doc
// without mutating v1InternalDoc.
func ToAICodeGenerateContentDoc(v1InternalDoc *ojson.Doc, experience, userTier string, businessMode bool) (*ojson.Doc, http.Header, error) {
return ToAICodeGenerateContentDocWithOptions(v1InternalDoc, AICodeFramingOptions{
Experience: experience,
UserTier: userTier,
BusinessMode: businessMode,
})
}
// ToAICodeGenerateContentDocWithOptions converts a finalized v1internal request
// document into a flat aicode.googleapis.com / businessaicode.googleapis.com
// (v1alpha) GenerateContentRequest *ojson.Doc without mutating v1InternalDoc.
//
// This helper performs structural transport framing and read-only validation
// AFTER FinalizePayloadDoc so user payload overrides are preserved and filtered
// fields are never restored: it reads ONLY canonical request.* fields (falling
// back to top-level aicode/entitlement/parent only for direct uncanonicalized
// callers), strictly enforces protobuf oneof inference mutual exclusivity
// (aicode only when experience is non-empty, otherwise model), uses
// DefaultExperience or AntigravityAICodeFallbackCreditExperience when
// GOOGLE_ONE_AI credits are enabled unless DisableCreditFallback is set,
// validates ThinkingConfig mutual exclusivity, omits continuationToken, emits
// parent only in Business AICode mode, and omits sessionId in business mode.
func ToAICodeGenerateContentDocWithOptions(v1InternalDoc *ojson.Doc, opts AICodeFramingOptions) (*ojson.Doc, http.Header, error) {
out := ojson.NewDocString("{}")
extraHeaders := make(http.Header)
trimmedExp := strings.TrimSpace(opts.Experience)
trimmedDefaultExp := strings.TrimSpace(opts.DefaultExperience)
trimmedTier := strings.TrimSpace(opts.UserTier)
if v1InternalDoc == nil {
if trimmedExp != "" {
_ = out.Set("aicode.experience", trimmedExp)
}
if opts.Staged == nil && trimmedTier != "" {
_ = out.Set("entitlement.userTier", trimmedTier)
}
if opts.Staged == nil && opts.BusinessMode {
if formattedParent := FormatAntigravityBusinessParent(opts.Parent); formattedParent != "" {
_ = out.Set("parent", formattedParent)
}
}
return out, extraHeaders, nil
}
if errLabels := ValidateAntigravityRequestLabelsDoc(v1InternalDoc); errLabels != nil {
return nil, nil, errLabels
}
if !opts.CreditsFiltered {
if errCredits := ValidateAntigravityFinalCreditTypesDoc(v1InternalDoc); errCredits != nil {
return nil, nil, errCredits
}
}
existingAICode := v1InternalDoc.Get("request.aicode")
if opts.Staged == nil && (!existingAICode.Exists() || !existingAICode.IsObject()) {
existingAICode = v1InternalDoc.Get("aicode")
}
hasExistingAICode := existingAICode.Exists() && existingAICode.IsObject()
effectiveExp := ""
if hasExistingAICode {
if expRes := existingAICode.Get("experience"); expRes.Type == ojson.String {
effectiveExp = strings.TrimSpace(expRes.String())
}
}
if effectiveExp == "" && !opts.AICodeFiltered && !opts.ExperienceOverridden {
effectiveExp = trimmedExp
}
var hasGoogleOneCredit bool
if opts.Staged != nil {
stagedRaw := ""
if opts.Staged.StagedEnabledCredits {
stagedRaw = opts.Staged.StagedEnabledCreditsRaw
}
reqECT := readRequestEnabledCreditTypes(v1InternalDoc, stagedRaw)
ectActive := hasGoogleOneAICreditType(reqECT)
aicodeEC := readAICodeEnabledCredits(existingAICode)
aicodeECActive := hasExistingAICode && hasGoogleOneAICreditType(aicodeEC)
if opts.Staged.StagedEnabledCredits {
// Credits were staged on both request.enabledCreditTypes and
// request.aicode.enabledCredits. Clearing or filtering either path
// disables credits; filtering the whole aicode object alone keeps
// request.enabledCreditTypes active so we reject instead of silently
// dropping paid credits onto the model arm.
hasGoogleOneCredit = ectActive && (!hasExistingAICode || aicodeECActive)
} else {
if hasExistingAICode && aicodeEC.Exists() {
hasGoogleOneCredit = aicodeECActive
} else {
hasGoogleOneCredit = ectActive
}
}
} else {
hasGoogleOneCredit = hasGoogleOneAICreditType(readRequestEnabledCreditTypes(v1InternalDoc, "")) ||
hasGoogleOneAICreditType(v1InternalDoc.Get("enabledCreditTypes")) ||
hasGoogleOneAICreditType(v1InternalDoc.Get("enabled_credit_types"))
if hasExistingAICode && !hasGoogleOneCredit {
hasGoogleOneCredit = hasGoogleOneAICreditType(readAICodeEnabledCredits(existingAICode))
}
}
if opts.CreditsFiltered {
hasGoogleOneCredit = false
}
// If aicode was only synthesized as a credit fallback for an unmapped model
// and user payload rules disabled credits without adding other aicode fields
// or overriding experience, retract the synthesized fallback so the request
// stays cleanly on the model arm.
if opts.Staged != nil && opts.Staged.StagedCreditFallback && !hasGoogleOneCredit &&
!opts.ExperienceOverridden &&
hasExistingAICode && effectiveExp == opts.Staged.StagedExperience && !aicodeHasNonCreditFields(existingAICode) {
hasExistingAICode = false
effectiveExp = ""
}
if effectiveExp == "" {
hasNonCreditFields := hasExistingAICode && aicodeHasNonCreditFields(existingAICode)
if hasNonCreditFields {
return nil, nil, fmt.Errorf("aicode request requires a non-empty experience")
}
if hasGoogleOneCredit {
aicodeExplicitlyFiltered := opts.AICodeFiltered || (opts.Staged != nil && opts.Staged.StagedAICode && !hasExistingAICode)
expExplicitlyStripped := opts.ExperienceOverridden || (opts.Staged != nil && opts.Staged.StagedExperience != "")
if opts.DisableCreditFallback || aicodeExplicitlyFiltered || expExplicitlyStripped {
return nil, nil, fmt.Errorf("aicode request requires a non-empty experience")
}
if trimmedDefaultExp != "" {
effectiveExp = trimmedDefaultExp
} else {
effectiveExp = AntigravityAICodeFallbackCreditExperience
}
} else if !opts.CreditsFiltered && hasExistingAICode && aicodeHasExplicitNonEmptyCredits(existingAICode) {
// Only ignore staged enabledCredits that were disabled via enabledCreditTypes
// when no other user-supplied enabledCredits remain.
if opts.Staged == nil || !opts.Staged.StagedEnabledCredits {
return nil, nil, fmt.Errorf("aicode request requires a non-empty experience")
}
}
}
// Enforce oneof inference mutual exclusivity: emit "aicode" ONLY when
// experience is non-empty; otherwise emit top-level "model".
if effectiveExp != "" {
aicodeDoc := ojson.NewDocString("{}")
if hasExistingAICode {
aicodeDoc = ojson.NewDoc([]byte(existingAICode.Raw))
}
_ = aicodeDoc.Set("experience", effectiveExp)
_ = aicodeDoc.Delete("enabled_credits")
if hasGoogleOneCredit {
_ = aicodeDoc.SetRawBytes("enabledCredits", []byte(`["GOOGLE_ONE_AI"]`))
} else {
_ = aicodeDoc.Delete("enabledCredits")
}
_ = out.SetRawBytes("aicode", aicodeDoc.Bytes())
} else if modelRes := v1InternalDoc.Get("model"); modelRes.Type == ojson.String {
if trimmedModel := strings.TrimSpace(modelRes.String()); trimmedModel != "" {
_ = out.Set("model", trimmedModel)
}
}
// Hoist ONLY canonical request.* fields without falling back to top-level or
// snake_case aliases so fields deleted by FinalizePayloadDoc can never be
// resurrected.
for _, field := range aicodeCanonicalRequestHoistFields {
if field == "sessionId" && opts.BusinessMode {
continue
}
val := v1InternalDoc.Get("request." + field)
if val.Exists() && val.Type != ojson.Null && val.Raw != "" {
_ = out.SetRawBytes(field, []byte(val.Raw))
}
}
// Read-only post-finalization validation: never silently re-merge snake_case
// thinking_config or delete user-configured thinkingBudget/thinkingLevel
// values after FinalizePayloadDoc.
if errValidate := validateAICodeThinkingConfigDoc(out); errValidate != nil {
return nil, nil, errValidate
}
if errEnums := applyAICodeRequestEnumsDoc(out, "", false); errEnums != nil {
return nil, nil, errEnums
}
if errCredits := ValidateAntigravityFinalCreditTypesDoc(out); errCredits != nil {
return nil, nil, errCredits
}
// Attach entitlement.userTier without overwriting a user-configured tier.
existingEnt := v1InternalDoc.Get("request.entitlement")
if opts.Staged == nil && !existingEnt.IsObject() {
existingEnt = v1InternalDoc.Get("entitlement")
}
if existingEnt.Exists() && existingEnt.IsObject() {
_ = out.SetRawBytes("entitlement", []byte(existingEnt.Raw))
}
if opts.Staged == nil && trimmedTier != "" {
if existingTier := out.Get("entitlement.userTier"); !existingTier.Exists() || strings.TrimSpace(existingTier.String()) == "" {
_ = out.Set("entitlement.userTier", trimmedTier)
}
}
// Business AICode moves prompt_id/request_id/trajectory_id into X-Aicode-* headers,
// lowercases all remaining label values, and emits top-level parent ("projects/<id>").
if opts.BusinessMode {
parentVal := ""
if reqParent := v1InternalDoc.Get("request.parent"); reqParent.Type == ojson.String && strings.TrimSpace(reqParent.String()) != "" {
parentVal = FormatAntigravityBusinessParent(reqParent.String())
} else if opts.Staged == nil {
if topParent := v1InternalDoc.Get("parent"); topParent.Type == ojson.String && strings.TrimSpace(topParent.String()) != "" {
parentVal = FormatAntigravityBusinessParent(topParent.String())
} else {
parentVal = FormatAntigravityBusinessParent(opts.Parent)
}
}
if parentVal != "" {
_ = out.Set("parent", parentVal)
}
fallbackReqID := aicodeCorrelationID(v1InternalDoc.Get("requestId"))
if fallbackReqID == "" {
fallbackReqID = aicodeCorrelationID(v1InternalDoc.Get("request.requestId"))
}
applyBusinessAICodeLabelsDoc(out, fallbackReqID, extraHeaders)
}
// Belt-and-suspenders guard against protojson oneof inference collision.
if out.Get("aicode").Exists() && out.Get("model").Exists() {
_ = out.Delete("model")
}
return out, extraHeaders, nil
}
var aicodeRequestEnums = []struct {
paths []string
names []string
}{
{
[]string{"toolConfig.functionCallingConfig.mode", "toolConfig.function_calling_config.mode"},
[]string{"MODE_UNSPECIFIED", "AUTO", "ANY", "NONE"},
},
{
[]string{
"generationConfig.thinkingConfig.thinkingLevel", "generationConfig.thinkingConfig.thinking_level",
"generationConfig.thinking_config.thinkingLevel", "generationConfig.thinking_config.thinking_level",
},
[]string{"THINKING_LEVEL_UNSPECIFIED", "LOW", "MEDIUM", "HIGH", "MINIMAL"},
},
}
// NormalizeAntigravityAICodeRequestEnumsDoc converts supported enum inputs to
// ProtoJSON names before user payload rules. Unsupported values are rejected
// instead of being silently replaced with another mode or level.
func NormalizeAntigravityAICodeRequestEnumsDoc(doc *ojson.Doc) error {
return applyAICodeRequestEnumsDoc(doc, "request.", true)
}
func applyAICodeRequestEnumsDoc(doc *ojson.Doc, prefix string, normalize bool) error {
if doc == nil {
return nil
}
for _, enum := range aicodeRequestEnums {
for _, path := range enum.paths {
value := doc.Get(prefix + path)
if !value.Exists() || value.Type == ojson.Null {
continue
}
name := ""
if code, ok := aicodeNumberedEnum(value); ok && code >= 0 && code < int64(len(enum.names)) {
name = enum.names[code]
} else if value.Type == ojson.String {
for _, candidate := range enum.names {
if strings.EqualFold(strings.TrimSpace(value.Str), candidate) {
name = candidate
break
}
}
}
if name == "" {
return fmt.Errorf("unsupported aicode enum at %s", path)
}
if normalize && value.String() != name {
_ = doc.Set(prefix+path, name)
}
}
}
return nil
}
func aicodeNumberedEnum(value ojson.Result) (int64, bool) {
switch value.Type {
case ojson.Number:
return antigravity.ParseExactJSONInt64(value)
case ojson.String:
trimmed := strings.TrimSpace(value.Str)
if isPureASCIIInteger(trimmed) {
code, errParse := strconv.ParseInt(trimmed, 10, 64)
return code, errParse == nil
}
}
return 0, false
}
func hasAICodeThinkingBudget(res ojson.Result) bool {
return res.Exists() && res.Type != ojson.Null && res.Raw != ""
}
func validateAICodeThinkingConfigDoc(out *ojson.Doc) error {
if out == nil {
return nil
}
tc := out.Get("generationConfig.thinkingConfig")
if !tc.Exists() || !tc.IsObject() {
return nil
}
hasActiveLevel := isActiveAICodeThinkingLevel(tc.Get("thinkingLevel")) || isActiveAICodeThinkingLevel(tc.Get("thinking_level"))
hasBudget := hasAICodeThinkingBudget(tc.Get("thinkingBudget")) || hasAICodeThinkingBudget(tc.Get("thinking_budget"))
if hasActiveLevel && hasBudget {
return fmt.Errorf("aicode thinkingConfig conflict: thinkingLevel and thinkingBudget cannot both be set")
}
return nil
}
func aicodeCorrelationID(value ojson.Result) string {
if value.Type != ojson.String || !httpguts.ValidHeaderFieldValue(value.Str) {
return ""
}
return strings.TrimSpace(value.Str)
}
func applyBusinessAICodeLabelsDoc(out *ojson.Doc, fallbackRequestID string, extraHeaders http.Header) {
if out == nil {
return
}
if labelsRes := out.Get("labels"); labelsRes.Exists() && labelsRes.IsObject() {
newLabels := ojson.NewDocString("{}")
kept := 0
labelsRes.ForEach(func(k, v ojson.Result) bool {
key := k.String()
switch key {
case "prompt_id":
if extraHeaders != nil {
if val := strings.TrimSpace(v.String()); val != "" && !strings.ContainsAny(val, "\r\n") {
extraHeaders.Set("X-Aicode-Prompt-Id", val)
}
}
return true
case "request_id":
if extraHeaders != nil {
if val := aicodeCorrelationID(v); val != "" {
extraHeaders.Set("X-Aicode-Request-Id", val)
}
}
return true
case "trajectory_id":
if extraHeaders != nil {
if val := strings.TrimSpace(v.String()); val != "" && !strings.ContainsAny(val, "\r\n") {
extraHeaders.Set("X-Aicode-Trajectory-Id", val)
}
}
return true
default:
escaped := escapeAICodeOJSONKey(key)
if v.Type == ojson.String {
_ = newLabels.Set(escaped, strings.ToLower(v.String()))
} else if v.Raw != "" {
_ = newLabels.SetRawBytes(escaped, []byte(v.Raw))
}
kept++
return true
}
})
if kept > 0 {
_ = out.SetRawBytes("labels", newLabels.Bytes())
} else {
_ = out.Delete("labels")
}
}
if extraHeaders != nil && extraHeaders.Get("X-Aicode-Request-Id") == "" {
if reqID := strings.TrimSpace(fallbackRequestID); reqID != "" && httpguts.ValidHeaderFieldValue(fallbackRequestID) {
extraHeaders.Set("X-Aicode-Request-Id", reqID)
}
}
}
// NormalizeAntigravityAICodeSafetySettingsDoc validates and normalizes
// request.safetySettings enum values into canonical ProtoJSON names BEFORE
// FinalizePayloadDoc so Vertex vs AICode HarmCategory enum number collisions
// (e.g. Vertex 2 vs AICode 10 for HARM_CATEGORY_DANGEROUS_CONTENT) cannot
// corrupt safety filters and user Payload.Override rules applied later remain
// the final semantic barrier.
//
// Vertex HarmCategory values that have no equivalent in the AICode proto schema
// (5..10: CIVIC_INTEGRITY, IMAGE_HATE, IMAGE_DANGEROUS_CONTENT, IMAGE_HARASSMENT,
// IMAGE_SEXUALLY_EXPLICIT, JAILBREAK) or unknown categories return an explicit
// error instead of silently remapping.
func NormalizeAntigravityAICodeSafetySettingsDoc(doc *ojson.Doc) error {
if doc == nil {
return nil
}
settings := doc.Get("request.safetySettings")
if !settings.Exists() || settings.Type == ojson.Null || !settings.IsArray() {
return nil
}
for idx, item := range settings.Array() {
if !item.IsObject() {
continue
}
prefix := fmt.Sprintf("request.safetySettings.%d.", idx)
if cat := item.Get("category"); cat.Exists() && cat.Type != ojson.Null {
canonical, errCat := normalizeAICodeSafetyCategory(cat)
if errCat != nil {
return fmt.Errorf("aicode safetySettings[%d].category: %w", idx, errCat)
}
_ = doc.Set(prefix+"category", canonical)
}
if thr := item.Get("threshold"); thr.Exists() && thr.Type != ojson.Null {
canonical, changed, errThr := normalizeAICodeSafetyThreshold(thr)
if errThr != nil {
return fmt.Errorf("aicode safetySettings[%d].threshold: %w", idx, errThr)
}
if changed {
_ = doc.Set(prefix+"threshold", canonical)
}
}
if mtd := item.Get("method"); mtd.Exists() && mtd.Type != ojson.Null {
canonical, changed, errMtd := normalizeAICodeSafetyMethod(mtd)
if errMtd != nil {
return fmt.Errorf("aicode safetySettings[%d].method: %w", idx, errMtd)
}
if changed {
_ = doc.Set(prefix+"method", canonical)
}
}
}
return nil
}
func isPureASCIIInteger(s string) bool {
if s == "" {
return false
}
start := 0
if s[0] == '-' || s[0] == '+' {
if len(s) == 1 {
return false
}
start = 1
}
for i := start; i < len(s); i++ {
if s[i] < '0' || s[i] > '9' {
return false
}
}
return true
}
// VertexHarmCategoryEnumName maps a numeric Vertex aiplatform_master_content.proto
// HarmCategory enum value (0..10) to its exact ProtoJSON name.
func VertexHarmCategoryEnumName(code int64) (string, bool) {
switch code {
case 0:
return "HARM_CATEGORY_UNSPECIFIED", true
case 1:
return "HARM_CATEGORY_HATE_SPEECH", true
case 2:
return "HARM_CATEGORY_DANGEROUS_CONTENT", true
case 3:
return "HARM_CATEGORY_HARASSMENT", true
case 4:
return "HARM_CATEGORY_SEXUALLY_EXPLICIT", true
case 5:
return "HARM_CATEGORY_CIVIC_INTEGRITY", true
case 6:
return "HARM_CATEGORY_IMAGE_HATE", true
case 7:
return "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", true
case 8:
return "HARM_CATEGORY_IMAGE_HARASSMENT", true
case 9:
return "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT", true
case 10:
return "HARM_CATEGORY_JAILBREAK", true
default:
return "", false
}
}
func isAICodeRepresentableHarmCategory(name string) bool {
switch name {
case "HARM_CATEGORY_UNSPECIFIED",
"HARM_CATEGORY_HARASSMENT",
"HARM_CATEGORY_HATE_SPEECH",
"HARM_CATEGORY_SEXUALLY_EXPLICIT",
"HARM_CATEGORY_DANGEROUS_CONTENT":
return true
default:
return false
}
}
func normalizeAICodeSafetyCategory(cat ojson.Result) (string, error) {
switch cat.Type {
case ojson.Number:
v, ok := antigravity.ParseExactJSONInt64(cat)
if !ok {
return "", fmt.Errorf("invalid numeric HarmCategory %q", strings.TrimSpace(cat.Raw))
}
vertexName, okVertex := VertexHarmCategoryEnumName(v)
if !okVertex {
return "", fmt.Errorf("unknown Vertex HarmCategory enum value %d", v)
}
if !isAICodeRepresentableHarmCategory(vertexName) {
return "", fmt.Errorf("Vertex HarmCategory %s (%d) is not representable in aicode schema", vertexName, v)
}
return vertexName, nil
case ojson.String:
trimmed := strings.TrimSpace(cat.Str)
if trimmed == "" {
return "", fmt.Errorf("empty HarmCategory")
}
if isPureASCIIInteger(trimmed) {
v, errParse := strconv.ParseInt(trimmed, 10, 64)
if errParse != nil {
return "", fmt.Errorf("invalid numeric HarmCategory %q", trimmed)
}
vertexName, okVertex := VertexHarmCategoryEnumName(v)
if !okVertex {
return "", fmt.Errorf("unknown Vertex HarmCategory enum value %d", v)
}
if !isAICodeRepresentableHarmCategory(vertexName) {
return "", fmt.Errorf("Vertex HarmCategory %s (%d) is not representable in aicode schema", vertexName, v)
}
return vertexName, nil
}
upper := strings.ToUpper(trimmed)
if !isAICodeRepresentableHarmCategory(upper) {
return "", fmt.Errorf("HarmCategory %q is not representable in aicode schema", trimmed)
}
return upper, nil
default:
return "", fmt.Errorf("unsupported HarmCategory JSON value %q", strings.TrimSpace(cat.Raw))
}
}
func normalizeAICodeSafetyThreshold(thr ojson.Result) (string, bool, error) {
switch thr.Type {
case ojson.Number:
v, ok := antigravity.ParseExactJSONInt64(thr)
if !ok {
return "", false, fmt.Errorf("invalid numeric HarmBlockThreshold %q", strings.TrimSpace(thr.Raw))
}
name, okEnum := vertexHarmBlockThresholdEnumName(v)
if !okEnum {
return "", false, fmt.Errorf("unknown HarmBlockThreshold enum value %d", v)
}
return name, true, nil
case ojson.String:
trimmed := strings.TrimSpace(thr.Str)
if isPureASCIIInteger(trimmed) {
v, errParse := strconv.ParseInt(trimmed, 10, 64)
if errParse != nil {
return "", false, fmt.Errorf("invalid numeric HarmBlockThreshold %q", trimmed)
}
name, okEnum := vertexHarmBlockThresholdEnumName(v)
if !okEnum {
return "", false, fmt.Errorf("unknown HarmBlockThreshold enum value %d", v)
}
return name, true, nil
}
return trimmed, false, nil
default:
return "", false, fmt.Errorf("unsupported HarmBlockThreshold JSON value %q", strings.TrimSpace(thr.Raw))
}
}
func normalizeAICodeSafetyMethod(mtd ojson.Result) (string, bool, error) {
switch mtd.Type {
case ojson.Number:
v, ok := antigravity.ParseExactJSONInt64(mtd)
if !ok {
return "", false, fmt.Errorf("invalid numeric HarmBlockMethod %q", strings.TrimSpace(mtd.Raw))
}
name, okEnum := vertexHarmBlockMethodEnumName(v)
if !okEnum {
return "", false, fmt.Errorf("unknown HarmBlockMethod enum value %d", v)
}
return name, true, nil
case ojson.String:
trimmed := strings.TrimSpace(mtd.Str)
if isPureASCIIInteger(trimmed) {
v, errParse := strconv.ParseInt(trimmed, 10, 64)
if errParse != nil {
return "", false, fmt.Errorf("invalid numeric HarmBlockMethod %q", trimmed)
}
name, okEnum := vertexHarmBlockMethodEnumName(v)
if !okEnum {
return "", false, fmt.Errorf("unknown HarmBlockMethod enum value %d", v)
}
return name, true, nil
}
return trimmed, false, nil
default:
return "", false, fmt.Errorf("unsupported HarmBlockMethod JSON value %q", strings.TrimSpace(mtd.Raw))
}
}
func vertexHarmBlockThresholdEnumName(code int64) (string, bool) {
switch code {
case 0:
return "HARM_BLOCK_THRESHOLD_UNSPECIFIED", true
case 1:
return "BLOCK_LOW_AND_ABOVE", true
case 2:
return "BLOCK_MEDIUM_AND_ABOVE", true
case 3:
return "BLOCK_ONLY_HIGH", true
case 4:
return "BLOCK_NONE", true
case 5:
return "OFF", true
default:
return "", false
}
}
func vertexHarmBlockMethodEnumName(code int64) (string, bool) {
switch code {
case 0:
return "HARM_BLOCK_METHOD_UNSPECIFIED", true
case 1:
return "SEVERITY", true
case 2:
return "PROBABILITY", true
default:
return "", false
}
}
// MapAICodeFinishReasonToVertex maps a numeric google.internal.cloud.aicode.v1main
// Candidate.FinishReason enum value to the corresponding Vertex AI
// aiplatform_master_content.proto FinishReason number, applying the Hub 2.36.0
// +1 shift for values 10..15 (skipping Vertex 10 = MODEL_ARMOR).
func MapAICodeFinishReasonToVertex(code int64) int64 {
if code >= 0 && code <= 9 {
return code
}
if code >= 10 && code <= 15 {
return code + 1
}
return 0
}
// NormalizeAICodeFinishReason converts a numeric aicode Candidate.FinishReason
// enum value into its canonical ProtoJSON FinishReason name.
func NormalizeAICodeFinishReason(code int64) string {
switch code {
case 1:
return "STOP"
case 2:
return "MAX_TOKENS"
case 3:
return "SAFETY"
case 4:
return "RECITATION"
case 5:
return "OTHER"
case 6:
return "BLOCKLIST"
case 7:
return "PROHIBITED_CONTENT"
case 8:
return "SPII"
case 9:
return "MALFORMED_FUNCTION_CALL"
case 10:
return "IMAGE_SAFETY"
case 11:
return "IMAGE_PROHIBITED_CONTENT"
case 12:
return "IMAGE_RECITATION"
case 13:
return "IMAGE_OTHER"
case 14:
return "UNEXPECTED_TOOL_CALL"
case 15:
return "NO_IMAGE"
default:
return "FINISH_REASON_UNSPECIFIED"
}
}
func normalizeAICodeCandidateFinishReasonsDoc(respDoc *ojson.Doc) {
if respDoc == nil {
return
}
candidates := respDoc.Get("candidates")
if !candidates.Exists() || !candidates.IsArray() {
return
}
for idx, cand := range candidates.Array() {
if !cand.IsObject() {
continue
}
prefix := fmt.Sprintf("candidates.%d.", idx)
canonicalizeAICodeFieldAliasesDoc(respDoc, prefix+"finishReason", prefix+"finish_reason")
normalizeAICodeSafetyRatingsDoc(respDoc, prefix)
fr := respDoc.Get(prefix + "finishReason")
switch fr.Type {
case ojson.Number:
name := "FINISH_REASON_UNSPECIFIED"
if code, ok := antigravity.ParseExactJSONInt64(fr); ok {
name = NormalizeAICodeFinishReason(code)
}
_ = respDoc.Set(prefix+"finishReason", name)
case ojson.String:
trimmed := strings.TrimSpace(fr.Str)
if isPureASCIIInteger(trimmed) {
name := "FINISH_REASON_UNSPECIFIED"
if code, errParse := strconv.ParseInt(trimmed, 10, 64); errParse == nil {
name = NormalizeAICodeFinishReason(code)
}
_ = respDoc.Set(prefix+"finishReason", name)
}
}
}
}
// MapAICodeBlockReasonToVertex maps a numeric aicode/businessaicode
// PromptFeedback.BlockReason enum value to the corresponding Vertex AI
// aiplatform_master BlockedReason number, applying the Hub 2.36.0 5 -> 6 shift
// for IMAGE_SAFETY (skipping Vertex 5 = MODEL_ARMOR).
func MapAICodeBlockReasonToVertex(code int64) int64 {
if code >= 0 && code <= 4 {
return code
}
if code == 5 {
return 6
}
return 0
}
// NormalizeAICodeBlockReason converts a numeric aicode/businessaicode
// PromptFeedback.BlockReason enum value into its canonical ProtoJSON name.
func NormalizeAICodeBlockReason(code int64) string {
switch code {
case 1:
return "SAFETY"
case 2:
return "OTHER"
case 3:
return "BLOCKLIST"
case 4:
return "PROHIBITED_CONTENT"
case 5:
return "IMAGE_SAFETY"
default:
return "BLOCKED_REASON_UNSPECIFIED"
}
}
func normalizeAICodePromptFeedbackBlockReasonDoc(respDoc *ojson.Doc) {
if respDoc == nil {
return
}
pf := respDoc.Get("promptFeedback")
if !pf.Exists() || !pf.IsObject() {
return
}
canonicalizeAICodeFieldAliasesDoc(respDoc, "promptFeedback.blockReason", "promptFeedback.block_reason")
normalizeAICodeSafetyRatingsDoc(respDoc, "promptFeedback.")
br := respDoc.Get("promptFeedback.blockReason")
switch br.Type {
case ojson.Number:
name := "BLOCKED_REASON_UNSPECIFIED"
if code, ok := antigravity.ParseExactJSONInt64(br); ok {
name = NormalizeAICodeBlockReason(code)
}
_ = respDoc.Set("promptFeedback.blockReason", name)
case ojson.String:
trimmed := strings.TrimSpace(br.Str)
if isPureASCIIInteger(trimmed) {
name := "BLOCKED_REASON_UNSPECIFIED"
if code, errParse := strconv.ParseInt(trimmed, 10, 64); errParse == nil {
name = NormalizeAICodeBlockReason(code)
}
_ = respDoc.Set("promptFeedback.blockReason", name)
}
}
}
func normalizeAICodeSafetyRatingsDoc(doc *ojson.Doc, prefix string) {
path := prefix + "safetyRatings"
canonicalizeAICodeFieldAliasesDoc(doc, path, prefix+"safety_ratings")
values := doc.Get(path)
if !values.IsArray() {
return
}
for idx, rating := range values.Array() {
code, ok := aicodeNumberedEnum(rating.Get("category"))
if !ok {
continue
}
// AICode 7..10 overlap unrelated Vertex numbers. Translate only
// recognized categories and preserve unknown values without guessing.
var vertexCode int64
switch code {
case 0:
vertexCode = 0
case 7:
vertexCode = 3
case 8:
vertexCode = 1
case 9:
vertexCode = 4
case 10:
vertexCode = 2
default:
continue
}
if name, found := VertexHarmCategoryEnumName(vertexCode); found {
_ = doc.Set(fmt.Sprintf("%s.%d.category", path, idx), name)
}
}
}
var aicodeFlatResponseFields = [][2]string{
{"candidates", "candidates"},
{"promptFeedback", "prompt_feedback"},
{"usageMetadata", "usage_metadata"},
{"modelVersion", "model_version"},
{"responseId", "response_id"},
}
// FromAICodeGenerateContentPayload converts a flat v1alpha GenerateContentResponse
// JSON object into the nested v1internal shape expected by downstream CLIProxyAPI
// usage, signature, continuation, and protocol-translation pipelines.
// Error payloads and already-nested responses are returned untouched.
func FromAICodeGenerateContentPayload(flat []byte) []byte {
trimmed := bytes.TrimSpace(flat)
if len(trimmed) == 0 || trimmed[0] != '{' || !ojson.ValidBytes(trimmed) {
return flat
}
root := ojson.ParseBytes(trimmed)
if !root.IsObject() {
return flat
}
if errRes := root.Get("error"); errRes.Exists() && errRes.Type != ojson.Null {
return flat
}
if respRes := root.Get("response"); respRes.Exists() && respRes.IsObject() {
return flat
}
hasFlatField := false
for _, field := range aicodeFlatResponseFields {
if antigravityFieldAlias(root, field[0], field[1]).Exists() {
hasFlatField = true
break
}
}
creditMeta := root.Get("creditUsageMetadata")
if !hasFlatField && (!creditMeta.Exists() || !creditMeta.IsObject()) {
return flat
}
respDoc := ojson.NewDocString("{}")
for _, field := range aicodeFlatResponseFields {
if val := antigravityFieldAlias(root, field[0], field[1]); val.Exists() && val.Raw != "" {
_ = respDoc.SetRaw(field[0], val.Raw)
}
}
normalizeAICodeCandidateFinishReasonsDoc(respDoc)
normalizeAICodePromptFeedbackBlockReasonDoc(respDoc)
outDoc := ojson.NewDocString("{}")
_ = outDoc.SetRawBytes("response", respDoc.Bytes())
if creditMeta.Exists() && creditMeta.IsObject() {
if consumed := creditMeta.Get("consumedCredits"); consumed.Exists() && consumed.Type != ojson.Null && consumed.Raw != "" {
_ = outDoc.SetRawBytes("consumedCredits", []byte(consumed.Raw))
}
if remaining := creditMeta.Get("remainingCredits"); remaining.Exists() && remaining.Type != ojson.Null && remaining.Raw != "" {
_ = outDoc.SetRawBytes("remainingCredits", []byte(remaining.Raw))
}
}
for _, passthrough := range []string{"traceId", "metadata"} {
if val := root.Get(passthrough); val.Exists() && val.Type != ojson.Null && val.Raw != "" {
_ = outDoc.SetRawBytes(passthrough, []byte(val.Raw))
}
}
return outDoc.Bytes()
}