Skip to content

[Feature]: Complete AI Studio wire-protocol specs & reference encoders (v0.3.17): Veo/VideoConfig, Audio/Voices/Music, Live parity, Genie 4, ErrorDetails, Lens/Transparent PNG, Build Proxy #369

Backlog

Description

@giryaby-by

想要什么,用来做什么 / What you want and what for

想要什么,用来做什么 / What you want and what for

A complete, implementation-ready protocol reference (exact protobuf/JSPB indices, WAA proof bindings, response layouts, and drop-in Go reference encoders/decoders) for verified AI Studio capabilities and error schemas in m_b.js / YUh4Se.js / XVDWwe.js not yet wired in v0.3.17 (5deae85), excluding items already tracked in #362, #363, and #368.


1. Native Veo (GenerateVideo / GetGenerateVideoOperation) & GenerateContent VideoConfig

Currently internal/aistudio/video.go:104 only handles Omni generateContent video models (IsVideoModel), rejects LastImage (video_omni.go:86), and leaves wire[27] empty in generate.go.

A. MakerSuiteService/GenerateVideo (_.F9a -> G9a, XVDWwe.js@360620)

  • Endpoint: POST /$rpc/google.internal.alkali.applications.makersuite.v1.MakerSuiteService/GenerateVideo (X-AIStudio-G1-Tier per sEa)
  • wire[0] (field 1): model (string, e.g. "models/veo-3.1-generate-preview")
  • wire[1] (field 2): prompt (string)
  • wire[2] (field 3, _.xGc): [videoCount, aspectRatio, [durationSeconds], outputResolution, lastFrameBlob, lastFrameDriveFile, task] (lastFrameBlob/DriveFile oneof yGc=[5,6])
  • wire[3] (field 4, oneof AGc=[4,5]): startImage inline Blob ([mimeType, base64])
  • wire[4] (field 5, oneof AGc=[4,5]): startImage Drive file _.sv ([driveFileId])
  • wire[5] (field 6): negativePrompt (string)
  • wire[6] (field 7): apiKey (string, optional)
  • wire[7] (field 8): waaProof — WAA binding (_.BGc): prompt || ""
  • wire[8] (field 9): repeated referenceImages (tGc, oneof uGc=[1,2]: [inlineBlob, driveFile])
  • wire[9] (field 10): extendVideo Drive file _.sv ([driveFileId])
  • Response (G9a): resp[0] (field 1) = operationName (string).
// EncodeGenerateVideoRequest encodes MakerSuiteService/GenerateVideo (_.F9a) with WAA placeholder at wire[7].
// WAA proof binding (_.BGc): prompt.
func EncodeGenerateVideoRequest(model, prompt, aspectRatio, resolution, negativePrompt, task string, count, durationSec int, start, last any, refs []any, extend any) ([]byte, int, error) {
	cfg := make([]any, 7)
	cfg[0] = count
	if aspectRatio != "" { cfg[1] = aspectRatio }
	if durationSec > 0 { cfg[2] = []any{int64(durationSec)} }
	if resolution != "" { cfg[3] = resolution }
	if last != nil { cfg[4] = last } // or cfg[5] for Drive file [fileID]
	if task != "" { cfg[6] = task }
	wire := make([]any, 10)
	wire[0], wire[1], wire[2] = "models/"+strings.TrimPrefix(model, "models/"), prompt, trimWireNil(cfg)
	if start != nil { wire[3] = start } // or wire[4] for Drive file [fileID]
	if negativePrompt != "" { wire[5] = negativePrompt }
	if len(refs) > 0 { wire[8] = refs }
	if extend != nil { wire[9] = extend }
	wire = trimWireNilMinLen(wire, 8) // keeps proof slot at index 7
	return marshalWAAArray(wire, 7)
}

B. MakerSuiteService/GetGenerateVideoOperation (_.hbb -> gbb, XVDWwe.js@202013, @798938)

  • Request: [operationName, optionalProjectName, optionalApiKey] (no WAA proof).
  • Response gbb: resp[0] = done (bool/int), resp[1] = repeated _.qxc where item[0][0] = generated MP4 Drive file ID, resp[2] = repeated filter/error strings.

C. GenerateContent VideoConfig (wire[27], _.IYa, m_b.js@1583250)

For models with secondary_capability_code_14 && secondary_capability_code_17, encode in internal/aistudio/generate.go:270-355:

var videoResolutionsGenContent = map[string]int64{"368p": 1, "720p": 2}

func encodeGenerateContentVideoConfig(cfg *VideoConfig) []any {
	if cfg == nil { return nil }
	var wire []any
	if cfg.FPS == "24fps" { wire = setWireField(wire, 4, int64(1)) }
	if cfg.AspectRatio != "" { wire = setWireField(wire, 5, cfg.AspectRatio) }
	if cfg.DurationSeconds > 0 { wire = setWireField(wire, 6, []any{cfg.DurationSeconds}) }
	if code, ok := videoResolutionsGenContent[cfg.Resolution]; ok { wire = setWireField(wire, 7, code) }
	return wire // write to generationConfig wire[27]
}

2. Audio, TTS Default Voices, Native Voices (ListVoices / DeleteVoice) & Lyria RealTime

A. TTS Default Voice Resolution (ListModels field 89 / row[88], _.ZCc)

internal/aistudio/generate.go:577-587 hardcodes "Zephyr" for all speech_route models. AI Studio (YUh4Se.js@181845, 3140570) resolves from ListModels field 89 (row[88], _.ZCc):

  • ZCc[0] (field 1): Live default voice
  • ZCc[1] (field 2): single-speaker TTS default (fallback "Fola" if speech_metadata cap 85, else "Zephyr")
  • ZCc[2] (field 3): 2nd-speaker TTS default (fallback "Rami" if cap 85, else "Puck")
  • ZCc[5] (field 6): voice list override when field 66 (row[65]) is empty

B. Native MakerSuiteService/CreateVoice, ListVoices & DeleteVoice (YUh4Se.js & mCtmAd)

  • CreateVoice (_.Ocb -> Pcb, mCtmAd@2333927-2335510, 2374820, 2383405):
    • Endpoint: POST /$rpc/google.internal.alkali.applications.makersuite.v1.MakerSuiteService/CreateVoice (optional X-AIStudio-User-Api-Key + X-AIStudio-G1-Tier per sEa/tEa).
    • Request (_.Ocb, MJh):
      • wire[0] (field 1): Voice (_.XJ / _.qK):
        • voice[1] (field 2): model (string)
        • voice[3] (field 4): type enum (1 = VOICE_TYPE_REPLICATED, 2 = VOICE_TYPE_PROMPTED)
        • voice[4] (field 5, JJh, for replicated/cloned voice): [sourceAudio([mimeType, base64]), consentAudio([mimeType, base64])]
        • voice[6] (field 7): displayName (string)
        • voice[7] (field 8, _.$Fc, for prompted/designed voice): [promptText]
        • voice[8] (field 9): languageCode (string)
        • voice[17] (field 18, optional remix base): base voice ID (string)
      • wire[1] (field 2): true (bool via _.Iq(c, 2, !0))
      • wire[2] (field 3): waaProof (string)
    • Exact WAA proof binding (LJh): c = (voice.model || "") + voiceTypeEnumName (no space; 2 -> "VOICE_TYPE_PROMPTED", 1 -> "VOICE_TYPE_REPLICATED", else "VOICE_TYPE_UNSPECIFIED"). If voice[4] (replicated) is present, append (sourceAudio.mimeType || "") + (sourceAudio.base64 || "") and (consentAudio.mimeType || "") + (consentAudio.base64 || ""); else if voice[7] (prompted) is present, append promptText || "".
    • Response (Pcb): resp[0] (field 1) = created Voice (_.XJ / _.qK, with id at [0] and key at [2]), optional resp[1] (field 2) = sample audio Blob ([mimeType, base64]).
    // EncodeCreateVoiceRequest encodes MakerSuiteService/CreateVoice (_.Ocb) for Voice Design (prompted) or Cloning (replicated).
    func EncodeCreateVoiceRequest(model, displayName, languageCode, promptText, remixBaseID string, source, consent *Blob) ([]byte, int, string, error) {
        voice := make([]any, 18)
        voice[1] = "models/" + strings.TrimPrefix(model, "models/")
        typeName := "VOICE_TYPE_UNSPECIFIED"
        binding := voice[1].(string)
        if source != nil && consent != nil {
            voice[3], typeName = int64(1), "VOICE_TYPE_REPLICATED"
            voice[4] = []any{
                []any{source.MIME, base64.StdEncoding.EncodeToString(source.Data)},
                []any{consent.MIME, base64.StdEncoding.EncodeToString(consent.Data)},
            }
            binding += typeName + source.MIME + base64.StdEncoding.EncodeToString(source.Data) +
                consent.MIME + base64.StdEncoding.EncodeToString(consent.Data)
        } else {
            voice[3], typeName = int64(2), "VOICE_TYPE_PROMPTED"
            voice[7] = []any{promptText}
            binding += typeName + promptText
        }
        if displayName != "" { voice[6] = displayName }
        if languageCode != "" { voice[8] = languageCode }
        if remixBaseID != "" { voice[17] = remixBaseID }
        wire := []any{trimWireNil(voice), true, nil}
        body, proofAt, err := marshalWAAArray(wire, 2)
        return body, proofAt, binding, err
    }
  • ListVoices (_.py -> jhb):
    • Request _.py: [0]=pageSize(50), [1]=pageToken, [2]=projectName, [3]=apiKey, [4]=languageCode[], [5]=regionCode[], [6]=accent[], [7]=persona[], [8]=context[], [9]=gender[], [10]=pitch[], [11]=type[] ("replicated" | "prompted"), [12]=search (optional header X-AIStudio-User-Api-Key).
    • Response jhb: [0] = repeated _.qK, [1] = nextPageToken.
    • Voice _.qK: [0]=id, [1]=model, [2]=key, [3]=typeEnum (1=replicated), [4]=isReplicatedFlag, [6]=displayName, [7]=promptedObj ([0]=promptText), [8]=languageCode, [10]=accent, [11]=persona, [12]=context, [13]=gender, [15]=description.
  • DeleteVoice (_.H7a -> I7a):
    • Request: [name, waaProof, projectName, apiKey], WAA proof binding (Fii): name ("voices/<id>").
  • X-AIStudio-G1-Tier: AI Studio's sEa / tEa set includes CreateVoice, ListVoices, and DeleteVoice.

C. Standard Lyria RealTime WebSocket Route (BidiGenerateMusic)

internal/aistudio/build_bidi.go already supports BidiGenerateMusic on /v1/live, but there is no standard Gemini WebSocket route (/ws/google.ai.generativelanguage.*.GenerativeService.BidiGenerateMusic) yet.


3. Live Audio/Video Transport Bugs & Build Live Parity (live_gemini.go, build_bidi.go)

  1. Multi-channel audio/pcm Resampling Bug (internal/api/live_gemini.go:530-532):
    geminiLiveMedia ignores ;channels=N and hardcodes 1 channel, corrupting stereo PCM playback/pitch:
    channels := 1
    if value := parameters["channels"]; value != "" {
        if parsed, convErr := strconv.Atoi(value); convErr == nil && parsed > 0 { channels = parsed }
    }
    if rate != geminiLiveAudioRate || channels != 1 {
        data = resample.PCM(data, channels, rate, geminiLiveAudioRate)
    }
  2. Multimodal clientContent.turns (internal/api/live_gemini.go:336-348):
    geminiLiveTexts rejects non-text (inlineData) parts in clientContent.turns. AI Studio (_.GMc / EMc in YUh4Se.js) supports multimodal Content turns with WAA binding parts.map(_.$n).join(" ").
  3. realtimeInput.mediaChunks WAA Binding (YUh4Se.js EMc):
    Unlike audio (field 2) and video (field 4) which use "", mediaChunks (_.fL field 1) binds mediaChunks.flatMap(b => b.getData().If()).join(" ") if forwarded directly.
  4. WebSocket Frame Opcode (internal/api/live_gemini.go:600):
    JSON server events use websocket.BinaryMessage (0x82), causing browser/JS clients expecting text to receive Blob/Buffer (consider websocket.TextMessage 0x81).
  5. Build Live (internal/aistudio/build_bidi.go:70-110, 173):
    EncodeBuildBidiSetup hardcodes bidiVariantConversation and "Zephyr" (missing DefaultVoice, ProactiveAudio/ProactiveVideo, AffectiveDialog, TurnCoverage, Translation, Transcription, custom voice_/voicekey_), and liveFrame rejects client_content / context_update even though proxy:proxyBidiStreamedCall forwards Gemini Live JSON directly.
  6. Live Upstream message[8] (field 9):
    In live v0.3.17 sessions, upstream WebChannel emits [null,null,null,null,null,null,null,null,["1"]] / ["2"] every turn, currently falling through into raw provider on /v1/live.

4. Interactive Video / Genie 4 Wire Spec (YUh4Se.js)

  • WebRTC (MakerSuiteService/StartInteractiveVideoWebRtcSession, _.akb -> bkb, _.ckb):
    • Request: [model, offerSdp, waaProof] — WAA binding (api): ${model} ${offerSdp}.
    • Response bkb: [interactionId, answerSdp]. Transceivers: video + audio recvonly, ordered DataChannel "events" (JSON).
  • WebChannel (POST https://webchannel-alkalimakersuite-pa.clients6.google.com/v1/interactiveVideoBidiStream, useFetchStreams: true):
    • Client Api (oneof w7=[1,2,3,5]): [0]=setup zpi([model, prompt, refImageBlob]), [1]=text, [2]=keyDown, [3]=waaProof, [4]=keyUp.
    • WAA binding ($oi): setup -> [model, prompt, refImageBase64].filter(Boolean).join(" "); text -> text; keyDown -> String(keyCode); keyUp -> "".
    • Server Epi (oneof Dpi=[1,2,3,4]): [0]=Cpi([interactionId]), [1]=videoFrame Blob, [2]=audioChunk Blob, [3]=Bpi([rpcStatus]).

5. Complete Structured RPC Error Decoding (GeminiApiErrorDetails & AiStudioErrorDetails)

decodeRPCErrorMetadata (internal/aistudio/client.go:373-414) only decodes google.rpc.RetryInfo and google.rpc.ErrorInfo, ignoring both Makersuite payloads (fCb / kCb / _.SDa / _.TDa in m_b.js@283566, 978349, 1136993):

  • GeminiApiErrorDetails (type.googleapis.com/google.internal.alkali.applications.makersuite.v1.GeminiApiErrorDetails, _.Go, oneof _.qp):
    • wire[28] (field 29, QuotaFailure Hyb): violations[0][3] (quotaMetric) + violations[0][4] (quotaId). Daily metrics (Iyb: generate_requests_per_model_per_user, generate_content_tokens_per_model_per_user, predict_requests_per_model_per_user, predict_long_running_generations_per_model_per_user_per_day, scaled_predict_long_running_generations_per_model_per_user_per_day) are RPM only when quotaId includes "PerMinute", otherwise DailyLimitKind.
    • wire[32] (field 33, Timestamp [seconds, nanos], zCa): exact quotaLimitResetTime -> use directly as cooldown Until when RetryInfo is absent.
    • wire[2] (3): input token limit [actual, limit]; wire[3] (4): too many inlined images [actual, limit]; wire[4]/[5]/[13] (5/6/14): file size limit; wire[11] (12): file not found; wire[12] (13): MIME mismatch [file, actualMime, expectedMime]; wire[14] (15): unsupported modalities; wire[23] (24): user location not supported (rotate region); wire[26] (27): file access denied; wire[27] (28): model deprecated; wire[39] (40): project verification required [projectNumber]; wire[40] (41): account verification required (verify-account -> ErrAccountVerification).
  • AiStudioErrorDetails (type.googleapis.com/google.internal.alkali.applications.makersuite.v1.AiStudioErrorDetails, _.sp, oneof _.oA):
    • wire[20] (field 21, _.TDa, bool): authoritative isRetryable flag checked before gRPC status heuristics (m_b.js@1518881).
    • wire[0] (1): Drive storage exceeded; wire[1] (2): Drive access not granted; wire[7] (8): request too large; wire[9]/[10] (10/11): API key / project creation errors.

6. Grounding with Google Lens & Native Transparent / Opaque PNG Background

  1. Google Lens (m_b.js@1582680, YUh4Se.js ZCf):
    • ListModels cap 97 + field 48 toolNames code 10 (internal/aistudio/models.go:497).
    • GoogleSearch.searchTypes field 3 / index 2: lensSearch ([] via A_a) in encodeSearchTool (internal/aistudio/tools.go:152-169).
  2. Transparent / Opaque PNG Background (cap 102, m_b.js iQb & TIa):
    • GenerateContent ImageConfig (wire[26][2], generate.go:467): 1=auto, 2=transparent, 3=opaque.
    • Interactions outputFormat (interaction[53]/[54], _.Eq[2] -> _.QIa[5], interaction.go:327): 1=auto, 2=transparent, 3=opaque.
    • Connects directly to OpenAI background: "transparent" | "opaque" | "auto" in internal/api/media.go:34.

7. Build Proxy Extensions (ProxyUnaryFileApiCall, /cachedContents) & X-AIStudio-G1-Tier Parity

  1. MakerSuiteService/ProxyUnaryFileApiCall (_.Shb -> _.Ohb, m_b.js@1157150):
    • Request _.Shb: [0]=method, [1]=iJ, [2]=request, [3]=waaProof (WAA binding YDa: ${method} ${request}), [4]=httpMethod, [5]=headersMap, [6]=p5d, [7]=fileContentBytes. Enables Build /files uploads directly without Google Drive.
  2. /cachedContents Context Caching: allowlisted in VDa (WAA-bound when path ends with /cachedContents or contains /cachedContents/).
  3. X-AIStudio-G1-Tier (internal/aistudio/benefit.go:25-36): AI Studio's sEa set also includes GetInteraction, GenerateVideo, GetGenerateVideoOperation, CreateVoice, ListVoices, DeleteVoice, StreamRunAgentTask, CancelAgentTask, and SendAgentFollowUpMessage.

8. Missing ListModels Capability Labels (internal/aistudio/models.go)

Verified from Fpi enum in YUh4Se.js@2892500:

  • 39: affective_dialog
  • 40: proactive_audio
  • 72: proactive_video
  • 86: voice_design
  • 87: voice_cloning
  • 93: custom_voices
  • 97: google_lens
  • 102: image_background

版本 / Version

v0.3.17

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions