cpa-exec 0.4.1

Part of cliproxy: upstream provider executors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! Vertex AI (internal/runtime/executor/gemini_vertex_executor.go).
//!
//! Two credential kinds share the Gemini request pipeline:
//! - Imported service-account files (`type: vertex`, `-vertex-import`): every request
//!   first exchanges a signed JWT for an access token (`vertex_auth`), then calls
//!   `https://<location>-aiplatform.googleapis.com` (or the global host) under
//!   `/v1/projects/<project>/locations/<location>/publishers/google/models/<model>`.
//! - API keys (`api-keys.vertex`, or a file credential's `access_token`): `x-goog-api-key`
//!   at `<base-url>/v1/publishers/google/models/<model>`, base URL used as configured.
//!
//! An Interactions client on a credential that opted in (`interactions`) instead reaches
//! the native Interactions API at `/v1beta1/interactions`, built as the Gemini executor
//! builds it (Go 2d5351b3).
//!
//! Unlike the Gemini API-key executor, Vertex translates without the is-compat variants,
//! does not cap `maxOutputTokens`, strips Responses tool-call IDs, sends Imagen models to
//! `:predict`, and hands every scanned stream line to the translator unfiltered.

use cpa_core::gostr::GoStr;
use std::collections::BTreeMap;

use bytes::Bytes;
use cpa_common::json::{self as gj, GoValue};
use cpa_common::thinking::parse_suffix;
use cpa_core::config::Config;
use cpa_core::credential::Credential;
use cpa_core::exec::{ExecError, ExecRequest, ExecResponse, FailureScope, Operation, ResponseBody};
use cpa_core::format::Format;
use serde_json::{Map, Value};

use crate::gemini::{self as g, Emit, LineState, Output};
use crate::gemini_payload as payload;
use crate::payload_barrier::Barrier;
use crate::proxy::{self, GoClients, GoHeaders, Hooks, Proxy};
use crate::{vertex_auth, vertex_openapi};

pub const PROVIDER: &str = "vertex";
const API_VERSION: &str = "v1";
const DEFAULT_API_KEY_BASE: &str = "https://aiplatform.googleapis.com";
const DEFAULT_LOCATION: &str = "us-central1";

pub struct VertexExecutor {
    clients: GoClients,
    /// Unix seconds for the JWT `iat` (tests pin it to Go's recorded clock).
    now: fn() -> i64,
}

fn system_now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs() as i64)
}

impl Default for VertexExecutor {
    fn default() -> Self {
        Self::with_hooks(Hooks::default(), system_now)
    }
}

/// How one request authenticates.
enum Auth {
    /// `x-goog-api-key` at `base` (empty: the global endpoint).
    ApiKey { key: String, base: String },
    ServiceAccount {
        project: String,
        location: String,
        account: Map<String, Value>,
    },
}

/// A Go error without a status code: the handler answers it with 500.
fn plain_error(message: impl Into<String>) -> ExecError {
    ExecError::local(500, FailureScope::Credential, message)
}

/// `vertexAPICreds`: the `api_key` and `base_url` attributes as stored, else the file's
/// `access_token`.
fn api_creds(credential: &Credential) -> (String, String) {
    let attr = |k: &str| credential.attributes.get(k).cloned().unwrap_or_default();
    let mut key = attr("api_key");
    if key.is_empty() {
        key = credential.str("access_token").unwrap_or_default().to_owned();
    }
    (key, attr("base_url"))
}

/// `vertexCreds`: project (`project_id`, then `project`), location (default
/// us-central1) and the normalized service account.
fn service_account(credential: &Credential) -> Result<Auth, ExecError> {
    let text = |k: &str| credential.str(k).map(str::trim).unwrap_or_default().to_owned();
    let mut project = text("project_id");
    if project.is_empty() {
        project = text("project");
    }
    if project.is_empty() {
        return Err(plain_error("vertex executor: missing project_id in credentials"));
    }
    let mut location = text("location");
    if location.is_empty() {
        location = DEFAULT_LOCATION.into();
    }
    let Some(Value::Object(account)) = credential.metadata.get("service_account") else {
        return Err(plain_error("vertex executor: missing service_account in credentials"));
    };
    let account =
        vertex_auth::normalize_service_account(account).map_err(|e| plain_error(format!("vertex executor: {e}")))?;
    Ok(Auth::ServiceAccount {
        project,
        location,
        account,
    })
}

fn auth_for(credential: &Credential) -> Result<Auth, ExecError> {
    let (key, base) = api_creds(credential);
    if key.is_empty() {
        return service_account(credential);
    }
    Ok(Auth::ApiKey { key, base })
}

/// `normalizeVertexOpenAPIRequest`: the `<publisher>/<model>` upstream model; the client
/// payload stays the payload-rule baseline.
fn openapi_request(mut req: ExecRequest) -> ExecRequest {
    let normalized = vertex_openapi::normalize_model(&req.model);
    if normalized.is_empty() || normalized == req.model {
        return req;
    }
    if req.original_body.is_empty() && !req.body.is_empty() {
        req.original_body = req.body.clone();
    }
    req.model = normalized;
    req
}

/// Go 2d5351b3 `shouldExecuteVertexInteractions`: an Interactions client on a credential
/// that opted into the native API (`interactions` attribute true or 1, or a file's
/// `interactions` / `native_interactions`).
fn native_interactions(credential: &Credential, source: Format) -> bool {
    if source != Format::Interactions {
        return false;
    }
    let attr = credential.attributes.get("interactions").map(|v| v.trim());
    // strings.EqualFold with "true": no letter of it has a non-ASCII fold partner but
    // the Kelvin sign, which "true" lacks.
    if attr.is_some_and(|v| v.go_eq_fold("true") || v == "1") {
        return true;
    }
    ["interactions", "native_interactions"]
        .iter()
        .any(|k| credential.metadata.get(*k) == Some(&Value::Bool(true)))
}

/// `vertexInteractionsURL`.
fn interactions_url(base: &str, project: &str, stream: bool) -> String {
    let base = base.trim();
    let base = if base.is_empty() { DEFAULT_API_KEY_BASE } else { base }.trim_end_matches('/');
    let project = project.trim();
    let mut url = if project.is_empty() {
        format!("{base}/v1beta1/interactions")
    } else {
        format!("{base}/v1beta1/projects/{project}/locations/global/interactions")
    };
    if stream {
        url.push_str("?alt=sse");
    }
    url
}

/// `vertexBaseURL`.
fn regional_base(location: &str) -> String {
    match location.trim() {
        "" => format!("https://{DEFAULT_LOCATION}-aiplatform.googleapis.com"),
        "global" => DEFAULT_API_KEY_BASE.into(),
        loc => format!("https://{loc}-aiplatform.googleapis.com"),
    }
}

fn endpoint(auth: &Auth, model: &str, action: &str) -> String {
    match auth {
        // `vertexAPIKeyModelsURL` (Go 2d7f5377): a base holding `/publishers/` is the
        // full models prefix; otherwise `/v1` is added unless the base ends in a
        // version segment such as `/v1beta1`.
        Auth::ApiKey { base, .. } => {
            let base = base.trim().trim_end_matches('/');
            let base = if base.is_empty() { DEFAULT_API_KEY_BASE } else { base };
            if base.contains("/publishers/") {
                return format!("{base}/{model}:{action}");
            }
            let version = if ends_in_version(base) {
                String::new()
            } else {
                format!("/{API_VERSION}")
            };
            format!("{base}{version}/publishers/google/models/{model}:{action}")
        }
        Auth::ServiceAccount { project, location, .. } => format!(
            "{}/{API_VERSION}/projects/{project}/locations/{location}/publishers/google/models/{model}:{action}",
            regional_base(location)
        ),
    }
}

/// `vertexAPIVersionSuffix`: the last path segment is `v`, then lower-case letters,
/// digits, `_` or `-`, with at least one digit.
fn ends_in_version(base: &str) -> bool {
    let seg = &base[base.rfind('/').map_or(0, |i| i + 1)..];
    let Some(rest) = seg.strip_prefix('v') else {
        return false;
    };
    rest.bytes().any(|c| c.is_ascii_digit())
        && rest
            .bytes()
            .all(|c| c.is_ascii_digit() || c.is_ascii_lowercase() || c == b'_' || c == b'-')
}

/// `http.NewRequestWithContext`'s URL parse. Go builds the request before the token
/// exchange, so a URL it rejects fails without contacting the token endpoint. A URL
/// its transport refuses (no host, or a scheme other than http and https) passes here
/// and fails at the send ([`g::send_captured`]).
fn check_url(url: &str) -> Result<(), ExecError> {
    crate::xai_url::new_request(url)?;
    if crate::xai_url::transport_refusal(url).is_some() {
        return Ok(());
    }
    // The shared client's own URL check (`proxy::send`), before the token exchange too.
    url::Url::parse(url).map_err(|_| ExecError::local(500, FailureScope::Request, "invalid upstream URL"))?;
    Ok(())
}

/// gjson's `String()` as Go's `json.Marshal` writes it back: each invalid UTF-8 byte
/// becomes U+FFFD.
fn go_string(value: &gj::Res<'_>) -> String {
    let bytes = value.bytes();
    let mut out = String::with_capacity(bytes.len());
    for chunk in bytes.utf8_chunks() {
        out.push_str(chunk.valid());
        out.extend(std::iter::repeat_n('\u{FFFD}', chunk.invalid().len()));
    }
    out
}

/// `isImagenModel`.
fn is_imagen(model: &str) -> bool {
    model.go_lower().contains("imagen")
}

/// `convertToImagenRequest`: the prompt from `contents.0.parts.0.text`, the first
/// non-empty `messages[].content`, or `prompt`, plus the optional Imagen parameters.
fn imagen_request(body: &[u8]) -> Result<Vec<u8>, ExecError> {
    let mut prompt = String::new();
    let text = gj::get(body, "contents.0.parts.0.text");
    if text.exists() {
        prompt = go_string(&text);
    }
    if prompt.is_empty() {
        let contents = gj::get(body, "messages.#.content");
        if contents.exists()
            && contents.is_array()
            && let Some(first) = contents.array().iter().map(go_string).find(|m| !m.is_empty())
        {
            prompt = first;
        }
    }
    if prompt.is_empty() {
        let direct = gj::get(body, "prompt");
        if direct.exists() {
            prompt = go_string(&direct);
        }
    }
    if prompt.is_empty() {
        return Err(plain_error("imagen: no prompt found in request"));
    }
    let mut instance = BTreeMap::new();
    instance.insert("prompt".to_owned(), GoValue::String(prompt));
    let mut parameters = BTreeMap::new();
    parameters.insert("sampleCount".to_owned(), GoValue::Number("1".into()));
    let aspect = gj::get(body, "aspectRatio");
    if aspect.exists() {
        parameters.insert("aspectRatio".to_owned(), GoValue::String(go_string(&aspect)));
    }
    let count = gj::get(body, "sampleCount");
    if count.exists() {
        parameters.insert("sampleCount".to_owned(), GoValue::Number(count.int().to_string()));
    }
    let negative = gj::get(body, "negativePrompt");
    if negative.exists() {
        instance.insert("negativePrompt".to_owned(), GoValue::String(go_string(&negative)));
    }
    let mut request = BTreeMap::new();
    request.insert("instances".to_owned(), GoValue::Array(vec![GoValue::Object(instance)]));
    request.insert("parameters".to_owned(), GoValue::Object(parameters));
    Ok(GoValue::Object(request).marshal())
}

/// `convertImagenToGeminiResponse`: predictions with image bytes become `inlineData`
/// parts of one Gemini candidate. `responseId` is `imagen-<UnixNano>` like Go's.
fn imagen_response(data: &[u8], model: &str) -> Vec<u8> {
    let predictions = gj::get(data, "predictions");
    if !predictions.exists() || !predictions.is_array() {
        return data.to_vec();
    }
    let string = |s: &str| GoValue::String(s.to_owned());
    let mut parts = Vec::new();
    for prediction in predictions.array() {
        let image = go_string(&prediction.get("bytesBase64Encoded"));
        let mut mime = go_string(&prediction.get("mimeType"));
        if mime.is_empty() {
            mime = "image/png".into();
        }
        if image.is_empty() {
            continue;
        }
        let inline = BTreeMap::from([
            ("mimeType".to_owned(), string(&mime)),
            ("data".to_owned(), string(&image)),
        ]);
        parts.push(GoValue::Object(BTreeMap::from([(
            "inlineData".to_owned(),
            GoValue::Object(inline),
        )])));
    }
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    let zero = || GoValue::Number("0".into());
    let content = BTreeMap::from([
        ("parts".to_owned(), GoValue::Array(parts)),
        ("role".to_owned(), string("model")),
    ]);
    let candidate = BTreeMap::from([
        ("content".to_owned(), GoValue::Object(content)),
        ("finishReason".to_owned(), string("STOP")),
    ]);
    let usage = BTreeMap::from([
        ("promptTokenCount".to_owned(), zero()),
        ("candidatesTokenCount".to_owned(), zero()),
        ("totalTokenCount".to_owned(), zero()),
    ]);
    GoValue::Object(BTreeMap::from([
        (
            "candidates".to_owned(),
            GoValue::Array(vec![GoValue::Object(candidate)]),
        ),
        ("responseId".to_owned(), GoValue::String(format!("imagen-{nanos}"))),
        ("modelVersion".to_owned(), string(model)),
        ("usageMetadata".to_owned(), GoValue::Object(usage)),
    ]))
    .marshal()
}

/// `helps.StripVertexOpenAIResponsesToolCallIDs`: Vertex rejects the Responses call IDs
/// the translator keeps on `functionCall` and `functionResponse` parts.
fn strip_tool_call_ids(body: Vec<u8>, source: Format) -> Vec<u8> {
    if source != Format::OpenAIResponse {
        return body;
    }
    let contents = gj::get(&body, "contents");
    if !contents.is_array() {
        return body;
    }
    let items = contents.array();
    let has_ids = items.iter().any(|c| {
        let parts = c.get("parts");
        parts.is_array()
            && parts
                .array()
                .iter()
                .any(|p| p.get("functionCall.id").exists() || p.get("functionResponse.id").exists())
    });
    if !has_ids {
        return body;
    }
    let mut changed = false;
    let mut out_items: Vec<Vec<u8>> = Vec::with_capacity(items.len());
    for content in &items {
        let parts = content.get("parts");
        if !parts.is_array() {
            out_items.push(content.raw().to_vec());
            continue;
        }
        let mut parts_changed = false;
        let mut part_items = Vec::new();
        for part in parts.array() {
            let mut raw = part.raw().to_vec();
            for path in ["functionCall.id", "functionResponse.id"] {
                if part.get(path).exists()
                    && let Ok(updated) = gj::try_delete(&raw, path)
                {
                    raw = updated;
                    parts_changed = true;
                }
            }
            part_items.push(raw);
        }
        let mut raw = content.raw().to_vec();
        if parts_changed && let Ok(updated) = gj::try_set_raw(&raw, "parts", gj::join(&part_items)) {
            raw = updated;
            changed = true;
        }
        out_items.push(raw);
    }
    if !changed {
        return body;
    }
    gj::try_set_raw(&body, "contents", gj::join(&out_items)).unwrap_or(body)
}

/// Vertex hands every scanned line, prefixes and blank lines included, to the
/// translator; then the tool-input finalization and `[DONE]`.
struct RawLines(Output);

impl LineState for RawLines {
    fn line(&mut self, line: &[u8]) -> Emit {
        // Go's reporter sees each raw line (model and usage, unfiltered).
        self.0.usage.response_line(Format::Gemini, line);
        self.0.observe_finish_signal(line);
        self.0.translate(&g::line_event(line))
    }

    fn end(&mut self) -> Emit {
        self.0.end_with_done()
    }

    fn end_after_error(&mut self) -> Emit {
        self.0.end_after_error()
    }

    fn output(&self) -> Option<&Output> {
        Some(&self.0)
    }

    fn flush(&mut self) -> Vec<Bytes> {
        self.0.flush_frames()
    }
}

impl VertexExecutor {
    /// Tests pass trust and resolve hooks and a fixed clock.
    pub fn with_hooks(hooks: Hooks, now: fn() -> i64) -> Self {
        Self {
            clients: GoClients::new(hooks),
            now,
        }
    }

    fn client(&self, credential: &Credential, cfg: &Config) -> wreq::Client {
        self.clients.get(&Proxy::effective(credential, cfg))
    }

    pub async fn execute(
        &self,
        credential: &Credential,
        req: ExecRequest,
        cfg: &Config,
    ) -> Result<ExecResponse, ExecError> {
        // Go d9451cb6: partner and open models, and credentials that opt in, take the
        // endpoints/openapi route, before the Interactions check.
        let openapi = vertex_openapi::should_execute(credential, &req.model);
        if req.operation == Operation::CountTokens {
            if openapi {
                return crate::openai_compat::count_tokens(credential, &openapi_request(req), cfg);
            }
            return self.count_tokens(credential, &req, cfg).await;
        }
        if req.alt.as_deref() == Some(g::COMPACT_ALT) {
            return Err(g::status_err(501, "/responses/compact not supported"));
        }
        if openapi {
            return self.openapi(credential, openapi_request(req), cfg).await;
        }
        if native_interactions(credential, req.source_format) {
            return self.interactions(credential, &req, cfg).await;
        }
        let auth = auth_for(credential)?;
        self.generate(credential, &req, cfg, &auth).await
    }

    /// Go d9451cb6 `executeOpenAPI` / `executeOpenAPIStream`: the OpenAI-compatible
    /// executor's chat request at the credential's endpoints/openapi base.
    async fn openapi(
        &self,
        credential: &Credential,
        req: ExecRequest,
        cfg: &Config,
    ) -> Result<ExecResponse, ExecError> {
        let client = self.client(credential, cfg);
        let credentials = self.openapi_credentials(&client, credential).await;
        // Go reports a credential failure as the Vertex executor and everything after
        // it through `OpenAICompatExecutor`'s reporter; both name the normalized model.
        let executor = if credentials.is_ok() {
            "OpenAICompatExecutor"
        } else {
            "GeminiVertexExecutor"
        };
        req.usage
            .delegated_executor(executor, &parse_suffix(&req.model).model_name);
        let (base_url, token) = credentials?;
        crate::openai_compat::chat_with(&client, credential, req, cfg, &base_url, &token, None).await
    }

    /// `resolveOpenAPICredentials`: a service account (also when the file carries an
    /// access token beside it) sends a fresh token to its project's route; an API key
    /// only to a third-party relay, since Google's hosts need OAuth.
    async fn openapi_credentials(
        &self,
        client: &wreq::Client,
        credential: &Credential,
    ) -> Result<(String, String), ExecError> {
        let (key, base) = api_creds(credential);
        let has_account = matches!(credential.metadata.get("service_account"), Some(Value::Object(a)) if !a.is_empty());
        if key.is_empty() || has_account {
            let Auth::ServiceAccount {
                project,
                location,
                account,
            } = service_account(credential)?
            else {
                unreachable!("service_account answers a service account")
            };
            let token = vertex_auth::access_token(client, &account, (self.now)())
                .await
                .map_err(|error| {
                    tracing::error!(%error, "vertex executor: access token error");
                    g::status_err(500, "internal server error")
                })?;
            if token.trim().is_empty() {
                return Err(g::status_err(401, "missing access token"));
            }
            let location = vertex_openapi::location(credential, &location);
            let base = vertex_openapi::auth_base_url(credential);
            return Ok((
                vertex_openapi::service_account_base_url(&base, API_VERSION, &project, &location),
                token,
            ));
        }
        if vertex_openapi::is_google_host(&base) {
            return Err(g::status_err(
                400,
                "vertex endpoints/openapi on aiplatform.googleapis.com requires service account credentials",
            ));
        }
        let location = vertex_openapi::location(credential, "");
        let project = vertex_openapi::auth_project_id(credential);
        Ok((
            vertex_openapi::api_key_base_url(&base, API_VERSION, &project, &location),
            key,
        ))
    }

    /// Go 2d5351b3 `executeInteractions` / `executeInteractionsStream`: the Interactions
    /// request as the Gemini executor builds it, at `<base>/v1beta1/interactions`
    /// (under `projects/<project>/locations/global` when a project is known).
    async fn interactions(
        &self,
        credential: &Credential,
        req: &ExecRequest,
        cfg: &Config,
    ) -> Result<ExecResponse, ExecError> {
        let body = g::interactions_body(req, cfg)?;
        let (key, mut base) = api_creds(credential);
        let (project, account) = if key.is_empty() {
            let Auth::ServiceAccount { project, account, .. } = service_account(credential)? else {
                unreachable!("service_account answers a service account")
            };
            if let Some(attr) = credential.attributes.get("base_url").filter(|b| !b.is_empty()) {
                base = attr.trim().to_owned();
            }
            (project, Some(account))
        } else {
            (credential.str("project_id").unwrap_or_default().to_owned(), None)
        };
        // Go builds the request before the token exchange: a URL it rejects fails
        // without a token request.
        let url = interactions_url(&base, &project, req.stream);
        check_url(&url)?;
        let client = self.client(credential, cfg);
        let mut headers = GoHeaders::new();
        headers.set("Content-Type", "application/json");
        match account {
            Some(account) => {
                let token = vertex_auth::access_token(&client, &account, (self.now)())
                    .await
                    .map_err(|error| {
                        tracing::error!(%error, "vertex executor: interactions access token error");
                        g::status_err(500, "internal server error")
                    })?;
                if token.trim().is_empty() {
                    return Err(g::status_err(401, "missing access token"));
                }
                headers.set("Authorization", format!("Bearer {token}"));
            }
            None => headers.set("x-goog-api-key", key),
        }
        g::set_custom_headers(&mut headers, credential, req);
        g::interactions_revision(&mut headers, req);
        g::interactions_exchange(req, credential, PROVIDER, &client, &url, headers, body).await
    }

    /// Content-Type, the credential (API key, or a fresh access token) and the custom
    /// headers.
    async fn headers(
        &self,
        credential: &Credential,
        req: &ExecRequest,
        cfg: &Config,
        auth: &Auth,
    ) -> Result<GoHeaders, ExecError> {
        let mut headers = GoHeaders::new();
        headers.set("Content-Type", "application/json");
        match auth {
            Auth::ApiKey { key, .. } => headers.set("x-goog-api-key", key.clone()),
            Auth::ServiceAccount { account, .. } => {
                // Token exchange uses the credential's proxy, like the model request.
                let token = vertex_auth::access_token(&self.client(credential, cfg), account, (self.now)())
                    .await
                    .map_err(|error| {
                        tracing::error!(%error, "vertex executor: access token error");
                        g::status_err(500, "internal server error")
                    })?;
                if !token.is_empty() {
                    headers.set("Authorization", format!("Bearer {token}"));
                }
            }
        }
        g::set_custom_headers(&mut headers, credential, req);
        Ok(headers)
    }

    /// The translated original (the payload-rule baseline) and the translated body
    /// through Go's Vertex request edits, before the boundary turns.
    fn prepared_body(
        &self,
        req: &ExecRequest,
        cfg: &Config,
        base_model: &str,
    ) -> Result<(Vec<u8>, Vec<u8>), ExecError> {
        let (from, to) = (req.source_format, Format::Gemini);
        let resolved = g::resolved(req);
        let original = g::translate(req, cfg, to, base_model, g::original_request(req), req.stream, false);
        let body = g::translate(req, cfg, to, base_model, &req.body, req.stream, false)?;
        let original = crate::translate::baseline_or_working(original, &body);
        let mut body = g::apply_thinking(req, body, from, to, PROVIDER, resolved.as_ref())?;
        body = payload::fix_image_aspect_ratio(base_model, body);
        body = payload::set_str_if_different(body, "model", base_model);
        body = strip_tool_call_ids(body, from);
        let body = cpa_common::signature::sanitize_gemini_request_thought_signatures(&body, "contents");
        Ok((original, body))
    }

    async fn generate(
        &self,
        credential: &Credential,
        req: &ExecRequest,
        cfg: &Config,
        auth: &Auth,
    ) -> Result<ExecResponse, ExecError> {
        let base_model = parse_suffix(&req.model).model_name;
        let imagen = is_imagen(&base_model);
        // Only the service-account Execute path speaks Imagen's own request format.
        let imagen_wire = imagen && !req.stream && matches!(auth, Auth::ServiceAccount { .. });
        let (original, mut body) = if imagen_wire {
            let body = imagen_request(&req.body)?;
            let original = if req.original_body.is_empty() {
                body.clone()
            } else {
                imagen_request(&req.original_body)?
            };
            (original, body)
        } else {
            self.prepared_body(req, cfg, &base_model)?
        };
        // Go drops trailing thought-only turns after the leading user turn on Execute
        // and before it on ExecuteStream; with a single model turn the order matters.
        if req.stream {
            body = payload::drop_trailing_thought_only_content(body, "contents");
        }
        body = payload::ensure_leading_user_content(body, "contents");
        if !req.stream {
            body = payload::drop_trailing_thought_only_content(body, "contents");
        }
        body = payload::ensure_trailing_user_content(body, "contents");
        let action = match (imagen, req.stream) {
            (true, _) => "predict",
            (false, true) => "streamGenerateContent",
            (false, false) => "generateContent",
        };
        let mut url = endpoint(auth, &base_model, action);
        match (req.stream, g::alt(req)) {
            (true, _) if imagen => {}
            (true, None) => url.push_str("?alt=sse"),
            (_, Some(alt)) => url.push_str(&format!("?$alt={alt}")),
            (false, None) => {}
        }
        body = payload::delete(body, "session_id");
        req.usage.request(Format::Gemini, &body);
        body = Barrier {
            executor: "",
            model: &base_model,
            protocol: Format::Gemini.as_str(),
            root: "",
            original: &original,
        }
        .apply(cfg, req, body);
        check_url(&url)?;
        let headers = self.headers(credential, req, cfg, auth).await?;
        let capture = req.capture();
        let client = self.client(credential, cfg);
        let body = Bytes::from(body);
        let upstream = g::send_captured(
            capture,
            credential,
            PROVIDER,
            &client,
            &url,
            headers,
            body.clone(),
            req.stream,
        )
        .await?;
        if !(200..300).contains(&upstream.status) {
            return Err(g::error_from(capture, upstream).await);
        }
        let response_headers = upstream.headers.clone();
        if !req.stream {
            // Go logs the raw body, before any Imagen conversion.
            let mut data = g::read_captured(capture, upstream, usize::MAX).await?.to_vec();
            // ponytail: Go observes the response model on the raw body but parses usage
            // after the Imagen conversion, whose usageMetadata is all zeros; Imagen
            // predict responses carry no usageMetadata, so the raw body gives the same.
            req.usage.response_body(Format::Gemini, &data);
            if imagen_wire {
                data = imagen_response(&data, &base_model);
            }
            let out = g::translate_non_stream(req, Format::Gemini, &body, &data)?;
            g::claude_error(req, &out)?;
            return Ok(ExecResponse {
                status: 200,
                headers: response_headers,
                body: ResponseBody::Buffered(out),
            });
        }
        let output = Output::new(req, Format::Gemini, &body)
            .with_claude_stream_errors()
            .require_finish_signal()
            .fail_on_client_drop(g::DropRule::BeforeTerminal { delivered: false });
        let lines = g::captured_lines(proxy::lines(upstream.body, g::MAX_LINE), capture.clone());
        let stream = g::drive(lines, RawLines(output));
        Ok(ExecResponse {
            status: 200,
            headers: response_headers,
            body: ResponseBody::Stream(stream),
        })
    }

    /// `countTokensWith*`: the translated request without tools, generation and safety
    /// settings, a leading user turn only.
    async fn count_tokens(
        &self,
        credential: &Credential,
        req: &ExecRequest,
        cfg: &Config,
    ) -> Result<ExecResponse, ExecError> {
        let auth = auth_for(credential)?;
        let base_model = parse_suffix(&req.model).model_name;
        let (from, to) = (req.source_format, Format::Gemini);
        let resolved = g::resolved(req);
        let body = g::translate(req, cfg, to, &base_model, &req.body, false, false)?;
        let original = g::count_original(req, cfg, to, &base_model, false, &body)?;
        let mut body = g::apply_thinking(req, body, from, to, PROVIDER, resolved.as_ref())?;
        body = payload::fix_image_aspect_ratio(&base_model, body);
        body = gj::try_set_str(&body, "model", &base_model).unwrap_or(body);
        body = strip_tool_call_ids(body, from);
        for path in ["tools", "generationConfig", "safetySettings"] {
            body = payload::delete(body, path);
        }
        body = cpa_common::signature::sanitize_gemini_request_thought_signatures(&body, "contents");
        body = payload::ensure_leading_user_content(body, "contents");
        body = Barrier {
            executor: PROVIDER,
            model: &base_model,
            protocol: to.as_str(),
            root: "",
            original: &original,
        }
        .apply(cfg, req, body);
        let url = endpoint(&auth, &base_model, "countTokens");
        check_url(&url)?;
        let headers = self.headers(credential, req, cfg, &auth).await?;
        let capture = req.capture();
        let client = self.client(credential, cfg);
        let body = Bytes::from(body);
        let upstream = g::send_captured(
            capture,
            credential,
            PROVIDER,
            &client,
            &url,
            headers,
            body.clone(),
            false,
        )
        .await?;
        if !(200..300).contains(&upstream.status) {
            return Err(g::error_from(capture, upstream).await);
        }
        let response_headers = upstream.headers.clone();
        let data = g::read_captured(capture, upstream, usize::MAX).await?;
        let count = gj::get(&data, "totalTokens").int();
        let out = cpa_translate::translate_token_count(req.response_format, to, count, &data);
        Ok(ExecResponse {
            status: 200,
            headers: response_headers,
            body: ResponseBody::Buffered(Bytes::from(out)),
        })
    }
}

/// `type` values the import flag writes and the executor serves.
pub fn handles(provider: &str) -> bool {
    provider == PROVIDER
}

#[cfg(test)]
#[path = "vertex_tests.rs"]
mod tests;