forked from microsoft/apm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
4413 lines (3752 loc) · 177 KB
/
cli.py
File metadata and controls
4413 lines (3752 loc) · 177 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
"""Command-line interface for Agent Package Manager (APM)."""
import builtins
import os
import sys
from pathlib import Path
from typing import List
import click
from colorama import Fore, Style, init
# CRITICAL: Shadow Click commands at module level to prevent namespace collision
# When Click commands like 'config set' are defined, calling set() can invoke the command
# instead of the Python built-in. This affects ALL functions in this module.
set = builtins.set
list = builtins.list
dict = builtins.dict
from apm_cli.commands.deps import deps
from apm_cli.compilation import AgentsCompiler, CompilationConfig
from apm_cli.primitives.discovery import discover_primitives
from apm_cli.utils.console import (
STATUS_SYMBOLS,
_create_files_table,
_get_console,
_rich_echo,
_rich_error,
_rich_info,
_rich_panel,
_rich_success,
_rich_warning,
show_download_spinner,
)
from apm_cli.utils.github_host import is_valid_fqdn, default_host
# APM imports - use absolute imports everywhere for consistency
from apm_cli.version import get_version
from apm_cli.utils.version_checker import check_for_updates
# APM Dependencies - Import for Task 5 integration
try:
from apm_cli.deps.apm_resolver import APMDependencyResolver
from apm_cli.deps.github_downloader import GitHubPackageDownloader
from apm_cli.deps.lockfile import LockFile
from apm_cli.models.apm_package import APMPackage, DependencyReference
from apm_cli.integration import PromptIntegrator, AgentIntegrator
APM_DEPS_AVAILABLE = True
except ImportError as e:
# Graceful fallback if APM dependencies are not available
APM_DEPS_AVAILABLE = False
_APM_IMPORT_ERROR = str(e)
# Initialize colorama for fallback
init(autoreset=True)
# Legacy colorama constants for compatibility
TITLE = f"{Fore.CYAN}{Style.BRIGHT}"
SUCCESS = f"{Fore.GREEN}{Style.BRIGHT}"
ERROR = f"{Fore.RED}{Style.BRIGHT}"
INFO = f"{Fore.BLUE}"
WARNING = f"{Fore.YELLOW}"
HIGHLIGHT = f"{Fore.MAGENTA}{Style.BRIGHT}"
RESET = Style.RESET_ALL
# Lazy loading for Rich components to improve startup performance
_console = None
def _get_console():
"""Get Rich console instance with lazy loading."""
global _console
if _console is None:
from rich.console import Console
from rich.theme import Theme
custom_theme = Theme(
{
"info": "cyan",
"warning": "yellow",
"error": "bold red",
"success": "bold green",
"highlight": "bold magenta",
"muted": "dim white",
"accent": "bold blue",
"title": "bold cyan",
}
)
_console = Console(theme=custom_theme)
return _console
def _rich_blank_line():
"""Print a blank line with Rich if available, otherwise use click."""
console = _get_console()
if console:
console.print()
else:
click.echo()
def _lazy_yaml():
"""Lazy import for yaml module to improve startup performance."""
try:
import yaml
return yaml
except ImportError:
raise ImportError("PyYAML is required but not installed")
def _lazy_prompt():
"""Lazy import for Rich Prompt to improve startup performance."""
try:
from rich.prompt import Prompt
return Prompt
except ImportError:
return None
def _lazy_confirm():
"""Lazy import for Rich Confirm to improve startup performance."""
try:
from rich.prompt import Confirm
return Confirm
except ImportError:
return None
def _check_orphaned_packages():
"""Check for packages in apm_modules/ that are not declared in apm.yml or apm.lock.
Considers both direct dependencies (from apm.yml) and transitive dependencies
(from apm.lock) as expected packages, so transitive deps are not falsely
flagged as orphaned.
Returns:
List[str]: List of orphaned package names in org/repo or org/project/repo format
"""
try:
# Check if apm.yml exists
if not Path("apm.yml").exists():
return []
# Check if apm_modules exists
apm_modules_dir = Path("apm_modules")
if not apm_modules_dir.exists():
return []
# Parse apm.yml to get declared dependencies
try:
apm_package = APMPackage.from_apm_yml(Path("apm.yml"))
declared_deps = apm_package.get_apm_dependencies()
# Build set of expected installed package paths using get_install_path()
# This ensures consistency with how packages are installed and uninstalled
expected_installed = builtins.set()
for dep in declared_deps:
install_path = dep.get_install_path(apm_modules_dir)
# Convert absolute path to relative key for comparison
try:
relative_path = install_path.relative_to(apm_modules_dir)
expected_installed.add(str(relative_path))
except ValueError:
# If path is not relative to apm_modules_dir, use as-is
expected_installed.add(str(install_path))
# Also include transitive dependencies from apm.lock
lockfile_paths = LockFile.installed_paths_for_project(Path.cwd())
expected_installed.update(lockfile_paths)
except Exception:
return [] # If can't parse apm.yml, assume no orphans
# Find installed packages in apm_modules/ (supports both 2-level and 3-level structures)
# GitHub: apm_modules/owner/repo (2 levels)
# Azure DevOps: apm_modules/org/project/repo (3 levels)
installed_packages = []
for level1_dir in apm_modules_dir.iterdir():
if level1_dir.is_dir() and not level1_dir.name.startswith("."):
for level2_dir in level1_dir.iterdir():
if level2_dir.is_dir() and not level2_dir.name.startswith("."):
# Check if level2 has apm.yml or .apm (GitHub 2-level structure)
if (level2_dir / "apm.yml").exists() or (
level2_dir / ".apm"
).exists():
path_key = f"{level1_dir.name}/{level2_dir.name}"
installed_packages.append(path_key)
else:
# Check for ADO 3-level structure
for level3_dir in level2_dir.iterdir():
if (
level3_dir.is_dir()
and not level3_dir.name.startswith(".")
):
if (level3_dir / "apm.yml").exists() or (
level3_dir / ".apm"
).exists():
path_key = f"{level1_dir.name}/{level2_dir.name}/{level3_dir.name}"
installed_packages.append(path_key)
# Find orphaned packages (installed but not declared or locked)
orphaned_packages = []
for org_repo_name in installed_packages:
if org_repo_name not in expected_installed:
orphaned_packages.append(org_repo_name)
return orphaned_packages
except Exception:
return [] # Return empty list if any error occurs
def print_version(ctx, param, value):
"""Print version and exit."""
if not value or ctx.resilient_parsing:
return
console = _get_console()
if console:
from rich.panel import Panel # type: ignore
from rich.text import Text # type: ignore
version_text = Text()
version_text.append("Agent Package Manager (APM) CLI", style="bold cyan")
version_text.append(f" version {get_version()}", style="white")
console.print(Panel(version_text, border_style="cyan", padding=(0, 1)))
else:
# Graceful fallback when Rich isn't available (e.g., stripped automation environment)
click.echo(
f"{TITLE}Agent Package Manager (APM) CLI{RESET} version {get_version()}"
)
ctx.exit()
def _check_and_notify_updates():
"""Check for updates and notify user non-blockingly."""
try:
# Skip version check in E2E test mode to avoid interfering with tests
if os.environ.get("APM_E2E_TESTS", "").lower() in ("1", "true", "yes"):
return
current_version = get_version()
# Skip check for development versions
if current_version == "unknown":
return
latest_version = check_for_updates(current_version)
if latest_version:
# Display yellow warning with update command
_rich_warning(
f"A new version of APM is available: {latest_version} (current: {current_version})",
symbol="warning",
)
# Show update command using helper for consistency
_rich_echo("Run apm update to upgrade", color="yellow", bold=True)
# Add a blank line for visual separation
click.echo()
except Exception:
# Silently fail - version checking should never block CLI usage
pass
@click.group(
help="Agent Package Manager (APM): The package manager for AI-Native Development"
)
@click.option(
"--version",
is_flag=True,
callback=print_version,
expose_value=False,
is_eager=True,
help="Show version and exit.",
)
@click.pass_context
def cli(ctx):
"""Main entry point for the APM CLI."""
ctx.ensure_object(dict)
# Check for updates non-blockingly (only if not already showing version)
if not ctx.resilient_parsing:
_check_and_notify_updates()
# Register command groups
cli.add_command(deps)
@cli.command(help="🚀 Initialize a new APM project")
@click.argument("project_name", required=False)
@click.option(
"--yes", "-y", is_flag=True, help="Skip prompts and use auto-detected defaults"
)
@click.pass_context
def init(ctx, project_name, yes):
"""Initialize a new APM project (like npm init).
Creates a minimal apm.yml with auto-detected metadata.
"""
try:
# Handle explicit current directory
if project_name == ".":
project_name = None
# Determine project directory and name
if project_name:
project_dir = Path(project_name)
project_dir.mkdir(exist_ok=True)
os.chdir(project_dir)
_rich_info(f"Created project directory: {project_name}", symbol="folder")
final_project_name = project_name
else:
project_dir = Path.cwd()
final_project_name = project_dir.name
# Check for existing apm.yml
apm_yml_exists = Path("apm.yml").exists()
# Handle existing apm.yml in brownfield projects
if apm_yml_exists:
_rich_warning("apm.yml already exists")
if not yes:
Confirm = _lazy_confirm()
if Confirm:
try:
confirm = Confirm.ask("Continue and overwrite?")
except Exception:
confirm = click.confirm("Continue and overwrite?")
else:
confirm = click.confirm("Continue and overwrite?")
if not confirm:
_rich_info("Initialization cancelled.")
return
else:
_rich_info("--yes specified, overwriting apm.yml...")
# Get project configuration (interactive mode or defaults)
if not yes:
config = _interactive_project_setup(final_project_name)
else:
# Use auto-detected defaults
config = _get_default_config(final_project_name)
_rich_success(f"Initializing APM project: {config['name']}", symbol="rocket")
# Create minimal apm.yml
_create_minimal_apm_yml(config)
_rich_success("APM project initialized successfully!", symbol="sparkles")
# Display created file info
try:
console = _get_console()
if console:
files_data = [
("✨", "apm.yml", "Project configuration"),
]
table = _create_files_table(files_data, title="Created Files")
console.print(table)
except (ImportError, NameError):
_rich_info("Created:")
_rich_echo(" ✨ apm.yml - Project configuration", style="muted")
_rich_blank_line()
# Next steps - actionable commands matching README workflow
next_steps = [
"Install a runtime: apm runtime setup copilot",
"Add APM dependencies: apm install <owner>/<repo>",
"Compile agent context: apm compile",
"Run your first workflow: apm run start",
]
try:
_rich_panel(
"\n".join(f"• {step}" for step in next_steps),
title="💡 Next Steps",
style="cyan",
)
except (ImportError, NameError):
_rich_info("Next steps:")
for step in next_steps:
click.echo(f" • {step}")
except Exception as e:
_rich_error(f"Error initializing project: {e}")
sys.exit(1)
def _validate_and_add_packages_to_apm_yml(packages, dry_run=False):
"""Validate packages exist and can be accessed, then add to apm.yml dependencies section."""
import subprocess
import tempfile
from pathlib import Path
import yaml
apm_yml_path = Path("apm.yml")
# Read current apm.yml
try:
with open(apm_yml_path, "r") as f:
data = yaml.safe_load(f) or {}
except Exception as e:
_rich_error(f"Failed to read apm.yml: {e}")
sys.exit(1)
# Ensure dependencies structure exists
if "dependencies" not in data:
data["dependencies"] = {}
if "apm" not in data["dependencies"]:
data["dependencies"]["apm"] = []
current_deps = data["dependencies"]["apm"] or []
validated_packages = []
# First, validate all packages
_rich_info(f"Validating {len(packages)} package(s)...")
for package in packages:
# Validate package format (should be owner/repo)
if "/" not in package:
_rich_error(f"Invalid package format: {package}. Use 'owner/repo' format.")
continue
# Check if package is already in dependencies
already_in_deps = package in current_deps
# Validate package exists and is accessible
if _validate_package_exists(package):
if already_in_deps:
_rich_info(
f"✓ {package} - already in apm.yml, ensuring installation..."
)
else:
validated_packages.append(package)
_rich_info(f"✓ {package} - accessible")
else:
_rich_error(f"✗ {package} - not accessible or doesn't exist")
if not validated_packages:
if dry_run:
_rich_warning("No new packages to add")
# If all packages already exist in apm.yml, that's OK - we'll reinstall them
return []
if dry_run:
_rich_info(
f"Dry run: Would add {len(validated_packages)} package(s) to apm.yml:"
)
for pkg in validated_packages:
_rich_info(f" + {pkg}")
return validated_packages
# Add validated packages to dependencies
for package in validated_packages:
current_deps.append(package)
_rich_info(f"Added {package} to apm.yml")
# Update dependencies
data["dependencies"]["apm"] = current_deps
# Write back to apm.yml
try:
with open(apm_yml_path, "w") as f:
yaml.safe_dump(data, f, default_flow_style=False, sort_keys=False)
_rich_success(f"Updated apm.yml with {len(validated_packages)} new package(s)")
except Exception as e:
_rich_error(f"Failed to write apm.yml: {e}")
sys.exit(1)
return validated_packages
def _validate_package_exists(package):
"""Validate that a package exists and is accessible on GitHub or Azure DevOps."""
import os
import subprocess
import tempfile
try:
# Parse the package to check if it's a virtual package or ADO
from apm_cli.models.apm_package import DependencyReference
from apm_cli.deps.github_downloader import GitHubPackageDownloader
dep_ref = DependencyReference.parse(package)
# For virtual packages, use the downloader's validation method
if dep_ref.is_virtual:
downloader = GitHubPackageDownloader()
return downloader.validate_virtual_package_exists(dep_ref)
# For Azure DevOps or GitHub Enterprise (non-github.com hosts),
# use the downloader which handles authentication properly
if dep_ref.is_azure_devops() or (dep_ref.host and dep_ref.host != "github.com"):
downloader = GitHubPackageDownloader()
# Set the host
if dep_ref.host:
downloader.github_host = dep_ref.host
# Build authenticated URL using downloader's auth
package_url = downloader._build_repo_url(
dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref
)
# Use the downloader's git environment which has auth configured
cmd = ["git", "ls-remote", "--heads", "--exit-code", package_url]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30,
env={**os.environ, **downloader.git_env},
)
return result.returncode == 0
# For GitHub.com, use standard approach (public repos don't need auth)
package_url = f"{dep_ref.to_github_url()}.git"
# For regular packages, use git ls-remote
with tempfile.TemporaryDirectory() as temp_dir:
try:
# Try cloning with minimal fetch
cmd = [
"git",
"ls-remote",
"--heads",
"--exit-code",
package_url,
]
result = subprocess.run(
cmd, capture_output=True, text=True, timeout=30 # 30 second timeout
)
return result.returncode == 0
except subprocess.TimeoutExpired:
return False
except Exception:
return False
except Exception:
# If parsing fails, assume it's a regular GitHub package
package_url = (
f"https://{package}.git"
if is_valid_fqdn(package)
else f"https://{default_host()}/{package}.git"
)
with tempfile.TemporaryDirectory() as temp_dir:
try:
cmd = [
"git",
"ls-remote",
"--heads",
"--exit-code",
package_url,
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
return result.returncode == 0
except subprocess.TimeoutExpired:
return False
except Exception:
return False
@cli.command(
help="📦 Install APM and MCP dependencies (auto-creates apm.yml when installing packages)"
)
@click.argument("packages", nargs=-1)
@click.option("--runtime", help="Target specific runtime only (copilot, codex, vscode)")
@click.option("--exclude", help="Exclude specific runtime from installation")
@click.option(
"--only",
type=click.Choice(["apm", "mcp"]),
help="Install only specific dependency type",
)
@click.option(
"--update", is_flag=True, help="Update dependencies to latest Git references"
)
@click.option(
"--dry-run", is_flag=True, help="Show what would be installed without installing"
)
@click.option("--verbose", is_flag=True, help="Show detailed installation information")
@click.pass_context
def install(ctx, packages, runtime, exclude, only, update, dry_run, verbose):
"""Install APM and MCP dependencies from apm.yml (like npm install).
This command automatically detects AI runtimes from your apm.yml scripts and installs
MCP servers for all detected and available runtimes. It also installs APM package
dependencies from GitHub repositories.
Examples:
apm install # Install existing deps from apm.yml
apm install org/pkg1 # Add package to apm.yml and install
apm install org/pkg1 org/pkg2 # Add multiple packages and install
apm install --exclude codex # Install for all except Codex CLI
apm install --only=apm # Install only APM dependencies
apm install --only=mcp # Install only MCP dependencies
apm install --update # Update dependencies to latest Git refs
apm install --dry-run # Show what would be installed
"""
try:
# Check if apm.yml exists
apm_yml_exists = Path("apm.yml").exists()
# Auto-bootstrap: create minimal apm.yml when packages specified but no apm.yml
if not apm_yml_exists and packages:
# Get current directory name as project name
project_name = Path.cwd().name
config = _get_default_config(project_name)
_create_minimal_apm_yml(config)
_rich_success("Created apm.yml", symbol="sparkles")
# Error when NO apm.yml AND NO packages
if not apm_yml_exists and not packages:
_rich_error("No apm.yml found")
_rich_info("💡 Run 'apm init' to create one, or:")
_rich_info(" apm install <org/repo> to auto-create + install")
sys.exit(1)
# If packages are specified, validate and add them to apm.yml first
if packages:
validated_packages = _validate_and_add_packages_to_apm_yml(
packages, dry_run
)
# Note: Empty validated_packages is OK if packages are already in apm.yml
# We'll proceed with installation from apm.yml to ensure everything is synced
_rich_info("Installing dependencies from apm.yml...")
# Parse apm.yml to get both APM and MCP dependencies
try:
apm_package = APMPackage.from_apm_yml(Path("apm.yml"))
except Exception as e:
_rich_error(f"Failed to parse apm.yml: {e}")
sys.exit(1)
# Get APM and MCP dependencies
apm_deps = apm_package.get_apm_dependencies()
mcp_deps = apm_package.get_mcp_dependencies()
# Determine what to install based on --only flag
should_install_apm = only != "mcp"
should_install_mcp = only != "apm"
# Show what will be installed if dry run
if dry_run:
_rich_info("Dry run mode - showing what would be installed:")
if should_install_apm and apm_deps:
_rich_info(f"APM dependencies ({len(apm_deps)}):")
for dep in apm_deps:
action = "update" if update else "install"
_rich_info(
f" - {dep.repo_url}#{dep.reference or 'main'} → {action}"
)
if should_install_mcp and mcp_deps:
_rich_info(f"MCP dependencies ({len(mcp_deps)}):")
for dep in mcp_deps:
_rich_info(f" - {dep}")
if not apm_deps and not mcp_deps:
_rich_warning("No dependencies found in apm.yml")
_rich_success("Dry run complete - no changes made")
return
# Install APM dependencies first (if requested)
apm_count = 0
prompt_count = 0
agent_count = 0
if should_install_apm and apm_deps:
if not APM_DEPS_AVAILABLE:
_rich_error("APM dependency system not available")
_rich_info(f"Import error: {_APM_IMPORT_ERROR}")
sys.exit(1)
try:
# If specific packages were requested, only install those
# Otherwise install all from apm.yml
only_pkgs = builtins.list(packages) if packages else None
apm_count, prompt_count, agent_count = _install_apm_dependencies(
apm_package, update, verbose, only_pkgs
)
except Exception as e:
_rich_error(f"Failed to install APM dependencies: {e}")
sys.exit(1)
elif should_install_apm and not apm_deps:
_rich_info("No APM dependencies found in apm.yml")
# Continue with MCP installation (existing logic)
mcp_count = 0
if should_install_mcp and mcp_deps:
mcp_count = _install_mcp_dependencies(mcp_deps, runtime, exclude, verbose)
elif should_install_mcp and not mcp_deps:
_rich_warning("No MCP dependencies found in apm.yml")
# Show beautiful post-install summary
_rich_blank_line()
if not only:
# Load apm.yml config for summary
apm_config = _load_apm_config()
_show_install_summary(
apm_count, prompt_count, agent_count, mcp_count, apm_config
)
elif only == "apm":
_rich_success(f"Installed {apm_count} APM dependencies")
elif only == "mcp":
_rich_success(f"Configured {mcp_count} MCP servers")
except Exception as e:
_rich_error(f"Error installing dependencies: {e}")
sys.exit(1)
@cli.command(help="Remove APM packages not listed in apm.yml")
@click.option(
"--dry-run", is_flag=True, help="Show what would be removed without removing"
)
@click.pass_context
def prune(ctx, dry_run):
"""Remove installed APM packages that are not listed in apm.yml (like npm prune).
This command cleans up the apm_modules/ directory by removing packages that
were previously installed but are no longer declared as dependencies in apm.yml.
Examples:
apm prune # Remove orphaned packages
apm prune --dry-run # Show what would be removed
"""
try:
# Check if apm.yml exists
if not Path("apm.yml").exists():
_rich_error("No apm.yml found. Run 'apm init' first.")
sys.exit(1)
# Check if apm_modules exists
apm_modules_dir = Path("apm_modules")
if not apm_modules_dir.exists():
_rich_info("No apm_modules/ directory found. Nothing to prune.")
return
_rich_info("Analyzing installed packages vs apm.yml...")
# Parse apm.yml to get declared dependencies
try:
apm_package = APMPackage.from_apm_yml(Path("apm.yml"))
declared_deps = apm_package.get_apm_dependencies()
# Build set of expected installed package paths
# For virtual packages, use the sanitized package name from get_virtual_package_name()
# For regular packages, use repo_url as-is
# GitHub: owner/repo or owner/virtual-pkg-name (2 levels)
# Azure DevOps: org/project/repo or org/project/virtual-pkg-name (3 levels)
expected_installed = builtins.set()
for dep in declared_deps:
repo_parts = dep.repo_url.split("/")
if dep.is_virtual:
if dep.is_virtual_subdirectory() and dep.virtual_path:
# Virtual subdirectory packages keep natural path structure.
if dep.is_azure_devops() and len(repo_parts) >= 3:
expected_installed.add(
f"{repo_parts[0]}/{repo_parts[1]}/{repo_parts[2]}/{dep.virtual_path}"
)
elif len(repo_parts) >= 2:
expected_installed.add(
f"{repo_parts[0]}/{repo_parts[1]}/{dep.virtual_path}"
)
else:
# Virtual file/collection packages are flattened.
package_name = dep.get_virtual_package_name()
if dep.is_azure_devops() and len(repo_parts) >= 3:
expected_installed.add(
f"{repo_parts[0]}/{repo_parts[1]}/{package_name}"
)
elif len(repo_parts) >= 2:
expected_installed.add(f"{repo_parts[0]}/{package_name}")
else:
# Regular package: use full repo_url path
if dep.is_azure_devops() and len(repo_parts) >= 3:
expected_installed.add(
f"{repo_parts[0]}/{repo_parts[1]}/{repo_parts[2]}"
)
elif len(repo_parts) >= 2:
expected_installed.add(f"{repo_parts[0]}/{repo_parts[1]}")
# Also include transitive dependencies from apm.lock
lockfile_paths = LockFile.installed_paths_for_project(Path.cwd())
expected_installed.update(lockfile_paths)
except Exception as e:
_rich_error(f"Failed to parse apm.yml: {e}")
sys.exit(1)
# Find installed packages in apm_modules/ (now org-namespaced)
# Walks the tree to find directories containing apm.yml or .apm,
# handling GitHub (2-level), ADO (3-level), and subdirectory (4+ level) packages.
installed_packages = {} # {"path": "display_name"}
if apm_modules_dir.exists():
for candidate in apm_modules_dir.rglob("*"):
if not candidate.is_dir() or candidate.name.startswith("."):
continue
if not ((candidate / "apm.yml").exists() or (candidate / ".apm").exists()):
continue
rel_parts = candidate.relative_to(apm_modules_dir).parts
if len(rel_parts) >= 2:
path_key = "/".join(rel_parts)
installed_packages[path_key] = path_key
# Find orphaned packages (installed but not declared)
orphaned_packages = {}
for org_repo_name, display_name in installed_packages.items():
if org_repo_name not in expected_installed:
orphaned_packages[org_repo_name] = display_name
if not orphaned_packages:
_rich_success("No orphaned packages found. apm_modules/ is clean.")
return
# Show what will be removed
_rich_info(f"Found {len(orphaned_packages)} orphaned package(s):")
for dir_name, display_name in orphaned_packages.items():
if dry_run:
_rich_info(f" - {display_name} (would be removed)")
else:
_rich_info(f" - {display_name}")
if dry_run:
_rich_success("Dry run complete - no changes made")
return
# Remove orphaned packages
removed_count = 0
for org_repo_name, display_name in orphaned_packages.items():
# Convert org/repo or org/project/repo to filesystem path
path_parts = org_repo_name.split("/")
pkg_path = apm_modules_dir.joinpath(*path_parts)
try:
import shutil
shutil.rmtree(pkg_path)
_rich_info(f"✓ Removed {display_name}")
removed_count += 1
# Clean up empty parent directories (project for ADO, org for both)
if len(path_parts) >= 3:
# ADO 3-level: clean up project directory if empty
project_path = apm_modules_dir / path_parts[0] / path_parts[1]
if project_path.exists() and not any(project_path.iterdir()):
project_path.rmdir()
# Clean up org directory if empty
org_path = apm_modules_dir / path_parts[0]
if org_path.exists() and not any(org_path.iterdir()):
org_path.rmdir()
except Exception as e:
_rich_error(f"✗ Failed to remove {display_name}: {e}")
# Final summary
if removed_count > 0:
_rich_success(f"Pruned {removed_count} orphaned package(s)")
else:
_rich_warning("No packages were removed")
except Exception as e:
_rich_error(f"Error pruning packages: {e}")
sys.exit(1)
@cli.command(help="⬆️ Update APM to the latest version")
@click.option("--check", is_flag=True, help="Only check for updates without installing")
def update(check):
"""Update APM CLI to the latest version (like npm update -g npm).
This command fetches and installs the latest version of APM using the
official install script. It will detect your platform and architecture
automatically.
Examples:
apm update # Update to latest version
apm update --check # Only check if update is available
"""
try:
import subprocess
import tempfile
current_version = get_version()
# Skip check for development versions
if current_version == "unknown":
_rich_warning(
"Cannot determine current version. Running in development mode?"
)
if not check:
_rich_info("To update, reinstall from the repository.")
return
_rich_info(f"Current version: {current_version}", symbol="info")
_rich_info("Checking for updates...", symbol="running")
# Check for latest version
from apm_cli.utils.version_checker import get_latest_version_from_github
latest_version = get_latest_version_from_github()
if not latest_version:
_rich_error("Unable to fetch latest version from GitHub")
_rich_info("Please check your internet connection or try again later")
sys.exit(1)
from apm_cli.utils.version_checker import is_newer_version
if not is_newer_version(current_version, latest_version):
_rich_success(
f"You're already on the latest version: {current_version}",
symbol="check",
)
return
_rich_info(f"Latest version available: {latest_version}", symbol="sparkles")
if check:
_rich_warning(f"Update available: {current_version} → {latest_version}")
_rich_info("Run 'apm update' (without --check) to install", symbol="info")
return
# Proceed with update
_rich_info("Downloading and installing update...", symbol="running")
# Download install script to temp file
try:
import requests
install_script_url = (
"https://raw.githubusercontent.com/microsoft/apm/main/install.sh"
)
response = requests.get(install_script_url, timeout=10)
response.raise_for_status()
# Create temporary file for install script
with tempfile.NamedTemporaryFile(mode="w", suffix=".sh", delete=False) as f:
temp_script = f.name
f.write(response.text)
# Make script executable
os.chmod(temp_script, 0o755)
# Run install script
_rich_info("Running installer...", symbol="gear")
# Use /bin/sh for better cross-platform compatibility
# Note: We don't capture output so the installer can prompt for sudo
shell_path = "/bin/sh" if os.path.exists("/bin/sh") else "sh"
result = subprocess.run(
[shell_path, temp_script], check=False
)
# Clean up temp file
try:
os.unlink(temp_script)
except Exception:
# Non-fatal: failed to delete temp install script
pass
if result.returncode == 0:
_rich_success(
f"Successfully updated to version {latest_version}!",
symbol="sparkles",
)
_rich_info(
"Please restart your terminal or run 'apm --version' to verify"
)
else:
_rich_error("Installation failed - see output above for details")
sys.exit(1)
except ImportError:
_rich_error("'requests' library not available")
_rich_info("Please update manually using:")
click.echo(
" curl -sSL https://raw.githubusercontent.com/microsoft/apm/main/install.sh | sh"
)
sys.exit(1)
except Exception as e:
_rich_error(f"Update failed: {e}")
_rich_info("Please update manually using:")
click.echo(
" curl -sSL https://raw.githubusercontent.com/microsoft/apm/main/install.sh | sh"