Skip to main content

gadk_cli/deploy/
agentengine.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! `gadk deploy agentengine`.
17//!
18//! The flag structs keep ADK's shape (the nested flag groups, field for field in ADK's order);
19//! gadk's additions (`bin`, `target`) sit after those fields. The flags are not printed:
20//! `--env` values may be secrets.
21//!
22//! `compute_flags` resolves the Cargo target where ADK splits an entry-point path, and fixes
23//! the archive root (`-d`, else the Cargo workspace root); the derived fields are set as
24//! ADK sets them (`exec_file` = the binary, `src_base_path` = the package directory,
25//! `source_dir` = the absolute archive root). Vertex AI is reached through
26//! `gadk_vertexai::reasoning_engine` with [`Env::vertex`].
27
28use std::ffi::OsString;
29use std::fs::{self, OpenOptions};
30use std::io::{ErrorKind, Write};
31use std::os::unix::fs::OpenOptionsExt;
32use std::path::{Path, PathBuf};
33use std::time::Duration;
34
35use base64::Engine;
36use base64::engine::general_purpose::STANDARD;
37use chrono::{Local, SecondsFormat};
38use clap::{ArgMatches, Command};
39use gadk_platform::{GoDuration, go_path_clean, go_path_join, go_quote};
40use gadk_vertexai::reasoning_engine::{ReasoningEngineClient, ReasoningEngineOptions};
41use serde_json::{Value, json};
42
43use crate::Env;
44use crate::flags::{
45    STRAY_ARGS, bool_flag, bool_value, duration_flag, duration_value, int_flag, int_value, passed,
46    pflag_command, stray_args, string_flag, string_value,
47};
48use crate::stage::{BuilderStage, SourceTree, dockerfile, make_temp};
49use crate::target::{
50    COMPILED_RUSTC_VERSION, CargoTarget, builder_image, builder_rust_version,
51    check_path_dependencies, resolve,
52};
53use crate::util::{Printer, log_start_stop, validate_shell_arg_safe};
54
55pub mod environment;
56#[cfg(test)]
57pub(crate) mod tests;
58
59use environment::{EnvVar, deployment_spec, register_environment_flags};
60
61/// The bound on waiting for a create/update operation.
62pub const AGENT_ENGINE_OPERATION_TIMEOUT: Duration = Duration::from_secs(45 * 60);
63
64/// The command's short description.
65pub const SHORT: &str = "Deploys the application to Agent Engine.";
66/// The command's long description.
67pub 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.";
68
69/// The gcloud flags.
70#[derive(Debug, Clone, Default, PartialEq, Eq)]
71pub struct GCloudFlags {
72    /// `--region` (`-r`): the GCP region.
73    pub region: String,
74    /// `--project_name` (`-p`): the GCP project.
75    pub project_name: String,
76}
77
78/// The memory bank flags.
79#[derive(Debug, Clone, Default, PartialEq, Eq)]
80pub struct MemoryBankFlags {
81    /// `--mem_deploy`: whether to deploy a Memory Bank too.
82    pub deploy: bool,
83    /// `--mem_model`: the Memory Bank model (`publishers/google/models/<model_id>`); empty uses
84    /// Memory Bank's default. [`AgentEngineFlags::compute_flags`] prefixes a non-empty value with
85    /// `projects/<project_name>/locations/<region>/`.
86    pub model: String,
87    /// `--mem_ttl`: the time-to-live of memories (default `8760h0m0s`).
88    pub ttl: GoDuration,
89}
90
91/// The Agent Engine service flags. `Debug` shows the `--env` names only: values may be secrets.
92#[derive(Clone, Default, PartialEq, Eq)]
93pub struct AgentEngineServiceFlags {
94    /// `--name` (`-s`): the Agent Engine name.
95    pub name: String,
96    /// The display name [`AgentEngineFlags::compute_flags`] derives: the name, or
97    /// `ADK Agent: <local time>` when the name is empty.
98    pub display_name: String,
99    /// `--server_port`: the agent server's port (default 8080).
100    pub server_port: i64,
101    /// `--agent_engine_id`: the Agent Engine instance to update; empty creates a new one.
102    pub agent_engine_id: String,
103    /// The Memory Bank flags.
104    pub memory_bank: MemoryBankFlags,
105    /// `--env` entries, verbatim (unvalidated until
106    /// [`AgentEngineFlags::environment_variables`]).
107    pub env: Vec<OsString>,
108    /// `--default_env`.
109    pub default_env: bool,
110    /// The environment [`AgentEngineFlags::compute_flags`] computed.
111    pub env_vars: Vec<EnvVar>,
112    /// `--env` or `--default_env` was on the command line: an update
113    /// replaces the environment.
114    pub update_env: bool,
115}
116
117impl std::fmt::Debug for AgentEngineServiceFlags {
118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        // Each `--env` entry as its name (the text before the first `=`), value redacted; an
120        // entry without `=` is malformed and could be a bare value, so it is redacted whole.
121        let env: Vec<String> = self
122            .env
123            .iter()
124            .map(|e| {
125                let e = e.to_string_lossy();
126                match e.split_once('=') {
127                    Some((name, _)) => format!("{name}=<redacted>"),
128                    None => "<redacted>".to_owned(),
129                }
130            })
131            .collect();
132        f.debug_struct("AgentEngineServiceFlags")
133            .field("name", &self.name)
134            .field("display_name", &self.display_name)
135            .field("server_port", &self.server_port)
136            .field("agent_engine_id", &self.agent_engine_id)
137            .field("memory_bank", &self.memory_bank)
138            .field("env", &env)
139            .field("default_env", &self.default_env)
140            .field("env_vars", &self.env_vars)
141            .field("update_env", &self.update_env)
142            .finish()
143    }
144}
145
146/// The build flags: the temp dir and the paths derived from it by `compute_flags`.
147#[derive(Debug, Clone, Default, PartialEq, Eq)]
148pub struct BuildFlags {
149    /// `--temp_dir` (`-t`); after [`AgentEngineFlags::compute_flags`], the `agentEngine_*`
150    /// directory it created there (in the system temp dir when the flag is empty).
151    pub temp_dir: String,
152    /// The path of the built executable: `<temp_dir>/<exec_file>` unless already set.
153    pub exec_path: String,
154    /// The executable name: the resolved Cargo binary target when `exec_path` is empty.
155    pub exec_file: String,
156    /// The path of the generated Dockerfile: `<temp_dir>/Dockerfile`.
157    pub dockerfile_build_path: String,
158    /// The path of the source archive: `<temp_dir>/archive.tgz`.
159    pub archive_path: String,
160}
161
162/// The source flags: the entry point, its original form and the derived source paths.
163#[derive(Debug, Clone, Default, PartialEq, Eq)]
164pub struct SourceFlags {
165    /// The directory of the resolved Cargo package.
166    pub src_base_path: String,
167    /// `--entry_point_path` (`-e`); made absolute by [`AgentEngineFlags::compute_flags`].
168    pub entry_point_path: String,
169    /// `--entry_point_path` as given on the command line.
170    pub orig_entry_point_path: String,
171    /// `--source_dir` (`-d`); after [`AgentEngineFlags::compute_flags`], the absolute archive
172    /// root (the Cargo workspace root when the flag is empty).
173    pub source_dir: String,
174}
175
176/// The flags of `gadk deploy agentengine`, plus gadk's `--bin` and the resolved Cargo target.
177#[derive(Debug, Clone, Default, PartialEq, Eq)]
178pub struct AgentEngineFlags {
179    /// The gcloud flags.
180    pub gcloud: GCloudFlags,
181    /// The Agent Engine service flags.
182    pub agent_engine: AgentEngineServiceFlags,
183    /// The build paths.
184    pub build: BuildFlags,
185    /// The source paths.
186    pub source: SourceFlags,
187    /// gadk's `--bin` (not printed).
188    pub bin: String,
189    /// The Cargo target `compute_flags` resolved (not printed).
190    pub target: Option<CargoTarget>,
191}
192
193/// The `agentengine` command with its flags, in ADK's order, plus gadk's `--bin`.
194/// Positional arguments are collected (not a clap error) so [`validate_args`] can reject them
195/// with ADK's text.
196pub fn command() -> Command {
197    let cmd = pflag_command("agentengine")
198        .about(SHORT)
199        .long_about(LONG)
200        .arg(string_flag("region", Some('r'), "", "GCP Region"))
201        .arg(string_flag("project_name", Some('p'), "", "GCP Project Name"))
202        .arg(string_flag("name", Some('s'), "", "Agent Engine name"))
203        .arg(string_flag(
204            "temp_dir",
205            Some('t'),
206            "",
207            "Temp dir for build, defaults to os.TempDir() if not specified",
208        ))
209        .arg(int_flag("server_port", None, "8080", "agentEngine server port"))
210        // `-e` names a Cargo package.
211        .arg(string_flag(
212            "entry_point_path",
213            Some('e'),
214            "",
215            "Path to the Cargo package of the entry point (its directory or Cargo.toml), defaults to the current directory",
216        ))
217        // The archive root defaults to the Cargo workspace root.
218        .arg(string_flag(
219            "source_dir",
220            Some('d'),
221            "",
222            "Directory to archive (the Cargo workspace root or an ancestor of it), defaults to the Cargo workspace root",
223        ))
224        .arg(string_flag(
225            "agent_engine_id",
226            None,
227            "",
228            "ID of the Agent Engine instance to update if it exists (default: \"\", which means a new instance will be created).",
229        ))
230        .arg(bool_flag(
231            "mem_deploy",
232            false,
233            "If set to true then memory bank will be deployed too",
234        ))
235        .arg(string_flag(
236            "mem_model",
237            None,
238            "",
239            "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",
240        ))
241        .arg(duration_flag(
242            "mem_ttl",
243            None,
244            "8760h0m0s",
245            "Time-To-Live for memories",
246        ));
247    register_environment_flags(cmd)
248        // A gadk-only flag selecting the Cargo binary target.
249        .arg(string_flag(
250            "bin",
251            None,
252            "",
253            "Binary target of the package to deploy, required when the package has more than one",
254        ))
255        .arg(stray_args())
256}
257
258/// Accepts no positional arguments: any positional argument fails with
259/// `accepts 0 arg(s), received N`, which does not echo the arguments; runs before
260/// anything else.
261pub fn validate_args(m: &ArgMatches) -> Result<(), String> {
262    let n = m.get_raw(STRAY_ARGS).map_or(0, |v| v.len());
263    if n != 0 {
264        return Err(format!("accepts 0 arg(s), received {n}"));
265    }
266    Ok(())
267}
268
269/// The flags of a parsed `agentengine` command;
270/// the derived fields are empty until [`AgentEngineFlags::compute_flags`].
271pub fn from_matches(m: &ArgMatches) -> AgentEngineFlags {
272    AgentEngineFlags {
273        gcloud: GCloudFlags {
274            region: string_value(m, "region"),
275            project_name: string_value(m, "project_name"),
276        },
277        agent_engine: AgentEngineServiceFlags {
278            name: string_value(m, "name"),
279            display_name: String::new(),
280            server_port: int_value(m, "server_port"),
281            agent_engine_id: string_value(m, "agent_engine_id"),
282            memory_bank: MemoryBankFlags {
283                deploy: bool_value(m, "mem_deploy"),
284                model: string_value(m, "mem_model"),
285                ttl: duration_value(m, "mem_ttl"),
286            },
287            env: m
288                .get_many::<OsString>("env")
289                .map(|v| v.cloned().collect())
290                .unwrap_or_default(),
291            default_env: bool_value(m, "default_env"),
292            env_vars: Vec::new(),
293            update_env: passed(m, "env") || passed(m, "default_env"),
294        },
295        build: BuildFlags {
296            temp_dir: string_value(m, "temp_dir"),
297            ..BuildFlags::default()
298        },
299        source: SourceFlags {
300            entry_point_path: string_value(m, "entry_point_path"),
301            source_dir: string_value(m, "source_dir"),
302            ..SourceFlags::default()
303        },
304        bin: string_value(m, "bin"),
305        target: None,
306    }
307}
308
309/// `path` relative to `root` when `path` is `root` or lies under it: compared lexically (both
310/// cleaned), else once both resolve (a symlinked temp or source dir).
311fn relative_to(path: &Path, root: &Path) -> Option<PathBuf> {
312    let clean = |p: &Path| PathBuf::from(go_path_clean(&p.to_string_lossy()));
313    if let Ok(rel) = clean(path).strip_prefix(clean(root)) {
314        return Some(rel.to_path_buf());
315    }
316    let (path, root) = (fs::canonicalize(path).ok()?, fs::canonicalize(root).ok()?);
317    path.strip_prefix(root).ok().map(Path::to_path_buf)
318}
319
320/// A `google.protobuf.Duration` in its JSON form: seconds with 0, 3, 6 or 9 fractional digits and
321/// an `s` suffix (`86400s`, `1.500s`, `-0.000000001s`).
322fn protojson_duration(d: GoDuration) -> String {
323    let (secs, nanos) = (d.0 / 1_000_000_000, d.0 % 1_000_000_000);
324    let sign = if secs == 0 && nanos < 0 { "-" } else { "" };
325    let x = format!("{sign}{secs}.{:09}", nanos.unsigned_abs());
326    let x = x.strip_suffix("000").unwrap_or(&x);
327    let x = x.strip_suffix("000").unwrap_or(x);
328    let x = x.strip_suffix(".000").unwrap_or(x);
329    format!("{x}s")
330}
331
332/// Waits for the operation, bounded by [`AGENT_ENGINE_OPERATION_TIMEOUT`],
333/// wrapped as `operation failed: <error>`.
334async fn wait_for_operation(client: &ReasoningEngineClient, op: Value) -> Result<Value, String> {
335    match tokio::time::timeout(AGENT_ENGINE_OPERATION_TIMEOUT, client.wait(op)).await {
336        Ok(Ok(engine)) => Ok(engine),
337        Ok(Err(e)) => Err(format!("operation failed: {e}")),
338        Err(_) => Err("operation failed: context deadline exceeded".to_string()),
339    }
340}
341
342/// A string field of a JSON message (`""` when absent).
343fn str_field<'a>(v: &'a Value, name: &str) -> &'a str {
344    v.get(name).and_then(Value::as_str).unwrap_or_default()
345}
346
347impl AgentEngineFlags {
348    /// Computes the derived flags: the environment (validated first, before any other step),
349    /// target resolution, the shell-safe checks, the archive root,
350    /// the `agentEngine_<local time>__*` temp dir, the derived paths, the display name and the
351    /// `--mem_model` prefix. Every check runs before the temp dir is created.
352    pub async fn compute_flags(&mut self, env: &Env) -> Result<(), String> {
353        log_start_stop(
354            &env.out,
355            "Computing flags & preparing temp",
356            async |p: Printer| {
357                self.agent_engine.env_vars = self.environment_variables()?;
358                self.source.orig_entry_point_path = self.source.entry_point_path.clone();
359                let orig = self.source.orig_entry_point_path.clone();
360                self.source.entry_point_path = env.abs(&orig).to_string_lossy().into_owned();
361
362                // Resolves the Cargo package and binary, the binary standing in for `exec_file`
363                // and the package directory for `src_base_path`.
364                let target = resolve(env, &orig, &self.bin).await?;
365                self.source.src_base_path = target.manifest_dir.to_string_lossy().into_owned();
366                if self.build.exec_path.is_empty() {
367                    self.build.exec_file = target.bin.clone();
368                }
369
370                validate_shell_arg_safe(
371                    &self.build.exec_file,
372                    &format!(
373                        "executable name derived from --entry_point_path {}:",
374                        go_quote(&orig)
375                    ),
376                )?;
377                // The package name reaches the RUN line's `-p`.
378                validate_shell_arg_safe(
379                    &target.package,
380                    &format!(
381                        "package name derived from --entry_point_path {}:",
382                        go_quote(&orig)
383                    ),
384                )?;
385                validate_shell_arg_safe(&orig, "--entry_point_path")?;
386
387                // The archive root is `-d` or else the Cargo workspace
388                // root, and must contain the workspace root,
389                // whose path below it becomes the builder's WORKDIR.
390                let archive_root = if self.source.source_dir.is_empty() {
391                    target.workspace_root.clone()
392                } else {
393                    env.abs(&self.source.source_dir)
394                };
395                let Some(workdir) = relative_to(&target.workspace_root, &archive_root) else {
396                    return Err(format!(
397                        "--source_dir {} is neither the Cargo workspace root {} nor an ancestor of it",
398                        go_quote(&self.source.source_dir),
399                        go_quote(&target.workspace_root.to_string_lossy())
400                    ));
401                };
402                validate_shell_arg_safe(workdir.as_os_str().as_encoded_bytes(), "--source_dir")?;
403                check_path_dependencies(&target, &archive_root)?;
404                self.source.source_dir = archive_root.to_string_lossy().into_owned();
405                self.target = Some(target);
406
407                if self.build.temp_dir.is_empty() {
408                    self.build.temp_dir = env.temp_dir().to_string_lossy().into_owned();
409                }
410                let absp = env.abs(&self.build.temp_dir);
411                // The wrapped error is Rust's `io::Error` text.
412                let dir = make_temp(&absp, "agentEngine_", env.time.now()).map_err(|e| {
413                    format!(
414                        "cannot create a temporary sub directory in '{}': {e}",
415                        absp.display()
416                    )
417                })?;
418                self.build.temp_dir = dir.to_string_lossy().into_owned();
419                p.print(&[&"Using temp dir:", &self.build.temp_dir]);
420
421                if self.build.exec_path.is_empty() {
422                    self.build.exec_path = go_path_join(&[&self.build.temp_dir, &self.build.exec_file]);
423                }
424                self.build.dockerfile_build_path =
425                    go_path_join(&[self.build.temp_dir.as_str(), "Dockerfile"]);
426                self.build.archive_path = go_path_join(&[self.build.temp_dir.as_str(), "archive.tgz"]);
427
428                let date_time = env
429                    .time
430                    .now()
431                    .with_timezone(&Local)
432                    .to_rfc3339_opts(SecondsFormat::Secs, true);
433                self.agent_engine.display_name = self.agent_engine.name.clone();
434                if self.agent_engine.display_name.is_empty() {
435                    self.agent_engine.display_name = format!("ADK Agent: {date_time}");
436                }
437
438                // prefix an explicit model with the project and region
439                if !self.agent_engine.memory_bank.model.is_empty() {
440                    self.agent_engine.memory_bank.model = format!(
441                        "projects/{}/locations/{}/{}",
442                        self.gcloud.project_name,
443                        self.gcloud.region,
444                        self.agent_engine.memory_bank.model
445                    );
446                }
447                Ok(())
448            },
449        )
450        .await
451    }
452
453    /// Removes the temp dir.
454    pub async fn clean_temp(&self, env: &Env) -> Result<(), String> {
455        log_start_stop(&env.out, "Cleaning temp", async |p: Printer| {
456            p.print(&[&"Clean temp starting with", &self.build.temp_dir]);
457            // The wrapped error is Rust's `io::Error` text.
458            match fs::remove_dir_all(&self.build.temp_dir) {
459                // A missing path is not an error.
460                Err(e) if e.kind() != ErrorKind::NotFound => Err(format!(
461                    "failed to clean temp directory {}: {e}",
462                    self.build.temp_dir
463                )),
464                _ => Ok(()),
465            }
466        })
467        .await
468    }
469
470    /// The directory archived: `source_dir` (absolute
471    /// after [`compute_flags`](Self::compute_flags)), else the target's workspace root.
472    fn archive_root(&self) -> PathBuf {
473        if self.source.source_dir.is_empty() {
474            self.target
475                .as_ref()
476                .map(|t| t.workspace_root.clone())
477                .unwrap_or_default()
478        } else {
479            PathBuf::from(&self.source.source_dir)
480        }
481    }
482
483    /// Prepares the Dockerfile: reads only the receiver (the builder version from the
484    /// target's workspace, `WORKDIR /app/<workspace root below the archive root>`, `-p
485    /// <package> --bin <exec_file>`, `EXPOSE`/`CMD` from `server_port`), written with mode 0600.
486    pub async fn prepare_dockerfile(&self, env: &Env) -> Result<(), String> {
487        log_start_stop(&env.out, "Preparing Dockerfile", async |p: Printer| {
488            p.print(&[&"Writing:", &self.build.dockerfile_build_path]);
489            let target = self.target.clone().unwrap_or_default();
490            let workdir = relative_to(&target.workspace_root, &self.archive_root())
491                .map(|w| w.to_string_lossy().into_owned())
492                .unwrap_or_default();
493            let builder = BuilderStage {
494                image: builder_image(&builder_rust_version(&target, COMPILED_RUSTC_VERSION)),
495                workdir,
496                package: target.package,
497                bin: self.build.exec_file.clone(),
498            };
499            let text = dockerfile(
500                &builder,
501                self.agent_engine.server_port,
502                r#", "agentengine""#,
503            );
504            // The error is Rust's `io::Error` text.
505            OpenOptions::new()
506                .write(true)
507                .create(true)
508                .truncate(true)
509                .mode(0o600)
510                .open(&self.build.dockerfile_build_path)
511                .and_then(|mut f| f.write_all(text.as_bytes()))
512                .map_err(|e| e.to_string())
513        })
514        .await
515    }
516
517    /// Creates the archive: the sorted tar.gz of the archive root (without `.git`,
518    /// `target`, a nested temp dir and the root `Dockerfile`) with the generated `Dockerfile`
519    /// last.
520    // The archive is written in-process (no `Running :` line, gadk's error texts) and leaves
521    // out a root `Dockerfile` of the source, so only the generated one is archived.
522    pub async fn create_archive(&self, env: &Env) -> Result<(), String> {
523        log_start_stop(&env.out, "Creating source archive", async |p: Printer| {
524            let root = self.archive_root();
525            p.print(&[&"Creating:", &self.build.archive_path]);
526            let mut exclude = vec![root.join("Dockerfile")];
527            if let Some(rel) = relative_to(Path::new(&self.build.temp_dir), &root)
528                && !rel.as_os_str().is_empty()
529            {
530                exclude.push(root.join(rel));
531            }
532            let tree = SourceTree::walk(&root, &exclude).map_err(|e| {
533                format!(
534                    "cannot read the source directory {}: {e}",
535                    go_quote(&root.to_string_lossy())
536                )
537            })?;
538            let generated = fs::read(&self.build.dockerfile_build_path)
539                .map_err(|e| format!("cannot read the generated Dockerfile: {e}"))?;
540            tree.write_tar_gz(
541                Path::new(&self.build.archive_path),
542                &[("Dockerfile", generated.as_slice())],
543            )
544            .map_err(|e| {
545                format!(
546                    "cannot write the source archive {}: {e}",
547                    go_quote(&self.build.archive_path)
548                )
549            })
550        })
551        .await
552    }
553
554    /// The memory bank context spec as a `ReasoningEngineContextSpec` in JSON form:
555    /// `memoryBankConfig.ttlConfig.defaultTtl` = `--mem_ttl`, and
556    /// `memoryBankConfig.generationConfig.model` only for a non-empty `--mem_model`.
557    pub fn memory_bank_context_spec(&self) -> Value {
558        let mb = &self.agent_engine.memory_bank;
559        let mut cfg = json!({"ttlConfig": {"defaultTtl": protojson_duration(mb.ttl)}});
560        if !mb.model.is_empty() {
561            cfg["generationConfig"] = json!({"model": mb.model});
562        }
563        json!({"memoryBankConfig": cfg})
564    }
565
566    /// Builds the Reasoning Engine client for the region's Vertex AI endpoint
567    /// with [`Env::vertex`]; ADC reads [`Env::env`] unless the options name an environment.
568    fn client(&self, env: &Env) -> Result<ReasoningEngineClient, String> {
569        let mut opts: ReasoningEngineOptions = env.vertex.clone();
570        if opts.env.is_none() {
571            opts.env = Some(env.env.clone());
572        }
573        ReasoningEngineClient::new(&self.gcloud.region, opts)
574            .map_err(|e| format!("cannot create ReasoningEngineClient: {e}"))
575    }
576
577    /// The parts of the create and update requests read from disk and the server package:
578    /// the `sourceCodeSpec` (inline archive, empty `imageSpec`) and the class methods,
579    /// printing `Methods: <json>`.
580    fn source_code_spec_and_methods(&self, p: &Printer) -> Result<(Value, Value), String> {
581        // The wrapped error is Rust's `io::Error` text.
582        let archive = fs::read(&self.build.archive_path)
583            .map_err(|e| format!("cannot read archive file: {e}"))?;
584        let methods = gadk_server::agentengine::list_class_methods();
585        let methods_json =
586            gadk_model::to_go_json(&methods).map_err(|e| format!("cannot marshal methods: {e}"))?;
587        p.print(&[&"Methods:", &String::from_utf8_lossy(&methods_json)]);
588        let source_code_spec = json!({
589            "inlineSource": {"sourceArchive": STANDARD.encode(&archive)},
590            "imageSpec": {},
591        });
592        Ok((source_code_spec, Value::from(methods)))
593    }
594
595    /// Creates the Reasoning Engine: `CreateReasoningEngine` under
596    /// `projects/<p>/locations/<r>`, then the operation awaited for at most 45 minutes.
597    pub async fn deploy_to_agent_engine(&self, env: &Env) -> Result<(), String> {
598        log_start_stop(&env.out, "Deploying to Agent Engine", async |p: Printer| {
599            let parent = format!(
600                "projects/{}/locations/{}",
601                self.gcloud.project_name, self.gcloud.region
602            );
603            let client = self.client(env)?;
604            let (source_code_spec, methods) = self.source_code_spec_and_methods(&p)?;
605            let mut engine = json!({
606                "displayName": self.agent_engine.display_name,
607                "spec": {
608                    "sourceCodeSpec": source_code_spec,
609                    "agentFramework": "google-adk",
610                    "deploymentSpec": deployment_spec(&self.agent_engine.env_vars),
611                    "classMethods": methods,
612                },
613            });
614            if self.agent_engine.memory_bank.deploy {
615                engine["contextSpec"] = self.memory_bank_context_spec();
616            }
617
618            p.print(&[&"Sending CreateReasoningEngine request..."]);
619            let op = client
620                .create(&parent, engine)
621                .await
622                .map_err(|e| format!("CreateReasoningEngine failed: {e}"))?;
623
624            p.print(&[&"Waiting for operation to complete..."]);
625            let re = wait_for_operation(&client, op).await?;
626
627            p.print(&[&"Deployed Reasoning Engine:", &str_field(&re, "name")]);
628            p.print(&[&"Display Name:", &str_field(&re, "displayName")]);
629            Ok(())
630        })
631        .await
632    }
633
634    /// Updates the Reasoning Engine: `UpdateReasoningEngine` of
635    /// `projects/<p>/locations/<r>/reasoningEngines/<id>` with the update mask in JSON
636    /// form (the environment only when [`AgentEngineServiceFlags::update_env`], before the
637    /// memory bank's `spec.contextSpec`), then the operation awaited for at most 45 minutes.
638    pub async fn update_agent_engine(&self, env: &Env) -> Result<(), String> {
639        log_start_stop(&env.out, "Updating Agent Engine", async |p: Printer| {
640            let name = format!(
641                "projects/{}/locations/{}/reasoningEngines/{}",
642                self.gcloud.project_name, self.gcloud.region, self.agent_engine.agent_engine_id
643            );
644            let client = self.client(env)?;
645            let (source_code_spec, methods) = self.source_code_spec_and_methods(&p)?;
646            let mut engine = json!({
647                "name": name,
648                "spec": {
649                    "sourceCodeSpec": source_code_spec,
650                    "classMethods": methods,
651                },
652            });
653            let mut mask = vec!["spec.sourceCodeSpec", "spec.classMethods"];
654            if self.agent_engine.update_env {
655                engine["spec"]["deploymentSpec"] = deployment_spec(&self.agent_engine.env_vars);
656                mask.push("spec.deploymentSpec.env");
657            }
658            if self.agent_engine.memory_bank.deploy {
659                engine["contextSpec"] = self.memory_bank_context_spec();
660                // The mask path `spec.context_spec` is kept (in JSON form) although `contextSpec`
661                // is a top-level ReasoningEngine field.
662                mask.push("spec.contextSpec");
663            }
664
665            p.print(&[&"Sending UpdateReasoningEngine request..."]);
666            let op = client
667                .update(engine, &mask)
668                .await
669                .map_err(|e| format!("UpdateReasoningEngine failed: {e}"))?;
670
671            p.print(&[&"Waiting for operation to complete..."]);
672            let re = wait_for_operation(&client, op).await?;
673
674            p.print(&[&"Updated Reasoning Engine:", &str_field(&re, "name")]);
675            p.print(&[&"Display Name:", &str_field(&re, "displayName")]);
676            Ok(())
677        })
678        .await
679    }
680
681    /// Deploys: compute → Dockerfile → archive → update|deploy → clean,
682    /// stopping at the first error (the temp dir is kept).
683    pub async fn deploy_on_agent_engine(&mut self, env: &Env) -> Result<(), String> {
684        self.compute_flags(env).await?;
685        self.prepare_dockerfile(env).await?;
686        self.create_archive(env).await?;
687        if !self.agent_engine.agent_engine_id.is_empty() {
688            self.update_agent_engine(env).await?;
689        } else {
690            self.deploy_to_agent_engine(env).await?;
691        }
692        self.clean_temp(env).await
693    }
694}