-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsetup_environment.py
More file actions
12052 lines (10159 loc) · 487 KB
/
Copy pathsetup_environment.py
File metadata and controls
12052 lines (10159 loc) · 487 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
"""
Cross-platform environment setup for Claude Code.
Downloads and configures development tools for Claude Code based on YAML configuration.
"""
# /// script
# dependencies = [
# "pyyaml",
# ]
# ///
import argparse
import concurrent.futures
import contextlib
import glob as glob_module
import gzip
import http.client
import json
import os
import platform
import random
import re
import shlex
import shutil
import ssl
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import zipfile
import zlib
from collections.abc import Callable
from dataclasses import dataclass
from dataclasses import field
from datetime import UTC
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from typing import NamedTuple
from typing import TextIO
from typing import TypeVar
from typing import cast
from urllib.request import Request
from urllib.request import urlopen
from urllib.request import urlretrieve
import yaml
# Import pwd module for Unix-like systems (used for detecting real user home under sudo)
# The import happens here but pwd is used in get_real_user_home() function
if sys.platform != 'win32':
pass # Used in get_real_user_home() for resolving sudo user's home directory
# Configuration inheritance constants
MAX_INHERITANCE_DEPTH = 10
INHERIT_KEY = 'inherit'
MERGE_KEYS_KEY = 'merge-keys'
# Keys eligible for selective merge during configuration inheritance.
# Only these top-level keys can be listed in the `merge-keys` directive.
MERGEABLE_CONFIG_KEYS: frozenset[str] = frozenset({
'dependencies',
'agents',
'slash-commands',
'rules',
'skills',
'files-to-download',
'hooks',
'mcp-servers',
'global-config',
'user-settings',
'env-variables',
'os-env-variables',
})
# Config keys containing file references (paths or URLs) that require
# resolution and validation. Used as a single source of truth for maintenance.
# Dot notation indicates nested keys (e.g., 'hooks.files' = hooks['files']).
#
# Access patterns differ per key type (simple list, dict-nested list,
# dict-nested scalar), so this constant serves as a registry, not a
# dispatch mechanism. validate_all_config_files() and
# _resolve_config_file_paths() handle type-specific extraction logic.
FILE_REFERENCE_KEYS: frozenset[str] = frozenset({
'agents', # list[str] -- simple string list
'slash-commands', # list[str] -- simple string list
'rules', # list[str] -- simple string list
'hooks.files', # list[str] -- nested under hooks dict
'files-to-download', # list[dict] -- each dict has 'source' key
'skills', # list[dict] -- each dict has 'base' key
'command-defaults.system-prompt', # str -- nested scalar under command-defaults
})
# Node.js installation constants (standalone -- no imports from install_claude.py)
MIN_NODE_VERSION = '18.0.0'
NODE_LTS_API = 'https://nodejs.org/dist/index.json'
# All valid top-level configuration keys for unknown key detection
KNOWN_CONFIG_KEYS: frozenset[str] = frozenset({
'name',
'version',
'inherit',
'merge-keys',
'command-names',
'base-url',
'claude-code-version',
'install-nodejs',
'link-projects-dir',
'dependencies',
'description',
'agents',
'slash-commands',
'rules',
'skills',
'files-to-download',
'global-config',
'hooks',
'mcp-servers',
'model',
'permissions',
'post-install-notes',
'env-variables',
'os-env-variables',
'command-defaults',
'user-settings',
'always-thinking-enabled',
'effort-level',
'company-announcements',
'attribution',
'status-line',
})
# Path prefixes indicating sensitive filesystem destinations
SENSITIVE_PATH_PREFIXES: tuple[str, ...] = (
'~/.ssh/',
'~/.gnupg/',
'~/.bashrc',
'~/.bash_profile',
'~/.profile',
'~/.zshrc',
'~/.config/',
)
# Mapping from platform.system() return values to dependency config keys.
# Used by collect_installation_plan(), install_dependencies(), and check_admin_needed()
# to determine which platform-specific dependencies apply to the current OS.
PLATFORM_SYSTEM_TO_CONFIG_KEY: dict[str, str] = {
'Windows': 'windows',
'Darwin': 'macos',
'Linux': 'linux',
}
# OS environment variables constants
OS_ENV_VARIABLES_KEY = 'os-env-variables'
ENV_VAR_MARKER_START = '# >>> claude-code-toolbox >>>'
ENV_VAR_MARKER_END = '# <<< claude-code-toolbox <<<'
# Per-path union whitelist used ONLY by the YAML inheritance layer
# (_resolve_single_key at lines 4331 and 4337) for child-overrides-parent
# composition semantics. On-disk writers (write_user_settings(),
# write_profile_settings_to_settings(), write_global_config()) use the
# default universal union-all-arrays semantics via
# _write_merged_json(array_union_keys=None) -- every array at every depth
# is unioned with structural dedupe, matching Claude Code CLI's
# cross-scope merge behavior.
DEFAULT_ARRAY_UNION_KEYS: set[str] = {
'permissions.allow',
'permissions.deny',
'permissions.ask',
}
# Keys that contain shell commands requiring tilde expansion
# These keys may reference file paths that need ~ expanded to absolute paths
# Uses expand_tildes_in_command() for consistent expansion (DRY with commit 46a086b)
TILDE_EXPANSION_KEYS: set[str] = {
'apiKeyHelper',
'awsCredentialExport',
}
# Keys that are NOT allowed in the user-settings section
# These keys have path resolution issues or are inherently profile-specific
USER_SETTINGS_EXCLUDED_KEYS: set[str] = {
'hooks', # Hooks require dedicated write logic with path resolution and type processing
'statusLine', # Path resolution issues; profile-specific display config
}
# Keys that are NOT allowed in the global-config section
# OAuth credentials must not appear in version-controlled YAML files
GLOBAL_CONFIG_EXCLUDED_KEYS: frozenset[str] = frozenset({
'oauthAccount',
})
# Mapping from root-level YAML keys to their user-settings equivalents
# Used for conflict detection between profile settings and user settings
# Root keys use kebab-case, user-settings uses camelCase (matching JSON schema)
ROOT_TO_USER_SETTINGS_KEY_MAP: dict[str, str] = {
'model': 'model', # Same in both
'permissions': 'permissions', # Same in both
'attribution': 'attribution', # Same in both
'always-thinking-enabled': 'alwaysThinkingEnabled',
'company-announcements': 'companyAnnouncements',
'env-variables': 'env', # Different names
'effort-level': 'effortLevel', # Adaptive reasoning effort
}
# Keys that are owned and written by the profile-settings subsystem.
# These keys are extracted from YAML root level and routed via
# create_profile_config() (isolated mode -> config.json) or
# write_profile_settings_to_settings() (non-isolated mode -> settings.json).
#
# Both writers are fed by the shared pure builder _build_profile_settings(),
# which performs kebab-to-camel translation. Values below are the POST-TRANSLATION
# camelCase keys as they appear in settings.json / config.json on disk.
#
# In non-isolated mode, write_profile_settings_to_settings() deep-merges the
# builder's delta into the shared ~/.claude/settings.json via
# _write_merged_json(), inheriting: deep-merge for nested dicts, array-union
# for permissions.allow/deny/ask, RFC 7396 null-as-delete for top-level and
# nested None values, and preservation for keys omitted from the delta.
# Keys not declared at YAML root level are PRESERVED in
# ~/.claude/settings.json (unchanged by this writer), including any
# prior-run contributions and any keys written by Step 14
# write_user_settings() under user-settings:.
PROFILE_OWNED_KEYS: frozenset[str] = frozenset({
'model',
'permissions',
'env',
'attribution',
'alwaysThinkingEnabled',
'effortLevel',
'companyAnnouncements',
'statusLine',
'hooks',
})
# Mapping from YAML root kebab-case key names to their on-disk camelCase
# equivalents for the 9 profile-owned keys. Used by main() to build the
# profile_config dict passed to _build_profile_settings(): dict membership
# encodes the "declared-vs-absent" distinction (which is lost by
# config.get() alone), and a YAML-level `model: null` declaration passes
# through as `profile_config['model'] = None`, which the builder forwards
# to the writer so _write_merged_json() can apply RFC 7396 null-as-delete
# to the shared settings.json.
#
# The mapping order matches PROFILE_OWNED_KEYS for visual clarity. It is
# SEPARATE from ROOT_TO_USER_SETTINGS_KEY_MAP (which covers 7 keys and
# drives detect_settings_conflicts()): this map intentionally includes
# `status-line` and `hooks` because they are profile-owned keys that
# participate in the null-as-delete contract even though they are
# excluded from the user-settings conflict surface.
_YAML_TO_CAMEL_PROFILE_KEYS: dict[str, str] = {
'model': 'model',
'permissions': 'permissions',
'env-variables': 'env',
'attribution': 'attribution',
'always-thinking-enabled': 'alwaysThinkingEnabled',
'effort-level': 'effortLevel',
'company-announcements': 'companyAnnouncements',
'status-line': 'statusLine',
'hooks': 'hooks',
}
# Platform-specific imports with proper type checking support
if sys.platform == 'win32':
import winreg
elif TYPE_CHECKING:
# This allows type checkers on non-Windows platforms to understand winreg types
import winreg # noqa: F401
# Helper function to detect if we're running in pytest
def is_running_in_pytest() -> bool:
"""Check if the script is running under pytest.
Returns:
True if running under pytest, False otherwise.
"""
return 'pytest' in sys.modules or 'py.test' in sys.argv[0]
def is_debug_enabled() -> bool:
"""Check if debug logging is enabled via environment variable.
Returns:
True if CLAUDE_CODE_TOOLBOX_DEBUG is set to '1', 'true', or 'yes' (case-insensitive)
"""
debug_value = os.environ.get('CLAUDE_CODE_TOOLBOX_DEBUG', '').lower()
return debug_value in ('1', 'true', 'yes')
def debug_log(message: str) -> None:
"""Log debug message if debug mode is enabled.
Args:
message: Debug message to log
"""
if is_debug_enabled():
# Use distinct prefix for easy filtering
print(f' [DEBUG] {message}', file=sys.stderr)
# Parallel execution helpers
# Type variable for generic parallel execution
T = TypeVar('T')
R = TypeVar('R')
# Type alias for JSON-compatible values used in deep merge operations
# Recursive type representing dict, list, or primitive values
type JsonValue = str | int | float | bool | None | list['JsonValue'] | dict[str, 'JsonValue']
# Default number of parallel workers - can be overridden via CLAUDE_CODE_TOOLBOX_PARALLEL_WORKERS env var
# Reduced from 5 to 2 to decrease likelihood of hitting GitHub secondary rate limits
DEFAULT_PARALLEL_WORKERS = int(os.environ.get('CLAUDE_CODE_TOOLBOX_PARALLEL_WORKERS', '2'))
def is_parallel_mode_enabled() -> bool:
"""Check if parallel execution is enabled.
Returns:
True if parallel mode is enabled (default), False if CLAUDE_CODE_TOOLBOX_SEQUENTIAL_MODE=1
"""
sequential_mode = os.environ.get('CLAUDE_CODE_TOOLBOX_SEQUENTIAL_MODE', '').lower()
return sequential_mode not in ('1', 'true', 'yes')
def execute_parallel(
items: list[T],
func: Callable[[T], R],
max_workers: int = DEFAULT_PARALLEL_WORKERS,
stagger_delay: float = 0.0,
) -> list[R]:
"""Execute a function on items in parallel with error isolation.
Processes items using ThreadPoolExecutor when parallel mode is enabled,
or sequentially when CLAUDE_CODE_TOOLBOX_SEQUENTIAL_MODE=1.
Args:
items: List of items to process
func: Function to apply to each item
max_workers: Maximum number of parallel workers (default: 2)
stagger_delay: Delay in seconds between task submissions to prevent
thundering herd on rate-limited APIs (default: 0.0)
Returns:
List of results in the same order as input items.
If an item raises an exception, that exception is stored in the result list
and re-raised after all items are processed.
"""
import operator
if not items:
return []
# Sequential mode fallback
if not is_parallel_mode_enabled():
debug_log('Sequential mode enabled, processing items sequentially')
return [func(item) for item in items]
# Parallel execution
debug_log(f'Parallel mode enabled, processing {len(items)} items with {max_workers} workers')
results_with_index: list[tuple[int, R | BaseException]] = []
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
# Submit tasks with optional stagger delay to prevent thundering herd
future_to_index: dict[concurrent.futures.Future[R], int] = {}
for idx, item in enumerate(items):
future_to_index[executor.submit(func, item)] = idx
if stagger_delay > 0 and idx < len(items) - 1:
time.sleep(stagger_delay)
# Collect results as they complete
for future in concurrent.futures.as_completed(future_to_index):
idx = future_to_index[future]
try:
result = future.result()
results_with_index.append((idx, result))
except Exception as task_exc:
# Store exception to maintain order and allow partial results
results_with_index.append((idx, task_exc))
# Sort by original index to maintain order
results_with_index.sort(key=operator.itemgetter(0))
# Extract results, re-raising any exceptions
final_results: list[R] = []
exceptions: list[tuple[int, BaseException]] = []
for idx, result_or_exc in results_with_index:
if isinstance(result_or_exc, BaseException):
exceptions.append((idx, result_or_exc))
else:
final_results.append(result_or_exc)
# If there were exceptions, raise the first one after logging all
if exceptions:
for exc_idx, stored_exc in exceptions:
debug_log(f'Item {exc_idx} raised exception: {stored_exc}')
# Re-raise the first exception
raise exceptions[0][1]
return final_results
def execute_parallel_safe(
items: list[T],
func: Callable[[T], R],
default_on_error: R,
max_workers: int = DEFAULT_PARALLEL_WORKERS,
stagger_delay: float = 0.0,
) -> list[R]:
"""Execute a function on items in parallel with error handling.
Unlike execute_parallel, this function catches exceptions and returns
a default value for failed items, allowing partial success.
Args:
items: List of items to process
func: Function to apply to each item
default_on_error: Value to return for items that raise exceptions
max_workers: Maximum number of parallel workers (default: 2)
stagger_delay: Delay in seconds between task submissions to prevent
thundering herd on rate-limited APIs (default: 0.0)
Returns:
List of results in the same order as input items.
Failed items return default_on_error instead of their result.
"""
if not items:
return []
def safe_func(item: T) -> R:
try:
return func(item)
except Exception as exc:
debug_log(f'Item processing failed: {exc}')
return default_on_error
return execute_parallel(items, safe_func, max_workers, stagger_delay=stagger_delay)
# Windows UAC elevation helper functions
def is_admin() -> bool:
"""Check if running with admin privileges on Windows.
Returns:
True if running as admin or not on Windows, False otherwise.
"""
if platform.system() != 'Windows':
return True # Not Windows, no admin check needed
try:
import ctypes
# Use getattr to access Windows-specific attributes dynamically
# This prevents type checkers from failing on non-Windows platforms
windll = getattr(ctypes, 'windll', None)
if windll is None:
return False
shell32 = getattr(windll, 'shell32', None)
if shell32 is None:
return False
is_user_admin = getattr(shell32, 'IsUserAnAdmin', None)
if is_user_admin is None:
return False
return bool(is_user_admin())
except Exception:
return False
def request_admin_elevation(script_args: list[str] | None = None) -> None:
"""Re-launch script with UAC elevation on Windows.
Args:
script_args: Optional list of arguments to pass to elevated script.
"""
if platform.system() != 'Windows':
return
try:
import ctypes
# Collect critical environment variables to pass to elevated process
env_vars_to_pass: list[str] = []
critical_env_vars = [
'CLAUDE_CODE_TOOLBOX_ENV_CONFIG',
'GITHUB_TOKEN',
'GITLAB_TOKEN',
'REPO_TOKEN',
'CLAUDE_CODE_TOOLBOX_VERSION',
'CLAUDE_CODE_TOOLBOX_CONFIRM_INSTALL',
'CLAUDE_CODE_TOOLBOX_DRY_RUN',
'CLAUDE_CODE_TOOLBOX_SKIP_INSTALL',
'CLAUDE_CODE_TOOLBOX_NO_ADMIN',
'CLAUDE_CODE_TOOLBOX_ENV_AUTH',
]
for var_name in critical_env_vars:
var_value = os.environ.get(var_name)
if var_value:
# Don't escape here - we'll handle escaping when building the params string
env_vars_to_pass.append(f'--env-{var_name}={var_value}')
# Build command line with script path, environment variables, then original arguments
# Important: sys.argv[0] is the script path, sys.argv[1:] are the actual arguments
# Add special flag to indicate UAC elevation created a new window
uac_flag = ['--elevated-via-uac']
if script_args:
# When script_args is provided, use it instead of sys.argv[1:]
all_args = [sys.argv[0]] + env_vars_to_pass + uac_flag + script_args
else:
# Use original arguments (excluding script path)
all_args = [sys.argv[0]] + env_vars_to_pass + uac_flag + sys.argv[1:]
# Build parameters string with proper quoting for Windows
# Quote each argument that contains spaces or special characters
params_list: list[str] = []
for arg in all_args:
# Always quote arguments with = to ensure proper parsing
if ' ' in arg or '"' in arg or '=' in arg or arg.startswith('--env-'):
# For Windows command line, we need to escape quotes properly
# Use \" for quotes inside quoted strings
escaped_arg = arg.replace('"', '\\"')
quoted_arg = f'"{escaped_arg}"'
params_list.append(quoted_arg)
else:
params_list.append(arg)
params = ' '.join(params_list)
# Use getattr to access Windows-specific attributes dynamically
windll = getattr(ctypes, 'windll', None)
if windll is None:
return
shell32 = getattr(windll, 'shell32', None)
if shell32 is None:
return
shell_execute_w = getattr(shell32, 'ShellExecuteW', None)
if shell_execute_w is None:
return
# Request elevation
result = shell_execute_w(
None,
'runas',
sys.executable,
params,
None,
1,
)
# Exit current process if elevation was requested
if result > 32: # Success
# Show message that elevated window is opening
print()
info('Administrator privileges granted!')
info('A new window is opening with elevated privileges...')
info('Please check the new window to see the setup progress.')
print()
# Wait briefly to ensure elevated process starts
time.sleep(1.0)
# Exit the non-elevated process so only the elevated one continues
sys.exit(0)
else:
# Elevation was denied or failed
error('Administrator elevation was denied')
error('Installation cannot proceed without administrator privileges')
error('')
error('Please run this script as administrator manually:')
error(' 1. Right-click on your terminal')
error(' 2. Select "Run as administrator"')
error(' 3. Run the setup command again')
sys.exit(1)
except Exception as e:
# If elevation fails due to an error, report it
error(f'Failed to request elevation: {e}')
error('Please run this script as administrator manually')
sys.exit(1)
def _is_global_npm_install(dep: str) -> bool:
"""Check if a dependency command is a global npm package installation.
Global npm installs write to the npm global prefix, which may require
elevated privileges (admin on Windows, sudo on Unix-like systems).
Args:
dep: Dependency command string from the configuration.
Returns:
True if the command installs an npm package globally.
"""
return 'npm install -g' in dep
def _contains_shell_control_chars(command: str) -> bool:
"""Check if a command string contains shell control characters.
Commands containing these characters can chain commands, redirect
output, or expand variables, so they must never be re-executed with
elevated privileges.
Args:
command: Shell command string to inspect.
Returns:
True if the command contains any shell control character.
"""
return any(char in command for char in ';&|<>$`\n')
def check_admin_needed(config: dict[str, Any], args: argparse.Namespace) -> bool:
"""Check if admin rights are needed for the current operation.
Args:
config: Configuration dictionary.
args: Command line arguments.
Returns:
True if admin needed, False otherwise.
"""
if platform.system() != 'Windows':
return False
# Check if Claude Code installation is needed
if not args.skip_install:
# Installing Node.js and Git typically requires admin on Windows
return True
# Check for dependencies that need admin
dependencies = config.get('dependencies', {})
if dependencies:
# Check current platform + common dependencies
current_platform_key = PLATFORM_SYSTEM_TO_CONFIG_KEY.get(platform.system())
platform_deps = dependencies.get(current_platform_key, []) if current_platform_key else []
common_deps = dependencies.get('common', [])
all_deps = list(platform_deps) + list(common_deps)
for dep in all_deps:
# Check for commands that typically need admin
if 'winget' in dep and '--scope machine' in dep:
return True
if _is_global_npm_install(dep):
# Global npm installs may need admin depending on Node.js installation
return True
return False
# ANSI color codes for pretty output
@dataclass(frozen=True)
class InheritanceChainEntry:
"""Single entry in the configuration inheritance chain."""
source: str
source_type: str # 'url', 'local', 'repo'
name: str
@dataclass
class InstallationPlan:
"""Structured representation of what the setup will install.
Separates data collection from display logic, enabling testability
and reuse between pre-install summary and post-install report.
"""
# Config metadata
config_name: str
config_source: str
config_source_type: str # 'url', 'local', 'repo'
config_version: str | None
config_description: str | None = None
# Inheritance chain (root ancestor first, current config last)
inheritance_chain: list[InheritanceChainEntry] = field(
default_factory=lambda: list[InheritanceChainEntry](),
)
# Resources by category
agents: list[str] = field(default_factory=lambda: list[str]())
slash_commands: list[str] = field(default_factory=lambda: list[str]())
rules: list[str] = field(default_factory=lambda: list[str]())
skills: list[dict[str, Any]] = field(default_factory=lambda: list[dict[str, Any]]())
files_to_download: list[dict[str, Any]] = field(
default_factory=lambda: list[dict[str, Any]](),
)
hooks_files: list[str] = field(default_factory=lambda: list[str]())
hooks_events: list[dict[str, Any]] = field(
default_factory=lambda: list[dict[str, Any]](),
)
mcp_servers: list[dict[str, Any]] = field(
default_factory=lambda: list[dict[str, Any]](),
)
# Dependency commands by platform
dependency_commands: dict[str, list[str]] = field(
default_factory=lambda: dict[str, list[str]](),
)
# Settings
model: str | None = None
system_prompt: str | None = None
system_prompt_mode: str = 'replace'
command_names: list[str] = field(default_factory=lambda: list[str]())
claude_code_version: str | None = None
install_nodejs: bool = False
skip_install: bool = False
permissions: dict[str, Any] | None = None
env_variables: dict[str, str | None] | None = None
os_env_variables: dict[str, Any] | None = None
user_settings: dict[str, Any] | None = None
global_config: dict[str, Any] | None = None
always_thinking_enabled: bool | None = None
effort_level: str | None = None
company_announcements: list[str] | None = None
attribution: dict[str, str] | None = None
status_line: dict[str, Any] | None = None
# Security analysis
unknown_keys: list[str] = field(default_factory=lambda: list[str]())
sensitive_paths: list[str] = field(default_factory=lambda: list[str]())
# Auto-injected items (auto-update controls)
auto_injected_items: list[str] = field(default_factory=lambda: list[str]())
@property
def total_resources(self) -> int:
"""Total count of downloadable resources."""
return (
len(self.agents)
+ len(self.slash_commands)
+ len(self.rules)
+ len(self.skills)
+ len(self.files_to_download)
+ len(self.hooks_files)
+ len(self.mcp_servers)
)
@property
def has_security_concerns(self) -> bool:
"""Whether any security attention items exist."""
return bool(
self.dependency_commands
or self.unknown_keys
or self.sensitive_paths
or self.hooks_events,
)
class Colors:
"""ANSI color codes for terminal output."""
_RED = '\033[0;31m'
_GREEN = '\033[0;32m'
_YELLOW = '\033[1;33m'
_BLUE = '\033[0;34m'
_CYAN = '\033[0;36m'
_NC = '\033[0m' # No Color
_BOLD = '\033[1m'
# Check if colors should be disabled
_NO_COLOR = platform.system() == 'Windows' and not os.environ.get('WT_SESSION')
# Public color attributes (computed properties)
RED = '' if _NO_COLOR else _RED
GREEN = '' if _NO_COLOR else _GREEN
YELLOW = '' if _NO_COLOR else _YELLOW
BLUE = '' if _NO_COLOR else _BLUE
CYAN = '' if _NO_COLOR else _CYAN
NC = '' if _NO_COLOR else _NC
BOLD = '' if _NO_COLOR else _BOLD
@classmethod
def strip(cls) -> None:
"""Strip ANSI color codes for environments that don't support them."""
if platform.system() == 'Windows' and not os.environ.get('WT_SESSION'):
# Use setattr for dynamic attribute assignment on class variables
for attr in ['RED', 'GREEN', 'YELLOW', 'BLUE', 'CYAN', 'NC', 'BOLD']:
setattr(cls, attr, '')
# Logging functions
def info(msg: str) -> None:
"""Print info message."""
print(f' {Colors.YELLOW}INFO:{Colors.NC} {msg}')
def success(msg: str) -> None:
"""Print success message."""
print(f' {Colors.GREEN}OK:{Colors.NC} {msg}')
def warning(msg: str) -> None:
"""Print warning message."""
print(f' {Colors.YELLOW}WARN:{Colors.NC} {msg}')
def error(msg: str) -> None:
"""Print error message."""
print(f' {Colors.RED}ERROR:{Colors.NC} {msg}', file=sys.stderr)
def header(environment_name: str = 'Development') -> None:
"""Print setup header."""
print()
print(f'{Colors.BLUE}========================================================================{Colors.NC}')
print(f'{Colors.BLUE} Claude Code {environment_name} Environment Setup{Colors.NC}')
print(f'{Colors.BLUE}========================================================================{Colors.NC}')
print()
def _prefer_windows_executable(cmd: str, resolved: str | None) -> str | None:
"""Prefer a launchable Windows wrapper over an extensionless shim.
``shutil.which()`` can resolve a command to the extensionless Unix shell
shim that Node.js ships beside its Windows wrapper (for example the ``npm``
script next to ``npm.cmd``). ``subprocess.run(..., shell=False)`` launches
resolved paths through ``CreateProcess``, which cannot execute such a shim
and fails with ``OSError`` ``[WinError 193] %1 is not a valid Win32
application``. On Python builds before the gh-109590 fix (Windows
``shutil.which`` on CPython 3.12.0 and every 3.11-or-earlier release), the
bare command name is probed ahead of the PATHEXT variants, so the shim
wins. When ``resolved`` lacks an executable extension, fall back to the
``.exe``/``.cmd``/``.bat``/``.com`` sibling that Windows can launch.
Args:
cmd: The command name originally passed to ``shutil.which()``.
resolved: The path ``shutil.which(cmd)`` returned (possibly ``None``).
Returns:
A launchable executable path when one is found, otherwise ``resolved``.
"""
executable_suffixes = ('.exe', '.cmd', '.bat', '.com')
if resolved and Path(resolved).suffix.lower() in executable_suffixes:
return resolved
# ``resolved`` is missing or a non-launchable shim. Probe each executable
# extension explicitly: appending a PATHEXT extension makes shutil.which()
# return the direct wrapper match on every Python version.
for suffix in executable_suffixes:
wrapper = shutil.which(cmd + suffix)
if wrapper:
return wrapper
return resolved
def run_command(cmd: list[str], capture_output: bool = True, **kwargs: Any) -> subprocess.CompletedProcess[str]:
"""Run a command and return the result."""
try:
# On Windows, resolve the executable to a full path that CreateProcess
# can launch. subprocess.run(shell=False) cannot run a command by bare
# name, and shutil.which() may resolve npm/npx to the extensionless Unix
# shim shipped beside the .cmd wrapper -- launching that shim raises
# WinError 193. _prefer_windows_executable() returns the .cmd/.exe
# wrapper instead so batch-based tools (npm, npx) run correctly.
if sys.platform == 'win32' and cmd:
resolved = _prefer_windows_executable(cmd[0], shutil.which(cmd[0]))
if resolved:
cmd = [resolved] + cmd[1:]
return subprocess.run(
cmd,
capture_output=capture_output,
text=True,
**kwargs,
)
except FileNotFoundError:
return subprocess.CompletedProcess(cmd, 1, '', f'Command not found: {cmd[0]}')
except OSError as exc:
# A non-launchable executable (e.g. WinError 193 from a stray shim) must
# not abort the whole setup: report it as a failed command so callers
# can continue and record the failure, mirroring the FileNotFoundError
# handling above.
return subprocess.CompletedProcess(cmd, 1, '', f'Failed to run {cmd[0]}: {exc}')
def _dev_tty_sudo_available() -> bool:
"""Check if sudo can acquire credentials via /dev/tty in non-interactive mode.
When stdin is piped (e.g., curl | bash), sudo cannot prompt via stdin.
However, if /dev/tty is available, sudo can be invoked with stdin
redirected from /dev/tty to prompt the user directly on the terminal.
Returns:
True if /dev/tty is available and sudo can be used through it,
False otherwise.
"""
if sys.platform != 'win32':
try:
with open('/dev/tty'):
return True
except OSError:
pass
return False
def _run_with_sudo_fallback(
cmd: list[str],
*,
capture_output: bool = True,
timeout: int = 30,
tty_timeout: int = 60,
) -> subprocess.CompletedProcess[str] | None:
"""Run a command with sudo, using a three-tier fallback strategy.
Tier 1: Interactive mode (stdin is a TTY) -- sudo prompts directly.
Tier 2: Cached credentials (sudo -n true succeeds) -- sudo without prompt.
Tier 3: /dev/tty available -- sudo with stdin redirected from /dev/tty.
If all tiers fail, returns None without running the command.
Args:
cmd: Command to execute with sudo prepended
(e.g., ['npm', 'uninstall', '-g', 'pkg']).
capture_output: Whether to capture stdout/stderr.
timeout: Timeout in seconds for Tier 1 and Tier 2 attempts.
tty_timeout: Timeout for Tier 3 (/dev/tty) attempt. Longer because
the user may need time to type their password.
Returns:
CompletedProcess if sudo was attempted (check returncode for success),
None if no sudo mechanism was available.
"""
if sys.platform != 'win32':
sudo_cmd = ['sudo'] + cmd
# Tier 1: Interactive mode -- user can enter password at stdin
if sys.stdin.isatty():
try:
return subprocess.run(
sudo_cmd,
capture_output=capture_output,
encoding='utf-8',
errors='replace',
timeout=timeout,
)
except subprocess.TimeoutExpired:
warning(f'Sudo command timed out after {timeout} seconds')
return None
except FileNotFoundError:
warning('sudo command not found')
return None
# Tier 2: Non-interactive with cached credentials
try:
cred_check = subprocess.run(
['sudo', '-n', 'true'],
capture_output=True,
timeout=5,
)
if cred_check.returncode == 0:
try:
return subprocess.run(
sudo_cmd,
capture_output=capture_output,
encoding='utf-8',
errors='replace',
timeout=timeout,
)
except subprocess.TimeoutExpired:
warning(f'Sudo command timed out after {timeout} seconds')
return None
except FileNotFoundError:
return None
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Tier 3: /dev/tty available -- redirect sudo stdin from terminal
if _dev_tty_sudo_available():
info('Terminal available via /dev/tty - attempting sudo with terminal prompt...')
try:
with open('/dev/tty') as tty:
return subprocess.run(
sudo_cmd,
stdin=tty,
capture_output=capture_output,
encoding='utf-8',
errors='replace',
timeout=tty_timeout,
)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
pass
# Windows or all tiers exhausted
return None
def find_command(cmd: str, fallback_paths: list[str] | None = None) -> str | None:
"""Find a command with robust platform-specific fallback search.
For the 'claude' command, checks the native installer target path first
to ensure the native binary is preferred over npm even when PATH ordering