-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathcreate.py
More file actions
1454 lines (1290 loc) · 56.9 KB
/
create.py
File metadata and controls
1454 lines (1290 loc) · 56.9 KB
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2025 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.
import datetime
import logging
import os
import pathlib
import shutil
import subprocess
import tempfile
from collections.abc import Callable
import click
from click.core import ParameterSource
from rich.console import Console
from rich.prompt import IntPrompt, Prompt
from ..utils.command import run_gcloud_command
from ..utils.datastores import DATASTORE_TYPES, DATASTORES
from ..utils.gcp import verify_credentials_and_vertex
from ..utils.logging import display_welcome_banner, handle_cli_error
from ..utils.remote_template import (
fetch_remote_template,
get_base_template_name,
load_remote_template_config,
merge_template_configs,
parse_agent_spec,
)
from ..utils.template import (
add_base_template_dependencies_interactively,
get_agent_language,
get_available_agents,
get_deployment_targets,
get_template_path,
load_template_config,
process_template,
prompt_cicd_runner_selection,
prompt_datastore_selection,
prompt_deployment_target,
prompt_session_type_selection,
resolve_agent_alias,
)
console = Console()
# Export the shared decorator for use by other commands
__all__ = ["create", "shared_template_options"]
def shared_template_options(f: Callable) -> Callable:
"""Decorator to add shared options for template-based commands."""
# Apply options in reverse order since decorators are applied bottom-up
f = click.option(
"-k",
"--google-api-key",
"--api-key",
is_flag=False,
flag_value="YOUR_API_KEY",
default=None,
help="Use Google AI Studio API key instead of Vertex AI. If provided without a value, generates a .env file with a placeholder.",
)(f)
f = click.option(
"-ag",
"--agent-garden",
is_flag=True,
help="Deployed from Agent Garden - customizes welcome messages",
default=False,
)(f)
f = click.option(
"--skip-deps",
is_flag=True,
help="Skip base template dependency installation (used when reusing saved config)",
default=False,
hidden=True,
)(f)
f = click.option(
"-s",
"--skip-checks",
is_flag=True,
help="Skip verification checks for GCP and Vertex AI",
default=False,
)(f)
f = click.option(
"--region",
help="GCP region for deployment (default: us-central1)",
default="us-central1",
)(f)
f = click.option(
"--auto-approve",
"--yes",
"-y",
is_flag=True,
help="Skip credential confirmation prompts",
)(f)
f = click.option("--debug", is_flag=True, help="Enable debug logging")(f)
f = click.option(
"--session-type",
type=click.Choice(["in_memory", "cloud_sql", "agent_engine"]),
help="Type of session storage to use",
)(f)
f = click.option(
"--datastore",
"-ds",
type=click.Choice(DATASTORE_TYPES),
help="Type of datastore to use for data ingestion (requires --include-data-ingestion)",
)(f)
f = click.option(
"--include-data-ingestion",
"-i",
is_flag=True,
help="Include data ingestion pipeline in the project",
)(f)
f = click.option(
"--prototype",
"-p",
is_flag=True,
help="Create minimal project without CI/CD or Terraform infrastructure",
default=False,
)(f)
f = click.option(
"--cicd-runner",
type=click.Choice(["google_cloud_build", "github_actions", "skip"]),
help="CI/CD runner to use",
)(f)
f = click.option(
"--deployment-target",
"-d",
type=click.Choice(["agent_engine", "cloud_run"]),
help="Deployment target name",
)(f)
f = click.option(
"--agent-directory",
"-dir",
help="Name of the agent directory (overrides template default)",
)(f)
f = click.option(
"--base-template",
"-bt",
help="Base template to use (overrides template default, only for remote templates)",
)(f)
return f
def get_available_base_templates() -> list[str]:
"""Get list of available base templates for inheritance.
Returns:
List of base template names.
"""
agents = get_available_agents()
return sorted([agent_info["name"] for agent_info in agents.values()])
def validate_base_template(base_template: str) -> bool:
"""Validate that a base template exists.
Args:
base_template: Name of the base template to validate
Returns:
True if the base template exists, False otherwise
"""
available_templates = get_available_base_templates()
return base_template in available_templates
def get_standard_ignore_patterns() -> Callable[[str, list[str]], list[str]]:
"""Get standard ignore patterns for copying directories.
Returns:
A callable that can be used with shutil.copytree's ignore parameter.
"""
exclude_dirs = {
".git",
".venv",
"venv",
"__pycache__",
".pytest_cache",
"node_modules",
".next",
"dist",
"build",
".DS_Store",
".vscode",
".idea",
"*.egg-info",
".mypy_cache",
".ty",
".coverage",
"htmlcov",
".tox",
".cache",
}
def ignore_patterns(dir: str, files: list[str]) -> list[str]:
return [f for f in files if f in exclude_dirs or f.startswith(".backup_")]
return ignore_patterns
def normalize_project_name(project_name: str) -> str:
"""Normalize project name for better compatibility with cloud resources and tools."""
needs_normalization = (
any(char.isupper() for char in project_name) or "_" in project_name
)
if needs_normalization:
normalized_name = project_name
console.print(
"Note: Project names are normalized (lowercase, hyphens only) for better compatibility with cloud resources and tools.",
style="dim",
)
if any(char.isupper() for char in normalized_name):
normalized_name = normalized_name.lower()
console.print(
f"Info: Converting to lowercase for compatibility: '{project_name}' -> '{normalized_name}'",
style="bold yellow",
)
if "_" in normalized_name:
# Capture the name state before this specific change
name_before_hyphenation = normalized_name
normalized_name = normalized_name.replace("_", "-")
console.print(
f"Info: Replacing underscores with hyphens for compatibility: '{name_before_hyphenation}' -> '{normalized_name}'",
style="yellow",
)
return normalized_name
return project_name
@click.command()
@click.pass_context
@click.argument("project_name", required=False, default=None)
@click.option(
"--agent",
"-a",
help="Template identifier to use. Can be a local agent name (e.g., `chat_agent`), a local path (`local@/path/to/template`), an `adk-samples` shortcut (e.g., `adk@data-science`), or a remote Git URL. Both shorthand (e.g., `github.com/org/repo/path@main`) and full URLs from your browser (e.g., `https://github.com/org/repo/tree/main/path`) are supported. Lists available local templates if omitted.",
)
@click.option(
"--output-dir",
"-o",
type=click.Path(),
help="Output directory for the project (default: current directory)",
)
@click.option(
"--in-folder",
"-if",
is_flag=True,
help="Template files directly into the current directory instead of creating a new project directory",
default=False,
)
@click.option(
"--skip-welcome",
is_flag=True,
hidden=True,
help="Skip the welcome banner",
default=False,
)
@click.option(
"--locked",
is_flag=True,
hidden=True,
help="Internal flag for version-locked remote templates",
default=False,
)
@shared_template_options
@click.option(
"--adk",
is_flag=True,
help="Quickstart mode: adk + agent_engine + prototype, skips prompts",
default=False,
)
@handle_cli_error
def create(
ctx: click.Context,
project_name: str,
agent: str | None,
deployment_target: str | None,
cicd_runner: str | None,
adk: bool,
prototype: bool,
include_data_ingestion: bool,
datastore: str | None,
session_type: str | None,
debug: bool,
output_dir: str | None,
auto_approve: bool,
region: str,
skip_checks: bool,
skip_deps: bool,
in_folder: bool,
agent_directory: str | None,
agent_garden: bool = False,
base_template: str | None = None,
skip_welcome: bool = False,
locked: bool = False,
cli_overrides: dict | None = None,
google_api_key: str | None = None,
) -> None:
"""Create GCP-based AI agent projects from templates."""
try:
console = Console()
# Display welcome banner (unless skipped)
if not skip_welcome:
display_welcome_banner(agent, agent_garden=agent_garden)
# Handle missing project name
if not project_name:
if auto_approve:
project_name = "my-agent"
console.print(
f"Info: Project name not specified. Defaulting to '{project_name}' in auto-approve mode.",
style="yellow",
)
else:
# Convert output_dir to Path for directory existence check
check_dir = (
pathlib.Path(output_dir) if output_dir else pathlib.Path.cwd()
).resolve()
while True:
project_name = Prompt.ask(
"\n> Enter a name for your project",
default="my-agent",
show_default=True,
)
if len(project_name) > 26:
console.print(
f"Error: Project name '{project_name}' exceeds 26 characters. Please use a shorter name.",
style="bold red",
)
continue
# Check if directory already exists
normalized_name = normalize_project_name(project_name)
if (check_dir / normalized_name).exists():
console.print(
f"Error: Project directory '{check_dir / normalized_name}' already exists. Please choose a different name.",
style="bold red",
)
continue
break
# Validate project name (for CLI-provided names)
if len(project_name) > 26:
console.print(
f"Error: Project name '{project_name}' exceeds 26 characters. Please use a shorter name.",
style="bold red",
)
return
project_name = normalize_project_name(project_name)
# Setup debug logging if enabled
if debug:
logging.basicConfig(level=logging.DEBUG)
console.print("> Debug mode enabled")
logging.debug("Starting CLI in debug mode")
# Handle --adk quickstart flag
if adk:
console.print(
"⚡ ADK quickstart: adk + Agent Engine + prototype mode\n",
style="cyan",
)
if agent and agent != "adk":
console.print(
f"Info: --agent '{agent}' ignored due to --adk flag (using adk).",
style="yellow",
)
agent = "adk"
if deployment_target and deployment_target != "agent_engine":
console.print(
f"Info: --deployment-target '{deployment_target}' ignored due to --adk flag (using agent_engine).",
style="yellow",
)
deployment_target = "agent_engine"
# Enable prototype mode and auto-approve
prototype = True
auto_approve = True
if debug:
logging.debug(
"ADK quickstart mode: agent=adk, deployment_target=agent_engine, prototype=True, auto_approve=True"
)
# Convert output_dir to Path if provided, otherwise use current directory
destination_dir = pathlib.Path(output_dir) if output_dir else pathlib.Path.cwd()
destination_dir = destination_dir.resolve() # Convert to absolute path
if in_folder:
# For in-folder templating, use the current directory directly
project_path = destination_dir
# In-folder mode is permissive - we assume the user wants to enhance their existing repo
# Create backup of entire directory before in-folder templating
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
backup_dir = project_path / f".backup_{project_path.name}_{timestamp}"
console.print("📦 [blue]Creating backup before modification...[/blue]")
try:
shutil.copytree(
project_path, backup_dir, ignore=get_standard_ignore_patterns()
)
console.print(f"Backup created: [cyan]{backup_dir.name}[/cyan]")
except Exception as e:
console.print(
f"⚠️ [yellow]Warning: Could not create backup: {e}[/yellow]"
)
if not auto_approve:
if not click.confirm("Continue without backup?", default=True):
console.print("✋ [red]Operation cancelled.[/red]")
return
console.print()
else:
# Check if project would exist in output directory
project_path = destination_dir / project_name
if project_path.exists():
console.print(
f"Error: Project directory '{project_path}' already exists",
style="bold red",
)
return
# Resolve agent name aliases (backwards compatibility)
agent = resolve_agent_alias(agent)
# Agent selection - handle remote templates
selected_agent = None
template_source_path = None
temp_dir_to_clean = None
remote_spec = None
if agent:
if agent.startswith("local@"):
path_str = agent.split("@", 1)[1]
local_path = pathlib.Path(path_str).resolve()
if not local_path.is_dir():
raise click.ClickException(
f"Local path not found or not a directory: {local_path}"
)
# Create a temporary directory and copy the local template to it
temp_dir = tempfile.mkdtemp(prefix="asp_local_template_")
temp_dir_to_clean = temp_dir
template_source_path = pathlib.Path(temp_dir) / local_path.name
shutil.copytree(
local_path,
template_source_path,
ignore=get_standard_ignore_patterns(),
)
# Check for version lock and execute nested command if found
from ..utils.remote_template import check_and_execute_with_version_lock
if check_and_execute_with_version_lock(
template_source_path, agent, locked, project_name
):
# If we executed with locked version, cleanup and exit
shutil.rmtree(temp_dir, ignore_errors=True)
return
selected_agent = f"local_{template_source_path.name}"
if locked:
# In locked mode, show a nicer message
console.print("✅ Using version-locked template", style="green")
else:
console.print(f"Using local template: {local_path}")
logging.debug(
f"Copied local template to temporary dir: {template_source_path}"
)
else:
# Check if it's a remote template specification
remote_spec = parse_agent_spec(agent)
if remote_spec:
if remote_spec.is_adk_samples:
console.print(
f"> Fetching template: {remote_spec.template_path}",
style="bold blue",
)
else:
console.print(f"Fetching remote template: {agent}")
template_source_path, temp_dir_path = fetch_remote_template(
remote_spec, agent, locked, project_name
)
temp_dir_to_clean = str(temp_dir_path)
selected_agent = f"remote_{hash(agent)}" # Generate unique name for remote template
# Show informational message for ADK samples with smart defaults
if remote_spec.is_adk_samples:
config = load_remote_template_config(
template_source_path, is_adk_sample=True
)
if not config.get("has_explicit_config", True):
console = Console()
console.print(
"\n[blue]ℹ️ Note: The starter pack uses heuristics to template this ADK sample agent.[/]"
)
console.print(
"[dim] The starter pack attempts to create a working codebase, but you'll need to follow the generated README for complete setup.[/]"
)
else:
# Handle local agent selection
agents = get_available_agents()
# First check if it's a valid agent name
if any(p["name"] == agent for p in agents.values()):
selected_agent = agent
else:
# Try numeric agent selection if input is a number
try:
agent_num = int(agent)
if agent_num in agents:
selected_agent = agents[agent_num]["name"]
else:
raise ValueError(f"Invalid agent number: {agent_num}")
except ValueError as err:
raise ValueError(
f"Invalid agent name or number: {agent}"
) from err
# Agent selection
final_agent = selected_agent
if not final_agent:
if auto_approve:
# Default to first available agent in auto-approve mode
agents = get_available_agents(deployment_target=deployment_target)
if not agents:
raise click.ClickException(
"Error: No agents available for the selected deployment target."
)
final_agent = next(iter(agents.values()))["name"]
console.print(
f"Info: --agent not specified. Defaulting to '{final_agent}' in auto-approve mode.",
style="yellow",
)
else:
final_agent = display_agent_selection(deployment_target)
# If browse functionality returned a remote agent spec, process it like CLI input
if final_agent and final_agent.startswith("adk@"):
# Set agent to the returned spec for remote processing
agent = final_agent
# Process the remote template spec just like CLI input
remote_spec = parse_agent_spec(agent)
if remote_spec:
if remote_spec.is_adk_samples:
console.print(
f"> Fetching template: {remote_spec.template_path}",
style="bold blue",
)
else:
console.print(f"Fetching remote template: {agent}")
template_source_path, temp_dir_path = fetch_remote_template(
remote_spec, agent, locked, project_name
)
temp_dir_to_clean = str(temp_dir_path)
final_agent = f"remote_{hash(agent)}" # Generate unique name for remote template
# Show informational message for ADK samples with smart defaults
if remote_spec.is_adk_samples:
config = load_remote_template_config(
template_source_path, is_adk_sample=True
)
if not config.get("has_explicit_config", True):
console = Console()
console.print(
"\n[blue]ℹ️ Note: The starter pack uses heuristics to template this ADK sample agent.[/]"
)
console.print(
"[dim] The starter pack attempts to create a working codebase, but you'll need to follow the generated README for complete setup.[/]"
)
if debug:
logging.debug(f"Selected agent: {final_agent}")
# Load template configuration based on whether it's remote or local
# Track original base template to detect actual overrides (not just selection)
original_base_template: str | None = None
if template_source_path:
# Prepare CLI overrides for remote template config
# Initialize cli_overrides if not provided (e.g., from enhance command)
if cli_overrides is None:
cli_overrides = {}
# First, get the original base template BEFORE applying cli_overrides
# This allows us to detect if user is actually overriding vs selecting same
original_config = load_remote_template_config(
template_source_path,
None, # No CLI overrides to get original value
is_adk_sample=remote_spec.is_adk_samples if remote_spec else False,
)
original_base_template = get_base_template_name(original_config)
if base_template:
# Validate that the base template exists
if not validate_base_template(base_template):
available_templates = get_available_base_templates()
console.print(
f"Error: Base template '{base_template}' not found.",
style="bold red",
)
console.print(
f"Available base templates: {', '.join(available_templates)}",
style="yellow",
)
raise click.Abort()
cli_overrides["base_template"] = base_template
# Load remote template config with CLI overrides
source_config = load_remote_template_config(
template_source_path,
cli_overrides,
is_adk_sample=remote_spec.is_adk_samples if remote_spec else False,
)
# Remote templates now work even without pyproject.toml thanks to defaults
if debug and source_config:
logging.debug(f"Final remote template config: {source_config}")
# Load base template config for inheritance
base_template_name = get_base_template_name(source_config)
if debug:
logging.debug(f"Using base template: {base_template_name}")
base_template_path = (
pathlib.Path(__file__).parent.parent.parent
/ "agents"
/ base_template_name
/ ".template"
)
base_config = load_template_config(base_template_path)
# Merge configs: remote inherits from and overrides base
config = merge_template_configs(base_config, source_config)
# For remote templates, use the template/ subdirectory as the template source
template_path = template_source_path / ".template"
else:
template_path = (
pathlib.Path(__file__).parent.parent.parent
/ "agents"
/ final_agent
/ ".template"
)
config = load_template_config(template_path)
# Apply CLI overrides for local templates if provided (e.g., from enhance command)
if cli_overrides:
config = merge_template_configs(config, cli_overrides)
if debug:
logging.debug(
f"Applied CLI overrides to local template config: {cli_overrides}"
)
# Data ingestion and datastore selection
# Check language early for data ingestion validation
early_agent_language = get_agent_language(final_agent)
# Go agents don't support data ingestion
if early_agent_language == "go":
if include_data_ingestion or datastore:
console.print(
"Warning: Go agents do not support data ingestion. "
"Ignoring --include-data-ingestion and --datastore flags.",
style="yellow",
)
include_data_ingestion = False
datastore = None
elif include_data_ingestion or datastore:
include_data_ingestion = True
if not datastore:
if auto_approve:
# Default to the first available datastore in non-interactive mode
datastore = next(iter(DATASTORES.keys()))
console.print(
f"Info: --datastore not specified. Defaulting to '{datastore}' in auto-approve mode.",
style="yellow",
)
else:
datastore = prompt_datastore_selection(
final_agent, from_cli_flag=True
)
if debug:
logging.debug(f"Data ingestion enabled: {include_data_ingestion}")
logging.debug(f"Selected datastore type: {datastore}")
else:
# Check if the agent requires data ingestion
if config and config.get("settings", {}).get("requires_data_ingestion"):
include_data_ingestion = True
if not datastore:
if auto_approve:
datastore = next(iter(DATASTORES.keys()))
console.print(
f"Info: --datastore not specified. Defaulting to '{datastore}' in auto-approve mode.",
style="yellow",
)
else:
datastore = prompt_datastore_selection(final_agent)
if debug:
logging.debug(
f"Data ingestion required by agent: {include_data_ingestion}"
)
logging.debug(f"Selected datastore type: {datastore}")
# Deployment target selection
# For remote templates, we need to use the base template name for deployment target selection
deployment_agent_name = final_agent
remote_config = None
if template_source_path:
# Use the base template name from remote config for deployment target selection
deployment_agent_name = get_base_template_name(config)
remote_config = config
final_deployment = deployment_target
if not final_deployment:
available_targets = get_deployment_targets(
deployment_agent_name, remote_config=remote_config
)
if not available_targets:
raise click.ClickException(
f"Error: No deployment targets available for agent '{deployment_agent_name}'."
)
# Auto-select if only one target available or in auto-approve mode
if len(available_targets) == 1:
final_deployment = available_targets[0]
console.print(
f"Info: Using '{final_deployment}' (only available deployment target for this agent).",
style="yellow",
)
elif auto_approve:
final_deployment = available_targets[0]
console.print(
f"Info: --deployment-target not specified. Defaulting to '{final_deployment}' in auto-approve mode.",
style="yellow",
)
else:
final_deployment = prompt_deployment_target(
deployment_agent_name, remote_config=remote_config
)
if debug:
logging.debug(f"Selected deployment target: {final_deployment}")
# Session type validation and selection (only for agents that require session management)
final_session_type = session_type
# Get agent language for language-specific validation
agent_language = get_agent_language(deployment_agent_name, remote_config)
# Go agents only support in-memory sessions
if agent_language == "go":
final_session_type = "in_memory"
if session_type and session_type != "in_memory":
console.print(
"Warning: Go agents only support in-memory sessions. "
"Using in-memory sessions for this agent.",
style="yellow",
)
else:
# Python agents - check if session management is required
requires_session = config.get("settings", {}).get("requires_session", False)
# Session type selection is only available for these agents on cloud_run
session_type_supported_agents = ("adk", "agentic_rag")
if requires_session:
if final_deployment == "agent_engine" and session_type:
console.print(
"Error: --session-type cannot be used with agent_engine deployment target. "
"Agent Engine handles session management internally.",
style="bold red",
)
return
if final_deployment == "cloud_run":
if deployment_agent_name in session_type_supported_agents:
# Allow session type selection for supported agents
if not session_type:
if auto_approve:
final_session_type = "in_memory"
console.print(
"Info: --session-type not specified. Defaulting to 'in_memory' in auto-approve mode.",
style="yellow",
)
else:
final_session_type = prompt_session_type_selection()
else:
# For unsupported agents, always use in_memory
final_session_type = "in_memory"
if session_type and session_type != "in_memory":
console.print(
f"Warning: Session type selection is only available for {', '.join(session_type_supported_agents)} agents. "
"Using in-memory sessions for this agent.",
style="yellow",
)
else:
# Agents that don't require session management always use in-memory sessions
final_session_type = "in_memory"
if session_type and session_type != "in_memory":
console.print(
"Warning: Session type options are only available for agents that require session management. "
"Using in-memory sessions for this agent.",
style="yellow",
)
if debug and final_session_type:
logging.debug(f"Selected session type: {final_session_type}")
# CI/CD runner selection
# --prototype flag or agent_garden mode defaults to "skip" (minimal project)
if prototype or agent_garden:
if cicd_runner and cicd_runner != "skip":
console.print(
f"Info: --cicd-runner '{cicd_runner}' ignored due to {'--prototype' if prototype else '--agent-garden'} flag.",
style="yellow",
)
final_cicd_runner = "skip"
if debug:
logging.debug("Prototype mode: setting cicd_runner to 'skip'")
elif cicd_runner:
final_cicd_runner = cicd_runner
elif auto_approve:
final_cicd_runner = "skip"
console.print(
"Info: --cicd-runner not specified. Defaulting to 'skip' (simple mode) in auto-approve mode.",
style="yellow",
)
else:
final_cicd_runner = prompt_cicd_runner_selection()
if debug:
logging.debug(f"Selected CI/CD runner: {final_cicd_runner}")
# Region confirmation (if not explicitly passed)
if (
not auto_approve
and ctx.get_parameter_source("region") != ParameterSource.COMMANDLINE
):
# Show Agent Engine supported regions link if agent_garden flag is set
if agent_garden:
console.print(
"\n📍 [blue]Agent Engine Supported Regions:[/blue]\n"
" [cyan]https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/overview#supported-regions[/cyan]"
)
region = prompt_region_confirmation(region, agent_garden=agent_garden)
if debug:
logging.debug(f"Selected region: {region}")
# GCP Setup
logging.debug("Setting up GCP...")
creds_info = {}
if not skip_checks and not google_api_key:
# Set up GCP environment
try:
creds_info = setup_gcp_environment(
auto_approve=auto_approve,
skip_checks=skip_checks,
region=region,
debug=debug,
agent_garden=agent_garden,
)
except Exception as e:
if debug:
logging.warning(f"GCP environment setup failed: {e}")
console.print(f"> ⚠️ {e}", style="bold yellow")
console.print(
"> Continuing with template processing...", style="yellow"
)
elif skip_checks and not google_api_key and final_agent.endswith("_go"):
# For Go templates, try to get project ID from gcloud config even when skipping checks
# This is needed because Go's .env requires a valid project ID for local development
try:
result = subprocess.run(
["gcloud", "config", "get-value", "project"],
capture_output=True,
text=True,
check=False,
)
project_id = result.stdout.strip()
if project_id:
creds_info = {"project": project_id}
logging.debug(f"Got project ID from gcloud config: {project_id}")
except Exception as e:
logging.debug(f"Could not get project ID from gcloud: {e}")
# Process template
if not template_source_path:
template_path = get_template_path(final_agent, debug=debug)
# template_path is already set above for remote templates
if debug:
logging.debug(f"Template path: {template_path}")
logging.debug(f"Processing template for project: {project_name}")
# Create output directory if it doesn't exist
if not destination_dir.exists():
destination_dir.mkdir(parents=True)
if debug:
logging.debug(f"Output directory: {destination_dir}")
# Construct CLI overrides for template processing
final_cli_overrides = cli_overrides or {}
if agent_directory:
if "settings" not in final_cli_overrides:
final_cli_overrides["settings"] = {}
final_cli_overrides["settings"]["agent_directory"] = agent_directory
try:
# Process template (handles both local and remote templates)
process_template(
agent_name=final_agent,
template_dir=template_path,
project_name=project_name,
deployment_target=final_deployment,
cicd_runner=final_cicd_runner,
include_data_ingestion=include_data_ingestion,
datastore=datastore,
session_type=final_session_type,
output_dir=destination_dir,
remote_template_path=template_source_path,
remote_config=config,
in_folder=in_folder,
cli_overrides=final_cli_overrides,
agent_garden=agent_garden,
remote_spec=remote_spec,
google_api_key=google_api_key,
google_cloud_project=creds_info.get("project"),
)
# Replace region in all files if a different region was specified
if region != "us-central1":
replace_region_in_files(project_path, region, debug=debug)
# Handle base template dependencies if override was used
# Skip if --skip-deps is set (used when reusing saved config)
# Only trigger if the base template is ACTUALLY different from the original
# (not just selected from interactive menu but same as default)
is_actual_override = (
base_template
and original_base_template
and base_template != original_base_template
)
if (
is_actual_override
and base_template
and template_source_path
and remote_config
and not skip_deps
):
# Load base template config to get extra_dependencies
base_template_path = get_template_path(base_template, debug=debug)
base_config = load_template_config(base_template_path)
base_deps = base_config.get("settings", {}).get(
"extra_dependencies", []
)
if base_deps:
# Call interactive dependency addition
add_base_template_dependencies_interactively(
project_path,
base_deps,
base_template,
auto_approve=auto_approve,
)
finally:
# Clean up the temporary directory if one was created
if temp_dir_to_clean:
try:
shutil.rmtree(temp_dir_to_clean)
logging.debug(
f"Successfully cleaned up temporary directory: {temp_dir_to_clean}"
)
except OSError as e:
logging.warning(
f"Failed to clean up temporary directory {temp_dir_to_clean}: {e}"
)
if not in_folder:
project_path = destination_dir / project_name
cd_path = project_path if output_dir else project_name
else: