-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathinstall.py
More file actions
2468 lines (2195 loc) · 114 KB
/
install.py
File metadata and controls
2468 lines (2195 loc) · 114 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
"""APM install command and dependency installation engine."""
import builtins
import sys
from pathlib import Path
from typing import List
import click
from ..constants import (
APM_LOCK_FILENAME,
APM_MODULES_DIR,
APM_YML_FILENAME,
GITHUB_DIR,
CLAUDE_DIR,
SKILL_MD_FILENAME,
InstallMode,
)
from ..drift import build_download_ref, detect_orphans, detect_ref_change
from ..models.results import InstallResult
from ..core.command_logger import InstallLogger, _ValidationOutcome
from ..utils.console import _rich_echo, _rich_error, _rich_info, _rich_success
from ..utils.diagnostics import DiagnosticCollector
from ..utils.github_host import default_host, is_valid_fqdn
from ..utils.path_security import safe_rmtree
from ._helpers import (
_create_minimal_apm_yml,
_get_default_config,
_rich_blank_line,
_update_gitignore_for_apm_modules,
)
# CRITICAL: Shadow Python builtins that share names with Click commands
set = builtins.set
list = builtins.list
dict = builtins.dict
# AuthResolver has no optional deps (stdlib + internal utils only), so it must
# be imported unconditionally here -- NOT inside the APM_DEPS_AVAILABLE guard.
# If it were gated, a missing optional dep (e.g. GitPython) would cause a
# NameError in install() before the graceful APM_DEPS_AVAILABLE check fires.
from ..core.auth import AuthResolver
# APM Dependencies (conditional import for graceful degradation)
APM_DEPS_AVAILABLE = False
_APM_IMPORT_ERROR = None
try:
from ..deps.apm_resolver import APMDependencyResolver
from ..deps.github_downloader import GitHubPackageDownloader
from ..deps.lockfile import LockFile, get_lockfile_path, migrate_lockfile_if_needed
from ..integration import AgentIntegrator, PromptIntegrator
from ..integration.mcp_integrator import MCPIntegrator
from ..models.apm_package import APMPackage, DependencyReference
APM_DEPS_AVAILABLE = True
except ImportError as e:
_APM_IMPORT_ERROR = str(e)
# ---------------------------------------------------------------------------
# Validation helpers
# ---------------------------------------------------------------------------
def _validate_and_add_packages_to_apm_yml(packages, dry_run=False, dev=False, logger=None, manifest_path=None, auth_resolver=None, scope=None):
"""Validate packages exist and can be accessed, then add to apm.yml dependencies section.
Implements normalize-on-write: any input form (HTTPS URL, SSH URL, FQDN, shorthand)
is canonicalized before storage. Default host (github.com) is stripped;
non-default hosts are preserved. Duplicates are detected by identity.
Args:
packages: Package specifiers to validate and add.
dry_run: If True, only show what would be added.
dev: If True, write to devDependencies instead of dependencies.
logger: InstallLogger for structured output.
manifest_path: Explicit path to apm.yml (defaults to cwd/apm.yml).
auth_resolver: Shared auth resolver for caching credentials.
scope: InstallScope controlling project vs user deployment.
Returns:
Tuple of (validated_packages list, _ValidationOutcome).
"""
import subprocess
import tempfile
from pathlib import Path
apm_yml_path = manifest_path or Path(APM_YML_FILENAME)
# Read current apm.yml
try:
from ..utils.yaml_io import load_yaml
data = load_yaml(apm_yml_path) or {}
except Exception as e:
if logger:
logger.error(f"Failed to read {APM_YML_FILENAME}: {e}")
else:
_rich_error(f"Failed to read {APM_YML_FILENAME}: {e}")
sys.exit(1)
# Ensure dependencies structure exists
dep_section = "devDependencies" if dev else "dependencies"
if dep_section not in data:
data[dep_section] = {}
if "apm" not in data[dep_section]:
data[dep_section]["apm"] = []
current_deps = data[dep_section]["apm"] or []
validated_packages = []
# Build identity set from existing deps for duplicate detection
existing_identities = builtins.set()
for dep_entry in current_deps:
try:
if isinstance(dep_entry, str):
ref = DependencyReference.parse(dep_entry)
elif isinstance(dep_entry, builtins.dict):
ref = DependencyReference.parse_from_dict(dep_entry)
else:
continue
existing_identities.add(ref.get_identity())
except (ValueError, TypeError, AttributeError, KeyError):
continue
# First, validate all packages
valid_outcomes = [] # (canonical, already_present) tuples
invalid_outcomes = [] # (package, reason) tuples
_marketplace_provenance = {} # canonical -> {discovered_via, marketplace_plugin_name}
if logger:
logger.validation_start(len(packages))
for package in packages:
# --- Marketplace pre-parse intercept ---
# If input has no slash and is not a local path, check if it is a
# marketplace ref (NAME@MARKETPLACE). If so, resolve it to a
# canonical owner/repo[#ref] string before entering the standard
# parse path. Anything that doesn't match is rejected as an
# invalid format.
marketplace_provenance = None
if "/" not in package and not DependencyReference.is_local_path(package):
try:
from ..marketplace.resolver import (
parse_marketplace_ref,
resolve_marketplace_plugin,
)
mkt_ref = parse_marketplace_ref(package)
except ImportError:
mkt_ref = None
if mkt_ref is not None:
plugin_name, marketplace_name = mkt_ref
try:
if logger:
logger.verbose_detail(
f" Resolving {plugin_name}@{marketplace_name} via marketplace..."
)
canonical_str, resolved_plugin = resolve_marketplace_plugin(
plugin_name,
marketplace_name,
auth_resolver=auth_resolver,
)
if logger:
logger.verbose_detail(
f" Resolved to: {canonical_str}"
)
marketplace_provenance = {
"discovered_via": marketplace_name,
"marketplace_plugin_name": plugin_name,
}
package = canonical_str
except Exception as mkt_err:
reason = str(mkt_err)
invalid_outcomes.append((package, reason))
if logger:
logger.validation_fail(package, reason)
continue
else:
# No slash, not a local path, and not a marketplace ref
reason = "invalid format -- use 'owner/repo' or 'plugin-name@marketplace'"
invalid_outcomes.append((package, reason))
if logger:
logger.validation_fail(package, reason)
continue
# Canonicalize input
try:
dep_ref = DependencyReference.parse(package)
canonical = dep_ref.to_canonical()
identity = dep_ref.get_identity()
except ValueError as e:
reason = str(e)
invalid_outcomes.append((package, reason))
if logger:
logger.validation_fail(package, reason)
continue
# Reject local packages at user scope -- relative paths resolve
# against cwd during validation but against $HOME during copy,
# causing silent failures.
if dep_ref.is_local and scope is not None:
from ..core.scope import InstallScope
if scope is InstallScope.USER:
reason = (
"local packages are not supported at user scope (--global). "
"Use a remote reference (owner/repo) instead"
)
invalid_outcomes.append((package, reason))
if logger:
logger.validation_fail(package, reason)
continue
# Check if package is already in dependencies (by identity)
already_in_deps = identity in existing_identities
# Validate package exists and is accessible
verbose = bool(logger and logger.verbose)
if _validate_package_exists(package, verbose=verbose, auth_resolver=auth_resolver):
valid_outcomes.append((canonical, already_in_deps))
if logger:
logger.validation_pass(canonical, already_present=already_in_deps)
if not already_in_deps:
validated_packages.append(canonical)
existing_identities.add(identity) # prevent duplicates within batch
if marketplace_provenance:
_marketplace_provenance[identity] = marketplace_provenance
else:
reason = _local_path_failure_reason(dep_ref)
if not reason:
reason = "not accessible or doesn't exist"
if not verbose:
reason += " -- run with --verbose for auth details"
invalid_outcomes.append((package, reason))
if logger:
logger.validation_fail(package, reason)
outcome = _ValidationOutcome(
valid=valid_outcomes,
invalid=invalid_outcomes,
marketplace_provenance=_marketplace_provenance or None,
)
# Let the logger emit a summary and decide whether to continue
if logger:
should_continue = logger.validation_summary(outcome)
if not should_continue:
return [], outcome
if not validated_packages:
if dry_run:
if logger:
logger.progress("No new packages to add")
# If all packages already exist in apm.yml, that's OK - we'll reinstall them
return [], outcome
if dry_run:
if logger:
logger.progress(
f"Dry run: Would add {len(validated_packages)} package(s) to apm.yml"
)
for pkg in validated_packages:
logger.verbose_detail(f" + {pkg}")
return validated_packages, outcome
# Add validated packages to dependencies (already canonical)
dep_label = "devDependencies" if dev else "apm.yml"
for package in validated_packages:
current_deps.append(package)
if logger:
logger.verbose_detail(f"Added {package} to {dep_label}")
# Update dependencies
data[dep_section]["apm"] = current_deps
# Write back to apm.yml
try:
from ..utils.yaml_io import dump_yaml
dump_yaml(data, apm_yml_path)
if logger:
logger.success(f"Updated {APM_YML_FILENAME} with {len(validated_packages)} new package(s)")
except Exception as e:
if logger:
logger.error(f"Failed to write {APM_YML_FILENAME}: {e}")
else:
_rich_error(f"Failed to write {APM_YML_FILENAME}: {e}")
sys.exit(1)
return validated_packages, outcome
def _local_path_failure_reason(dep_ref):
"""Return a specific failure reason for local path deps, or None for remote."""
if not (dep_ref.is_local and dep_ref.local_path):
return None
local = Path(dep_ref.local_path).expanduser()
if not local.is_absolute():
local = Path.cwd() / local
local = local.resolve()
if not local.exists():
return "path does not exist"
if not local.is_dir():
return "path is not a directory"
# Directory exists but has no package markers
return "no apm.yml, SKILL.md, or plugin.json found"
def _local_path_no_markers_hint(local_dir, verbose_log=None):
"""Scan two levels for sub-packages and print a hint if any are found."""
from apm_cli.utils.helpers import find_plugin_json
markers = ("apm.yml", "SKILL.md")
found = []
for child in sorted(local_dir.iterdir()):
if not child.is_dir():
continue
if any((child / m).exists() for m in markers) or find_plugin_json(child) is not None:
found.append(child)
# Also check one more level (e.g. skills/<name>/)
for grandchild in sorted(child.iterdir()) if child.is_dir() else []:
if not grandchild.is_dir():
continue
if any((grandchild / m).exists() for m in markers) or find_plugin_json(grandchild) is not None:
found.append(grandchild)
if not found:
return
_rich_info(" [i] Found installable package(s) inside this directory:")
for p in found[:5]:
_rich_echo(f" apm install {p}", color="dim")
if len(found) > 5:
_rich_echo(f" ... and {len(found) - 5} more", color="dim")
def _validate_package_exists(package, verbose=False, auth_resolver=None):
"""Validate that a package exists and is accessible on GitHub, Azure DevOps, or locally."""
import os
import subprocess
import tempfile
from apm_cli.core.auth import AuthResolver
verbose_log = (lambda msg: _rich_echo(f" {msg}", color="dim")) if verbose else None
# Use provided resolver or create new one if not in a CLI session context
if auth_resolver is None:
auth_resolver = AuthResolver()
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 local packages, validate directory exists and has valid package content
if dep_ref.is_local and dep_ref.local_path:
local = Path(dep_ref.local_path).expanduser()
if not local.is_absolute():
local = Path.cwd() / local
local = local.resolve()
if not local.is_dir():
return False
# Must contain apm.yml, SKILL.md, or plugin.json
if (local / "apm.yml").exists() or (local / "SKILL.md").exists():
return True
from apm_cli.utils.helpers import find_plugin_json
if find_plugin_json(local) is not None:
return True
# Directory exists but lacks package markers -- surface a hint
_local_path_no_markers_hint(local, verbose_log)
return False
# For virtual packages, use the downloader's validation method
if dep_ref.is_virtual:
ctx = auth_resolver.resolve_for_dep(dep_ref)
host = dep_ref.host or default_host()
org = dep_ref.repo_url.split('/')[0] if dep_ref.repo_url and '/' in dep_ref.repo_url else None
if verbose_log:
verbose_log(f"Auth resolved: host={host}, org={org}, source={ctx.source}, type={ctx.token_type}")
virtual_downloader = GitHubPackageDownloader(auth_resolver=auth_resolver)
result = virtual_downloader.validate_virtual_package_exists(dep_ref)
if not result and verbose_log:
try:
err_ctx = auth_resolver.build_error_context(host, f"accessing {package}", org=org)
for line in err_ctx.splitlines():
verbose_log(line)
except Exception:
pass
return result
# 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"):
from apm_cli.utils.github_host import is_github_hostname, is_azure_devops_hostname
# Determine host type before building the URL so we know whether to
# embed a token. Generic (non-GitHub, non-ADO) hosts are excluded
# from APM-managed auth; they rely on git credential helpers via the
# relaxed validate_env below.
is_generic = not is_github_hostname(dep_ref.host) and not is_azure_devops_hostname(dep_ref.host)
# For GHES / ADO: resolve per-dependency auth up front so the URL
# carries an embedded token and avoids triggering OS credential
# helper popups during git ls-remote validation.
_url_token = None
if not is_generic:
_dep_ctx = auth_resolver.resolve_for_dep(dep_ref)
_url_token = _dep_ctx.token
ado_downloader = GitHubPackageDownloader(auth_resolver=auth_resolver)
# Set the host
if dep_ref.host:
ado_downloader.github_host = dep_ref.host
# Build authenticated URL using the resolved per-dep token.
package_url = ado_downloader._build_repo_url(
dep_ref.repo_url, use_ssh=False, dep_ref=dep_ref, token=_url_token
)
# For generic hosts (not GitHub, not ADO), relax the env so native
# credential helpers (SSH keys, macOS Keychain, etc.) can work.
# This mirrors _clone_with_fallback() which does the same relaxation.
if is_generic:
validate_env = {k: v for k, v in ado_downloader.git_env.items()
if k not in ('GIT_ASKPASS', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM')}
validate_env['GIT_TERMINAL_PROMPT'] = '0'
else:
validate_env = {**os.environ, **ado_downloader.git_env}
if verbose_log:
verbose_log(f"Trying git ls-remote for {dep_ref.host}")
cmd = ["git", "ls-remote", "--heads", "--exit-code", package_url]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
timeout=30,
env=validate_env,
)
if verbose_log:
if result.returncode == 0:
verbose_log(f"git ls-remote rc=0 for {package}")
else:
# Sanitize stderr to avoid leaking tokens
stderr_snippet = (result.stderr or "").strip()[:200]
for env_var in ("GIT_ASKPASS", "GIT_CONFIG_GLOBAL"):
stderr_snippet = stderr_snippet.replace(
validate_env.get(env_var, ""), "***"
)
verbose_log(f"git ls-remote rc={result.returncode}: {stderr_snippet}")
return result.returncode == 0
# For GitHub.com, use AuthResolver with unauth-first fallback
host = dep_ref.host or default_host()
org = dep_ref.repo_url.split('/')[0] if dep_ref.repo_url and '/' in dep_ref.repo_url else None
host_info = auth_resolver.classify_host(host)
if verbose_log:
ctx = auth_resolver.resolve(host, org=org)
verbose_log(f"Auth resolved: host={host}, org={org}, source={ctx.source}, type={ctx.token_type}")
def _check_repo(token, git_env):
"""Check repo accessibility via GitHub API (or git ls-remote for non-GitHub)."""
import urllib.request
import urllib.error
api_base = host_info.api_base
api_url = f"{api_base}/repos/{dep_ref.repo_url}"
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "apm-cli",
}
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(api_url, headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=15)
if verbose_log:
verbose_log(f"API {api_url} -> {resp.status}")
return True
except urllib.error.HTTPError as e:
if verbose_log:
verbose_log(f"API {api_url} -> {e.code} {e.reason}")
if e.code == 404 and token:
# 404 with token could mean no access — raise to trigger fallback
raise RuntimeError(f"API returned {e.code}")
raise RuntimeError(f"API returned {e.code}: {e.reason}")
except Exception as e:
if verbose_log:
verbose_log(f"API request failed: {e}")
raise
try:
return auth_resolver.try_with_fallback(
host, _check_repo,
org=org,
repo_path=f"{dep_ref.repo_url}.git",
unauth_first=True,
verbose_callback=verbose_log,
)
except Exception:
if verbose_log:
try:
ctx = auth_resolver.build_error_context(host, f"accessing {package}", org=org)
for line in ctx.splitlines():
verbose_log(line)
except Exception:
pass
return False
except Exception:
# If parsing fails, assume it's a regular GitHub package
host = default_host()
org = package.split('/')[0] if '/' in package else None
repo_path = package # owner/repo format
def _check_repo_fallback(token, git_env):
import urllib.request
import urllib.error
host_info = auth_resolver.classify_host(host)
api_url = f"{host_info.api_base}/repos/{repo_path}"
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "apm-cli",
}
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(api_url, headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=15)
return True
except urllib.error.HTTPError as e:
if verbose_log:
verbose_log(f"API fallback -> {e.code} {e.reason}")
raise RuntimeError(f"API returned {e.code}")
except Exception as e:
if verbose_log:
verbose_log(f"API fallback failed: {e}")
raise
try:
return auth_resolver.try_with_fallback(
host, _check_repo_fallback,
org=org,
repo_path=f"{repo_path}.git",
unauth_first=True,
verbose_callback=verbose_log,
)
except Exception:
if verbose_log:
try:
ctx = auth_resolver.build_error_context(host, f"accessing {package}", org=org)
for line in ctx.splitlines():
verbose_log(line)
except Exception:
pass
return False
# ---------------------------------------------------------------------------
# Install command
# ---------------------------------------------------------------------------
@click.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("--force", is_flag=True, help="Overwrite locally-authored files on collision and deploy despite critical security findings")
@click.option("--verbose", "-v", is_flag=True, help="Show detailed installation information")
@click.option(
"--trust-transitive-mcp",
is_flag=True,
help="Trust self-defined MCP servers from transitive packages (skip re-declaration requirement)",
)
@click.option(
"--parallel-downloads",
type=int,
default=4,
show_default=True,
help="Max concurrent package downloads (0 to disable parallelism)",
)
@click.option(
"--dev",
is_flag=True,
default=False,
help="Install as development dependency (devDependencies)",
)
@click.option(
"--target",
"-t",
"target",
type=click.Choice(
["copilot", "claude", "cursor", "opencode", "codex", "vscode", "agents", "all"],
case_sensitive=False,
),
default=None,
help="Force deployment to a specific target (overrides auto-detection)",
)
@click.option(
"--global", "-g", "global_",
is_flag=True,
default=False,
help="Install to user scope (~/.apm/) instead of the current project",
)
@click.pass_context
def install(ctx, packages, runtime, exclude, only, update, dry_run, force, verbose, trust_transitive_mcp, parallel_downloads, dev, target, global_):
"""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.
The --only flag filters by dependency type (apm or mcp). Internally converted
to an InstallMode enum for type-safe dispatch.
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
apm install -g org/pkg1 # Install to user scope (~/.apm/)
"""
try:
# Create structured logger for install output early so exception
# handlers can always reference it (avoids UnboundLocalError if
# scope initialisation below throws).
is_partial = bool(packages)
logger = InstallLogger(verbose=verbose, dry_run=dry_run, partial=is_partial)
# Resolve scope
from ..core.scope import InstallScope, get_apm_dir, get_manifest_path, get_modules_dir, ensure_user_dirs, warn_unsupported_user_scope
scope = InstallScope.USER if global_ else InstallScope.PROJECT
if scope is InstallScope.USER:
ensure_user_dirs()
logger.progress("Installing to user scope (~/.apm/)")
_scope_warn = warn_unsupported_user_scope()
if _scope_warn:
logger.warning(_scope_warn)
# Scope-aware paths
manifest_path = get_manifest_path(scope)
apm_dir = get_apm_dir(scope)
# Display name for messages (short for project scope, full for user scope)
manifest_display = str(manifest_path) if scope is InstallScope.USER else APM_YML_FILENAME
# Create shared auth resolver for all downloads in this CLI invocation
# to ensure credentials are cached and reused (prevents duplicate auth popups)
auth_resolver = AuthResolver()
# Check if apm.yml exists
apm_yml_exists = manifest_path.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 if scope is InstallScope.PROJECT else Path.home().name
config = _get_default_config(project_name)
_create_minimal_apm_yml(config, target_path=manifest_path)
logger.success(f"Created {manifest_display}")
# Error when NO apm.yml AND NO packages
if not apm_yml_exists and not packages:
logger.error(f"No {manifest_display} found")
if scope is InstallScope.USER:
logger.progress("Run 'apm install -g <org/repo>' to auto-create + install")
else:
logger.progress("Run 'apm init' to create one, or:")
logger.progress(" 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, outcome = _validate_and_add_packages_to_apm_yml(
packages, dry_run, dev=dev, logger=logger,
manifest_path=manifest_path, auth_resolver=auth_resolver,
scope=scope,
)
# Short-circuit: all packages failed validation — nothing to install
if outcome.all_failed:
return
# 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
logger.resolution_start(
to_install_count=len(validated_packages) if packages else 0,
lockfile_count=0, # Refined later inside _install_apm_dependencies
)
# Parse apm.yml to get both APM and MCP dependencies
try:
apm_package = APMPackage.from_apm_yml(manifest_path)
except Exception as e:
logger.error(f"Failed to parse {manifest_display}: {e}")
sys.exit(1)
logger.verbose_detail(
f"Parsed {APM_YML_FILENAME}: {len(apm_package.get_apm_dependencies())} APM deps, "
f"{len(apm_package.get_mcp_dependencies())} MCP deps"
+ (f", {len(apm_package.get_dev_apm_dependencies())} dev deps"
if apm_package.get_dev_apm_dependencies() else "")
)
# Get APM and MCP dependencies
apm_deps = apm_package.get_apm_dependencies()
dev_apm_deps = apm_package.get_dev_apm_dependencies()
has_any_apm_deps = bool(apm_deps) or bool(dev_apm_deps)
mcp_deps = apm_package.get_mcp_dependencies()
# Convert --only string to InstallMode enum
if only is None:
install_mode = InstallMode.ALL
else:
install_mode = InstallMode(only)
# Determine what to install based on install mode
should_install_apm = install_mode != InstallMode.MCP
should_install_mcp = install_mode != InstallMode.APM
# MCP servers are workspace-scoped (.vscode/mcp.json); skip at user scope
if scope is InstallScope.USER:
should_install_mcp = False
if logger:
logger.verbose_detail(
"MCP servers skipped at user scope (workspace-scoped concept)"
)
# Show what will be installed if dry run
if dry_run:
logger.progress("Dry run mode - showing what would be installed:")
if should_install_apm and apm_deps:
logger.progress(f"APM dependencies ({len(apm_deps)}):")
for dep in apm_deps:
action = "update" if update else "install"
logger.progress(
f" - {dep.repo_url}#{dep.reference or 'main'} -> {action}"
)
if should_install_mcp and mcp_deps:
logger.progress(f"MCP dependencies ({len(mcp_deps)}):")
for dep in mcp_deps:
logger.progress(f" - {dep}")
if not apm_deps and not dev_apm_deps and not mcp_deps:
logger.progress("No dependencies found in apm.yml")
logger.success("Dry run complete - no changes made")
return
# Install APM dependencies first (if requested)
apm_count = 0
prompt_count = 0
agent_count = 0
# Migrate legacy apm.lock → apm.lock.yaml if needed (one-time, transparent)
migrate_lockfile_if_needed(apm_dir)
# Capture old MCP servers and configs from lockfile BEFORE
# _install_apm_dependencies regenerates it (which drops the fields).
# We always read this — even when --only=apm — so we can restore the
# field after the lockfile is regenerated by the APM install step.
old_mcp_servers: builtins.set = builtins.set()
old_mcp_configs: builtins.dict = {}
_lock_path = get_lockfile_path(apm_dir)
_existing_lock = LockFile.read(_lock_path)
if _existing_lock:
old_mcp_servers = builtins.set(_existing_lock.mcp_servers)
old_mcp_configs = builtins.dict(_existing_lock.mcp_configs)
apm_diagnostics = None
if should_install_apm and has_any_apm_deps:
if not APM_DEPS_AVAILABLE:
logger.error("APM dependency system not available")
logger.progress(f"Import error: {_APM_IMPORT_ERROR}")
sys.exit(1)
try:
# If specific packages were requested, only install those
# Otherwise install all from apm.yml.
# Use validated_packages (canonical strings) instead of
# raw packages (which may contain marketplace refs like
# NAME@MARKETPLACE that don't match resolved dep identities).
only_pkgs = builtins.list(validated_packages) if packages else None
install_result = _install_apm_dependencies(
apm_package, update, verbose, only_pkgs, force=force,
parallel_downloads=parallel_downloads,
logger=logger,
scope=scope,
auth_resolver=auth_resolver,
target=target,
marketplace_provenance=(
outcome.marketplace_provenance if packages and outcome else None
),
)
apm_count = install_result.installed_count
prompt_count = install_result.prompts_integrated
agent_count = install_result.agents_integrated
apm_diagnostics = install_result.diagnostics
except Exception as e:
logger.error(f"Failed to install APM dependencies: {e}")
if not verbose:
logger.progress("Run with --verbose for detailed diagnostics")
sys.exit(1)
elif should_install_apm and not has_any_apm_deps:
logger.verbose_detail("No APM dependencies found in apm.yml")
# When --update is used, package files on disk may have changed.
# Clear the parse cache so transitive MCP collection reads fresh data.
if update:
from apm_cli.models.apm_package import clear_apm_yml_cache
clear_apm_yml_cache()
# Collect transitive MCP dependencies from resolved APM packages
apm_modules_path = get_modules_dir(scope)
if should_install_mcp and apm_modules_path.exists():
lock_path = get_lockfile_path(apm_dir)
transitive_mcp = MCPIntegrator.collect_transitive(
apm_modules_path, lock_path, trust_transitive_mcp,
diagnostics=apm_diagnostics,
)
if transitive_mcp:
logger.verbose_detail(f"Collected {len(transitive_mcp)} transitive MCP dependency(ies)")
mcp_deps = MCPIntegrator.deduplicate(mcp_deps + transitive_mcp)
# Continue with MCP installation (existing logic)
mcp_count = 0
new_mcp_servers: builtins.set = builtins.set()
if should_install_mcp and mcp_deps:
mcp_count = MCPIntegrator.install(
mcp_deps, runtime, exclude, verbose,
stored_mcp_configs=old_mcp_configs,
diagnostics=apm_diagnostics,
)
new_mcp_servers = MCPIntegrator.get_server_names(mcp_deps)
new_mcp_configs = MCPIntegrator.get_server_configs(mcp_deps)
# Remove stale MCP servers that are no longer needed
stale_servers = old_mcp_servers - new_mcp_servers
if stale_servers:
MCPIntegrator.remove_stale(stale_servers, runtime, exclude)
# Persist the new MCP server set and configs in the lockfile
MCPIntegrator.update_lockfile(new_mcp_servers, mcp_configs=new_mcp_configs)
elif should_install_mcp and not mcp_deps:
# No MCP deps at all — remove any old APM-managed servers
if old_mcp_servers:
MCPIntegrator.remove_stale(old_mcp_servers, runtime, exclude)
MCPIntegrator.update_lockfile(builtins.set(), mcp_configs={})
logger.verbose_detail("No MCP dependencies found in apm.yml")
elif not should_install_mcp and old_mcp_servers:
# --only=apm: APM install regenerated the lockfile and dropped
# mcp_servers. Restore the previous set so it is not lost.
MCPIntegrator.update_lockfile(old_mcp_servers, mcp_configs=old_mcp_configs)
# Show diagnostics and final install summary
if apm_diagnostics and apm_diagnostics.has_diagnostics:
apm_diagnostics.render_summary()
else:
_rich_blank_line()
error_count = 0
if apm_diagnostics:
try:
error_count = int(apm_diagnostics.error_count)
except (TypeError, ValueError):
error_count = 0
logger.install_summary(apm_count=apm_count, mcp_count=mcp_count, errors=error_count)
# Hard-fail when critical security findings blocked any package.
# Consistent with apm unpack which also hard-fails on critical.
# Use --force to override.
if not force and apm_diagnostics and apm_diagnostics.has_critical_security:
sys.exit(1)
except Exception as e:
logger.error(f"Error installing dependencies: {e}")
if not verbose:
logger.progress("Run with --verbose for detailed diagnostics")
sys.exit(1)
# ---------------------------------------------------------------------------
# Install engine
# ---------------------------------------------------------------------------
def _pre_deploy_security_scan(
install_path: Path,
diagnostics: DiagnosticCollector,
package_name: str = "",
force: bool = False,
logger=None,
) -> bool:
"""Scan package source files for hidden characters BEFORE deployment.
Delegates to :class:`SecurityGate` for the scan->classify->decide pipeline.
Inline CLI feedback (error/info lines) is kept here because it is
install-specific formatting.
Returns:
True if deployment should proceed, False to block.
"""
from ..security.gate import BLOCK_POLICY, SecurityGate
verdict = SecurityGate.scan_files(
install_path, policy=BLOCK_POLICY, force=force
)
if not verdict.has_findings:
return True
# Record into diagnostics (consistent messaging via gate)
SecurityGate.report(verdict, diagnostics, package=package_name, force=force)
if verdict.should_block:
if logger:
logger.error(
f" Blocked: {package_name or 'package'} contains "
f"critical hidden character(s)"
)
logger.progress(f" └─ Inspect source: {install_path}")
logger.progress(" └─ Use --force to deploy anyway")
return False
return True
def _integrate_package_primitives(
package_info,
project_root,
*,
targets,
prompt_integrator,
agent_integrator,
skill_integrator,
instruction_integrator,
command_integrator,
hook_integrator,
force,
managed_files,
diagnostics,
package_name="",
logger=None,
scope=None,
):
"""Run the full integration pipeline for a single package.
Iterates over *targets* (``TargetProfile`` list) and dispatches each
primitive to the appropriate integrator via the target-driven API.
Skills are handled separately because ``SkillIntegrator`` already
routes across all targets internally.
When *scope* is ``InstallScope.USER``, targets and primitives that
do not support user-scope deployment are silently skipped.
Returns a dict with integration counters and the list of deployed file paths.
"""
from apm_cli.integration.dispatch import get_dispatch_table
_dispatch = get_dispatch_table()
result = {
"prompts": 0,
"agents": 0,
"skills": 0,
"sub_skills": 0,
"instructions": 0,
"commands": 0,
"hooks": 0,
"links_resolved": 0,
"deployed_files": [],
}
deployed = result["deployed_files"]
if not targets: