gadk-cli 0.2.2

The gadk deploy CLI: deploy gadk agents to Cloud Run and Vertex AI Agent Engine
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
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! `gadk deploy agentengine`.
//!
//! The flag structs keep ADK's shape (the nested flag groups, field for field in ADK's order);
//! gadk's additions (`bin`, `target`) sit after those fields. The flags are not printed:
//! `--env` values may be secrets.
//!
//! `compute_flags` resolves the Cargo target where ADK splits an entry-point path, and fixes
//! the archive root (`-d`, else the Cargo workspace root); the derived fields are set as
//! ADK sets them (`exec_file` = the binary, `src_base_path` = the package directory,
//! `source_dir` = the absolute archive root). Vertex AI is reached through
//! `gadk_vertexai::reasoning_engine` with [`Env::vertex`].

use std::ffi::OsString;
use std::fs::{self, OpenOptions};
use std::io::{ErrorKind, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use chrono::{Local, SecondsFormat};
use clap::{ArgMatches, Command};
use gadk_platform::{GoDuration, go_path_clean, go_path_join, go_quote};
use gadk_vertexai::reasoning_engine::{ReasoningEngineClient, ReasoningEngineOptions};
use serde_json::{Value, json};

use crate::Env;
use crate::flags::{
    STRAY_ARGS, bool_flag, bool_value, duration_flag, duration_value, int_flag, int_value, passed,
    pflag_command, stray_args, string_flag, string_value,
};
use crate::stage::{BuilderStage, SourceTree, dockerfile, make_temp};
use crate::target::{
    COMPILED_RUSTC_VERSION, CargoTarget, builder_image, builder_rust_version,
    check_path_dependencies, resolve,
};
use crate::util::{Printer, log_start_stop, validate_shell_arg_safe};

pub mod environment;
#[cfg(test)]
pub(crate) mod tests;

use environment::{EnvVar, deployment_spec, register_environment_flags};

/// The bound on waiting for a create/update operation.
pub const AGENT_ENGINE_OPERATION_TIMEOUT: Duration = Duration::from_secs(45 * 60);

/// The command's short description.
pub const SHORT: &str = "Deploys the application to Agent Engine.";
/// The command's long description.
pub const LONG: &str = "Deploys the application to Agent Engine. It creates a source archive, uploads it to create a Reasoning Engine, and cleans up temporary files.";

/// The gcloud flags.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GCloudFlags {
    pub region: String,
    pub project_name: String,
}

/// The memory bank flags.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MemoryBankFlags {
    pub deploy: bool,
    pub model: String,
    pub ttl: GoDuration,
}

/// The Agent Engine service flags. `Debug` shows the `--env` names only: values may be secrets.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct AgentEngineServiceFlags {
    pub name: String,
    pub display_name: String,
    pub server_port: i64,
    pub agent_engine_id: String,
    pub memory_bank: MemoryBankFlags,
    /// `--env` entries, verbatim (unvalidated until
    /// [`AgentEngineFlags::environment_variables`]).
    pub env: Vec<OsString>,
    /// `--default_env`.
    pub default_env: bool,
    /// The environment [`AgentEngineFlags::compute_flags`] computed.
    pub env_vars: Vec<EnvVar>,
    /// `--env` or `--default_env` was on the command line: an update
    /// replaces the environment.
    pub update_env: bool,
}

impl std::fmt::Debug for AgentEngineServiceFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Each `--env` entry as its name (the text before the first `=`), value redacted; an
        // entry without `=` is malformed and could be a bare value, so it is redacted whole.
        let env: Vec<String> = self
            .env
            .iter()
            .map(|e| {
                let e = e.to_string_lossy();
                match e.split_once('=') {
                    Some((name, _)) => format!("{name}=<redacted>"),
                    None => "<redacted>".to_owned(),
                }
            })
            .collect();
        f.debug_struct("AgentEngineServiceFlags")
            .field("name", &self.name)
            .field("display_name", &self.display_name)
            .field("server_port", &self.server_port)
            .field("agent_engine_id", &self.agent_engine_id)
            .field("memory_bank", &self.memory_bank)
            .field("env", &env)
            .field("default_env", &self.default_env)
            .field("env_vars", &self.env_vars)
            .field("update_env", &self.update_env)
            .finish()
    }
}

/// The build flags: the temp dir and the paths derived from it by `compute_flags`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BuildFlags {
    pub temp_dir: String,
    pub exec_path: String,
    pub exec_file: String,
    pub dockerfile_build_path: String,
    pub archive_path: String,
}

/// The source flags: the entry point, its original form and the derived source paths.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SourceFlags {
    pub src_base_path: String,
    pub entry_point_path: String,
    pub orig_entry_point_path: String,
    pub source_dir: String,
}

/// The flags of `gadk deploy agentengine`, plus gadk's `--bin` and the resolved Cargo target.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AgentEngineFlags {
    pub gcloud: GCloudFlags,
    pub agent_engine: AgentEngineServiceFlags,
    pub build: BuildFlags,
    pub source: SourceFlags,
    /// gadk's `--bin` (not printed).
    pub bin: String,
    /// The Cargo target `compute_flags` resolved (not printed).
    pub target: Option<CargoTarget>,
}

/// The `agentengine` command with its flags, in ADK's order, plus gadk's `--bin`.
/// Positional arguments are collected (not a clap error) so [`validate_args`] can reject them
/// with ADK's text.
pub fn command() -> Command {
    let cmd = pflag_command("agentengine")
        .about(SHORT)
        .long_about(LONG)
        .arg(string_flag("region", Some('r'), "", "GCP Region"))
        .arg(string_flag("project_name", Some('p'), "", "GCP Project Name"))
        .arg(string_flag("name", Some('s'), "", "Agent Engine name"))
        .arg(string_flag(
            "temp_dir",
            Some('t'),
            "",
            "Temp dir for build, defaults to os.TempDir() if not specified",
        ))
        .arg(int_flag("server_port", None, "8080", "agentEngine server port"))
        // `-e` names a Cargo package.
        .arg(string_flag(
            "entry_point_path",
            Some('e'),
            "",
            "Path to the Cargo package of the entry point (its directory or Cargo.toml), defaults to the current directory",
        ))
        // The archive root defaults to the Cargo workspace root.
        .arg(string_flag(
            "source_dir",
            Some('d'),
            "",
            "Directory to archive (the Cargo workspace root or an ancestor of it), defaults to the Cargo workspace root",
        ))
        .arg(string_flag(
            "agent_engine_id",
            None,
            "",
            "ID of the Agent Engine instance to update if it exists (default: \"\", which means a new instance will be created).",
        ))
        .arg(bool_flag(
            "mem_deploy",
            false,
            "If set to true then memory bank will be deployed too",
        ))
        .arg(string_flag(
            "mem_model",
            None,
            "",
            "Name of the model to be used for memory generation, as publishers/google/models/<model_id>. If empty, Memory Bank uses its own default model. A non-empty value is prefixed with projects/<project_name>/locations/<region>, so the model must be available in that region. To list models, GET https://${LOCATION_ID}-aiplatform.googleapis.com/v1beta1/publishers/google/models",
        ))
        .arg(duration_flag(
            "mem_ttl",
            None,
            "8760h0m0s",
            "Time-To-Live for memories",
        ));
    register_environment_flags(cmd)
        // A gadk-only flag selecting the Cargo binary target.
        .arg(string_flag(
            "bin",
            None,
            "",
            "Binary target of the package to deploy, required when the package has more than one",
        ))
        .arg(stray_args())
}

/// Accepts no positional arguments: any positional argument fails with
/// `accepts 0 arg(s), received N`, which does not echo the arguments; runs before
/// anything else.
pub fn validate_args(m: &ArgMatches) -> Result<(), String> {
    let n = m.get_raw(STRAY_ARGS).map_or(0, |v| v.len());
    if n != 0 {
        return Err(format!("accepts 0 arg(s), received {n}"));
    }
    Ok(())
}

/// The flags of a parsed `agentengine` command;
/// the derived fields are empty until [`AgentEngineFlags::compute_flags`].
pub fn from_matches(m: &ArgMatches) -> AgentEngineFlags {
    AgentEngineFlags {
        gcloud: GCloudFlags {
            region: string_value(m, "region"),
            project_name: string_value(m, "project_name"),
        },
        agent_engine: AgentEngineServiceFlags {
            name: string_value(m, "name"),
            display_name: String::new(),
            server_port: int_value(m, "server_port"),
            agent_engine_id: string_value(m, "agent_engine_id"),
            memory_bank: MemoryBankFlags {
                deploy: bool_value(m, "mem_deploy"),
                model: string_value(m, "mem_model"),
                ttl: duration_value(m, "mem_ttl"),
            },
            env: m
                .get_many::<OsString>("env")
                .map(|v| v.cloned().collect())
                .unwrap_or_default(),
            default_env: bool_value(m, "default_env"),
            env_vars: Vec::new(),
            update_env: passed(m, "env") || passed(m, "default_env"),
        },
        build: BuildFlags {
            temp_dir: string_value(m, "temp_dir"),
            ..BuildFlags::default()
        },
        source: SourceFlags {
            entry_point_path: string_value(m, "entry_point_path"),
            source_dir: string_value(m, "source_dir"),
            ..SourceFlags::default()
        },
        bin: string_value(m, "bin"),
        target: None,
    }
}

/// `path` relative to `root` when `path` is `root` or lies under it: compared lexically (both
/// cleaned), else once both resolve (a symlinked temp or source dir).
fn relative_to(path: &Path, root: &Path) -> Option<PathBuf> {
    let clean = |p: &Path| PathBuf::from(go_path_clean(&p.to_string_lossy()));
    if let Ok(rel) = clean(path).strip_prefix(clean(root)) {
        return Some(rel.to_path_buf());
    }
    let (path, root) = (fs::canonicalize(path).ok()?, fs::canonicalize(root).ok()?);
    path.strip_prefix(root).ok().map(Path::to_path_buf)
}

/// A `google.protobuf.Duration` in its JSON form: seconds with 0, 3, 6 or 9 fractional digits and
/// an `s` suffix (`86400s`, `1.500s`, `-0.000000001s`).
fn protojson_duration(d: GoDuration) -> String {
    let (secs, nanos) = (d.0 / 1_000_000_000, d.0 % 1_000_000_000);
    let sign = if secs == 0 && nanos < 0 { "-" } else { "" };
    let x = format!("{sign}{secs}.{:09}", nanos.unsigned_abs());
    let x = x.strip_suffix("000").unwrap_or(&x);
    let x = x.strip_suffix("000").unwrap_or(x);
    let x = x.strip_suffix(".000").unwrap_or(x);
    format!("{x}s")
}

/// Waits for the operation, bounded by [`AGENT_ENGINE_OPERATION_TIMEOUT`],
/// wrapped as `operation failed: <error>`.
async fn wait_for_operation(client: &ReasoningEngineClient, op: Value) -> Result<Value, String> {
    match tokio::time::timeout(AGENT_ENGINE_OPERATION_TIMEOUT, client.wait(op)).await {
        Ok(Ok(engine)) => Ok(engine),
        Ok(Err(e)) => Err(format!("operation failed: {e}")),
        Err(_) => Err("operation failed: context deadline exceeded".to_string()),
    }
}

/// A string field of a JSON message (`""` when absent).
fn str_field<'a>(v: &'a Value, name: &str) -> &'a str {
    v.get(name).and_then(Value::as_str).unwrap_or_default()
}

impl AgentEngineFlags {
    /// Computes the derived flags: the environment (validated first, before any other step),
    /// target resolution, the shell-safe checks, the archive root,
    /// the `agentEngine_<local time>__*` temp dir, the derived paths, the display name and the
    /// `--mem_model` prefix. Every check runs before the temp dir is created.
    pub async fn compute_flags(&mut self, env: &Env) -> Result<(), String> {
        log_start_stop(
            &env.out,
            "Computing flags & preparing temp",
            async |p: Printer| {
                self.agent_engine.env_vars = self.environment_variables()?;
                self.source.orig_entry_point_path = self.source.entry_point_path.clone();
                let orig = self.source.orig_entry_point_path.clone();
                self.source.entry_point_path = env.abs(&orig).to_string_lossy().into_owned();

                // Resolves the Cargo package and binary, the binary standing in for `exec_file`
                // and the package directory for `src_base_path`.
                let target = resolve(env, &orig, &self.bin).await?;
                self.source.src_base_path = target.manifest_dir.to_string_lossy().into_owned();
                if self.build.exec_path.is_empty() {
                    self.build.exec_file = target.bin.clone();
                }

                validate_shell_arg_safe(
                    &self.build.exec_file,
                    &format!(
                        "executable name derived from --entry_point_path {}:",
                        go_quote(&orig)
                    ),
                )?;
                // The package name reaches the RUN line's `-p`.
                validate_shell_arg_safe(
                    &target.package,
                    &format!(
                        "package name derived from --entry_point_path {}:",
                        go_quote(&orig)
                    ),
                )?;
                validate_shell_arg_safe(&orig, "--entry_point_path")?;

                // The archive root is `-d` or else the Cargo workspace
                // root, and must contain the workspace root,
                // whose path below it becomes the builder's WORKDIR.
                let archive_root = if self.source.source_dir.is_empty() {
                    target.workspace_root.clone()
                } else {
                    env.abs(&self.source.source_dir)
                };
                let Some(workdir) = relative_to(&target.workspace_root, &archive_root) else {
                    return Err(format!(
                        "--source_dir {} is neither the Cargo workspace root {} nor an ancestor of it",
                        go_quote(&self.source.source_dir),
                        go_quote(&target.workspace_root.to_string_lossy())
                    ));
                };
                validate_shell_arg_safe(workdir.as_os_str().as_encoded_bytes(), "--source_dir")?;
                check_path_dependencies(&target, &archive_root)?;
                self.source.source_dir = archive_root.to_string_lossy().into_owned();
                self.target = Some(target);

                if self.build.temp_dir.is_empty() {
                    self.build.temp_dir = env.temp_dir().to_string_lossy().into_owned();
                }
                let absp = env.abs(&self.build.temp_dir);
                // The wrapped error is Rust's `io::Error` text.
                let dir = make_temp(&absp, "agentEngine_", env.time.now()).map_err(|e| {
                    format!(
                        "cannot create a temporary sub directory in '{}': {e}",
                        absp.display()
                    )
                })?;
                self.build.temp_dir = dir.to_string_lossy().into_owned();
                p.print(&[&"Using temp dir:", &self.build.temp_dir]);

                if self.build.exec_path.is_empty() {
                    self.build.exec_path = go_path_join(&[&self.build.temp_dir, &self.build.exec_file]);
                }
                self.build.dockerfile_build_path =
                    go_path_join(&[self.build.temp_dir.as_str(), "Dockerfile"]);
                self.build.archive_path = go_path_join(&[self.build.temp_dir.as_str(), "archive.tgz"]);

                let date_time = env
                    .time
                    .now()
                    .with_timezone(&Local)
                    .to_rfc3339_opts(SecondsFormat::Secs, true);
                self.agent_engine.display_name = self.agent_engine.name.clone();
                if self.agent_engine.display_name.is_empty() {
                    self.agent_engine.display_name = format!("ADK Agent: {date_time}");
                }

                // prefix an explicit model with the project and region
                if !self.agent_engine.memory_bank.model.is_empty() {
                    self.agent_engine.memory_bank.model = format!(
                        "projects/{}/locations/{}/{}",
                        self.gcloud.project_name,
                        self.gcloud.region,
                        self.agent_engine.memory_bank.model
                    );
                }
                Ok(())
            },
        )
        .await
    }

    /// Removes the temp dir.
    pub async fn clean_temp(&self, env: &Env) -> Result<(), String> {
        log_start_stop(&env.out, "Cleaning temp", async |p: Printer| {
            p.print(&[&"Clean temp starting with", &self.build.temp_dir]);
            // The wrapped error is Rust's `io::Error` text.
            match fs::remove_dir_all(&self.build.temp_dir) {
                // A missing path is not an error.
                Err(e) if e.kind() != ErrorKind::NotFound => Err(format!(
                    "failed to clean temp directory {}: {e}",
                    self.build.temp_dir
                )),
                _ => Ok(()),
            }
        })
        .await
    }

    /// The directory archived: `source_dir` (absolute
    /// after [`compute_flags`](Self::compute_flags)), else the target's workspace root.
    fn archive_root(&self) -> PathBuf {
        if self.source.source_dir.is_empty() {
            self.target
                .as_ref()
                .map(|t| t.workspace_root.clone())
                .unwrap_or_default()
        } else {
            PathBuf::from(&self.source.source_dir)
        }
    }

    /// Prepares the Dockerfile: reads only the receiver (the builder version from the
    /// target's workspace, `WORKDIR /app/<workspace root below the archive root>`, `-p
    /// <package> --bin <exec_file>`, `EXPOSE`/`CMD` from `server_port`), written with mode 0600.
    pub async fn prepare_dockerfile(&self, env: &Env) -> Result<(), String> {
        log_start_stop(&env.out, "Preparing Dockerfile", async |p: Printer| {
            p.print(&[&"Writing:", &self.build.dockerfile_build_path]);
            let target = self.target.clone().unwrap_or_default();
            let workdir = relative_to(&target.workspace_root, &self.archive_root())
                .map(|w| w.to_string_lossy().into_owned())
                .unwrap_or_default();
            let builder = BuilderStage {
                image: builder_image(&builder_rust_version(&target, COMPILED_RUSTC_VERSION)),
                workdir,
                package: target.package,
                bin: self.build.exec_file.clone(),
            };
            let text = dockerfile(
                &builder,
                self.agent_engine.server_port,
                r#", "agentengine""#,
            );
            // The error is Rust's `io::Error` text.
            OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .mode(0o600)
                .open(&self.build.dockerfile_build_path)
                .and_then(|mut f| f.write_all(text.as_bytes()))
                .map_err(|e| e.to_string())
        })
        .await
    }

    /// Creates the archive: the sorted tar.gz of the archive root (without `.git`,
    /// `target`, a nested temp dir and the root `Dockerfile`) with the generated `Dockerfile`
    /// last.
    // The archive is written in-process (no `Running :` line, gadk's error texts) and leaves
    // out a root `Dockerfile` of the source, so only the generated one is archived.
    pub async fn create_archive(&self, env: &Env) -> Result<(), String> {
        log_start_stop(&env.out, "Creating source archive", async |p: Printer| {
            let root = self.archive_root();
            p.print(&[&"Creating:", &self.build.archive_path]);
            let mut exclude = vec![root.join("Dockerfile")];
            if let Some(rel) = relative_to(Path::new(&self.build.temp_dir), &root)
                && !rel.as_os_str().is_empty()
            {
                exclude.push(root.join(rel));
            }
            let tree = SourceTree::walk(&root, &exclude).map_err(|e| {
                format!(
                    "cannot read the source directory {}: {e}",
                    go_quote(&root.to_string_lossy())
                )
            })?;
            let generated = fs::read(&self.build.dockerfile_build_path)
                .map_err(|e| format!("cannot read the generated Dockerfile: {e}"))?;
            tree.write_tar_gz(
                Path::new(&self.build.archive_path),
                &[("Dockerfile", generated.as_slice())],
            )
            .map_err(|e| {
                format!(
                    "cannot write the source archive {}: {e}",
                    go_quote(&self.build.archive_path)
                )
            })
        })
        .await
    }

    /// The memory bank context spec as a `ReasoningEngineContextSpec` in JSON form:
    /// `memoryBankConfig.ttlConfig.defaultTtl` = `--mem_ttl`, and
    /// `memoryBankConfig.generationConfig.model` only for a non-empty `--mem_model`.
    pub fn memory_bank_context_spec(&self) -> Value {
        let mb = &self.agent_engine.memory_bank;
        let mut cfg = json!({"ttlConfig": {"defaultTtl": protojson_duration(mb.ttl)}});
        if !mb.model.is_empty() {
            cfg["generationConfig"] = json!({"model": mb.model});
        }
        json!({"memoryBankConfig": cfg})
    }

    /// Builds the Reasoning Engine client for the region's Vertex AI endpoint
    /// with [`Env::vertex`]; ADC reads [`Env::env`] unless the options name an environment.
    fn client(&self, env: &Env) -> Result<ReasoningEngineClient, String> {
        let mut opts: ReasoningEngineOptions = env.vertex.clone();
        if opts.env.is_none() {
            opts.env = Some(env.env.clone());
        }
        ReasoningEngineClient::new(&self.gcloud.region, opts)
            .map_err(|e| format!("cannot create ReasoningEngineClient: {e}"))
    }

    /// The parts of the create and update requests read from disk and the server package:
    /// the `sourceCodeSpec` (inline archive, empty `imageSpec`) and the class methods,
    /// printing `Methods: <json>`.
    fn source_code_spec_and_methods(&self, p: &Printer) -> Result<(Value, Value), String> {
        // The wrapped error is Rust's `io::Error` text.
        let archive = fs::read(&self.build.archive_path)
            .map_err(|e| format!("cannot read archive file: {e}"))?;
        let methods = gadk_server::agentengine::list_class_methods();
        let methods_json =
            gadk_model::to_go_json(&methods).map_err(|e| format!("cannot marshal methods: {e}"))?;
        p.print(&[&"Methods:", &String::from_utf8_lossy(&methods_json)]);
        let source_code_spec = json!({
            "inlineSource": {"sourceArchive": STANDARD.encode(&archive)},
            "imageSpec": {},
        });
        Ok((source_code_spec, Value::from(methods)))
    }

    /// Creates the Reasoning Engine: `CreateReasoningEngine` under
    /// `projects/<p>/locations/<r>`, then the operation awaited for at most 45 minutes.
    pub async fn deploy_to_agent_engine(&self, env: &Env) -> Result<(), String> {
        log_start_stop(&env.out, "Deploying to Agent Engine", async |p: Printer| {
            let parent = format!(
                "projects/{}/locations/{}",
                self.gcloud.project_name, self.gcloud.region
            );
            let client = self.client(env)?;
            let (source_code_spec, methods) = self.source_code_spec_and_methods(&p)?;
            let mut engine = json!({
                "displayName": self.agent_engine.display_name,
                "spec": {
                    "sourceCodeSpec": source_code_spec,
                    "agentFramework": "google-adk",
                    "deploymentSpec": deployment_spec(&self.agent_engine.env_vars),
                    "classMethods": methods,
                },
            });
            if self.agent_engine.memory_bank.deploy {
                engine["contextSpec"] = self.memory_bank_context_spec();
            }

            p.print(&[&"Sending CreateReasoningEngine request..."]);
            let op = client
                .create(&parent, engine)
                .await
                .map_err(|e| format!("CreateReasoningEngine failed: {e}"))?;

            p.print(&[&"Waiting for operation to complete..."]);
            let re = wait_for_operation(&client, op).await?;

            p.print(&[&"Deployed Reasoning Engine:", &str_field(&re, "name")]);
            p.print(&[&"Display Name:", &str_field(&re, "displayName")]);
            Ok(())
        })
        .await
    }

    /// Updates the Reasoning Engine: `UpdateReasoningEngine` of
    /// `projects/<p>/locations/<r>/reasoningEngines/<id>` with the update mask in JSON
    /// form (the environment only when [`AgentEngineServiceFlags::update_env`], before the
    /// memory bank's `spec.contextSpec`), then the operation awaited for at most 45 minutes.
    pub async fn update_agent_engine(&self, env: &Env) -> Result<(), String> {
        log_start_stop(&env.out, "Updating Agent Engine", async |p: Printer| {
            let name = format!(
                "projects/{}/locations/{}/reasoningEngines/{}",
                self.gcloud.project_name, self.gcloud.region, self.agent_engine.agent_engine_id
            );
            let client = self.client(env)?;
            let (source_code_spec, methods) = self.source_code_spec_and_methods(&p)?;
            let mut engine = json!({
                "name": name,
                "spec": {
                    "sourceCodeSpec": source_code_spec,
                    "classMethods": methods,
                },
            });
            let mut mask = vec!["spec.sourceCodeSpec", "spec.classMethods"];
            if self.agent_engine.update_env {
                engine["spec"]["deploymentSpec"] = deployment_spec(&self.agent_engine.env_vars);
                mask.push("spec.deploymentSpec.env");
            }
            if self.agent_engine.memory_bank.deploy {
                engine["contextSpec"] = self.memory_bank_context_spec();
                // The mask path `spec.context_spec` is kept (in JSON form) although `contextSpec`
                // is a top-level ReasoningEngine field.
                mask.push("spec.contextSpec");
            }

            p.print(&[&"Sending UpdateReasoningEngine request..."]);
            let op = client
                .update(engine, &mask)
                .await
                .map_err(|e| format!("UpdateReasoningEngine failed: {e}"))?;

            p.print(&[&"Waiting for operation to complete..."]);
            let re = wait_for_operation(&client, op).await?;

            p.print(&[&"Updated Reasoning Engine:", &str_field(&re, "name")]);
            p.print(&[&"Display Name:", &str_field(&re, "displayName")]);
            Ok(())
        })
        .await
    }

    /// Deploys: compute → Dockerfile → archive → update|deploy → clean,
    /// stopping at the first error (the temp dir is kept).
    pub async fn deploy_on_agent_engine(&mut self, env: &Env) -> Result<(), String> {
        self.compute_flags(env).await?;
        self.prepare_dockerfile(env).await?;
        self.create_archive(env).await?;
        if !self.agent_engine.agent_engine_id.is_empty() {
            self.update_agent_engine(env).await?;
        } else {
            self.deploy_to_agent_engine(env).await?;
        }
        self.clean_temp(env).await
    }
}