mise 2026.9.4

Dev tools, env vars, and tasks in one CLI
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;

use eyre::Result;
use eyre::WrapErr;
use indexmap::IndexSet;
use itertools::Itertools;
use tokio::sync::OnceCell;
use tokio::sync::{Mutex, Semaphore};
use tokio::task::JoinSet;

use crate::config::Config;
use crate::config::settings::Settings;
use crate::errors::Error;
use crate::hooks::{Hooks, InstalledToolInfo};
use crate::install_context::{InstallContext, install_dependency_declarations};
use crate::plugins::PluginType;
use crate::registry::REGISTRY;
use crate::toolset::Toolset;
use crate::toolset::helpers::{preflight_system_deps, show_python_install_hint};
use crate::toolset::install_options::InstallOptions;
use crate::toolset::tool_deps::{ToolDeps, ensure_compatible_install_requests, tool_key};
use crate::toolset::tool_request::ToolRequest;
use crate::toolset::tool_source::ToolSource;
use crate::toolset::tool_version::{ResolveOptions, ToolVersion};
use crate::ui::install_progress::{InstallProgress, ToolProgress, install_progress};
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::{backend, config, hooks, runtime_symlinks, shims};

impl Toolset {
    async fn missing_lazy_bin_provider(
        &self,
        config: &Arc<Config>,
        bin_name: &str,
    ) -> Result<Option<ToolVersion>> {
        let mut providers = self
            .list_missing_versions_for_install(config)
            .await
            .into_iter()
            .filter_map(|tv| {
                let options = tv.request.options();
                if options.lazy == Some(true) {
                    match tv.request.lazy_bins() {
                        Ok(Some(bins))
                            if bins.iter().any(|bin| lazy_bin_names_eq(bin, bin_name)) =>
                        {
                            Some(Ok(tv))
                        }
                        Ok(_) => None,
                        // Missing metadata for one lazy declaration says nothing
                        // about whether another declaration provides this command.
                        // ensure_lazy_shims reports that declaration's error while
                        // still materializing the valid providers' shims.
                        Err(_) => None,
                    }
                } else if tv.ba().matches_bin_name(bin_name)
                    || tv
                        .ba()
                        .registry_tool()
                        .is_some_and(|tool| tool.provides_bin(bin_name))
                {
                    Some(Ok(tv))
                } else {
                    None
                }
            })
            .map(|tv| tv.and_then(|tv| Ok((tv.backend()?, tv))))
            .collect::<Result<Vec<_>>>()?;
        Self::sort_by_overrides(&mut providers)?;
        Ok(providers
            .into_iter()
            .next()
            .and_then(|(_, tv)| (tv.request.options().lazy == Some(true)).then_some(tv)))
    }

    pub(crate) async fn has_missing_lazy_bin_provider(
        &self,
        config: &Arc<Config>,
        bin_name: &str,
    ) -> Result<bool> {
        Ok(self
            .missing_lazy_bin_provider(config, bin_name)
            .await?
            .is_some())
    }

    /// A lazy tool's dependencies are commonly lazy themselves, so nothing else
    /// installs them and the provider alone fails its dependency preflight.
    async fn lazy_install_requests(
        &self,
        config: &Arc<Config>,
        tv: &ToolVersion,
    ) -> Vec<ToolRequest> {
        let missing = self.list_missing_versions_for_install(config).await;
        let mut requests = vec![tv.request.clone()];
        let mut next = 0;
        while next < requests.len() {
            let declarations = install_dependency_declarations(&requests[next]);
            next += 1;
            for candidate in &missing {
                // Keyed on the request, not the backend: the preflight requires every
                // configured version of a dependency, not just the first one.
                if declarations.matches(candidate.ba()) && !requests.contains(&candidate.request) {
                    requests.push(candidate.request.clone());
                }
            }
        }
        requests
    }

    pub(crate) async fn install_missing_lazy_bin(
        &mut self,
        config: &mut Arc<Config>,
        bin_name: &str,
    ) -> Result<Option<Vec<ToolVersion>>> {
        let Some(tv) = self.missing_lazy_bin_provider(config, bin_name).await? else {
            return Ok(None);
        };
        // The batch can span scopes, so each tool resolves its own destination rather
        // than inheriting the provider's. The provider's own directory is still needed
        // to explain a failure that is caused by writing outside the user's install dir.
        let provider_install_dir = scope_installs_dir(&tv.request);
        let install_options = InstallOptions {
            reason: "lazy shim".into(),
            scoped_install_dirs: true,
            ..Default::default()
        };
        let requests = self.lazy_install_requests(config, &tv).await;
        let installed = self
            .install_all_versions(config, requests, &install_options)
            .await
            .wrap_err_with(|| {
                provider_install_dir.as_ref().map_or_else(
                    || format!("failed to install lazy tool {}", tv.style()),
                    |dir| {
                        format!(
                            "failed to install lazy tool {} into {}. Preinstall it with appropriate privileges or set system_installs_dir to a writable directory",
                            tv.style(),
                            crate::file::display_path(dir)
                        )
                    },
                )
            })?;
        if !installed.is_empty() {
            let ts = config.get_toolset().await?;
            config::rebuild_shims_and_runtime_symlinks(
                config,
                ts,
                &installed,
                crate::lockfile::LockfileUpdateMode::Normal,
            )
            .await?;
        }
        Ok(Some(installed))
    }

    pub(crate) async fn should_install_missing_registry_bin_provider(
        &self,
        config: &Arc<Config>,
        bin_name: &str,
    ) -> Result<bool> {
        let mut providers = vec![];
        for (backend, tv) in self.list_current_versions() {
            if backend.is_version_installed(config, &tv, true) {
                if backend
                    .which(config, &tv, bin_name)
                    .await
                    .ok()
                    .flatten()
                    .is_some()
                {
                    providers.push((backend, tv));
                }
            } else if REGISTRY
                .get(&tv.ba().short)
                .is_some_and(|tool| tool.provides_bin(bin_name))
                && match &Settings::get().auto_install_disable_tools {
                    Some(disable_tools) => !disable_tools.contains(&tv.ba().short),
                    None => true,
                }
            {
                providers.push((backend, tv));
            }
        }
        Self::sort_by_overrides(&mut providers)?;
        Ok(providers.first().is_some_and(|(backend, tv)| {
            !backend.is_version_installed(config, tv, true)
                && REGISTRY
                    .get(&tv.ba().short)
                    .is_some_and(|tool| tool.provides_bin(bin_name))
        }))
    }

    #[async_backtrace::framed]
    /// Installs missing tool versions and returns (installed_versions, still_missing_versions).
    /// This avoids callers needing to re-compute the missing versions list.
    pub async fn install_missing_versions(
        &mut self,
        config: &mut Arc<Config>,
        opts: &InstallOptions,
    ) -> Result<(Vec<ToolVersion>, Vec<ToolVersion>)> {
        let missing = self.list_missing_versions_for_install(config).await;

        // If auto-install is explicitly disabled, skip installation but return what's missing
        if opts.skip_auto_install {
            return Ok((vec![], missing));
        }

        let mut versions = missing
            .iter()
            .filter(|tv| tv.request.options().lazy != Some(true) || opts.include_lazy)
            .filter(|tv| {
                !opts.missing_args_only
                    || matches!(self.versions[tv.ba()].source, ToolSource::Argument)
            })
            .filter(|tv| {
                if let Some(tools) = &opts.auto_install_disable_tools {
                    !tools.contains(&tv.ba().short)
                } else {
                    true
                }
            })
            .map(|tv| tv.request.clone())
            .collect_vec();
        // Ensure options from toolset are preserved during auto-install
        self.init_request_options(&mut versions);
        let installed = self.install_all_versions(config, versions, opts).await?;
        if opts.dry_run {
            // Dry-run install results describe the planned installs. They are not
            // present on disk, so rebuilding shims/runtime symlinks or updating
            // lockfiles for them would both mutate state and advertise tools that
            // cannot be executed.
            return Ok((installed, missing));
        }
        if !installed.is_empty() {
            let ts = config.get_toolset().await?;
            config::rebuild_shims_and_runtime_symlinks(
                config,
                ts,
                &installed,
                crate::lockfile::LockfileUpdateMode::Normal,
            )
            .await?;
            // Re-check what's still missing after installation
            let still_missing = self.list_missing_versions_for_install(config).await;
            return Ok((installed, still_missing));
        }
        // Nothing was installed, the missing list is unchanged
        Ok((installed, missing))
    }

    /// sets the options on incoming requests to install to whatever is already in the toolset
    /// this handles the use-case where you run `mise use ubi:cilium/cilium-cli` (without CLi options)
    /// but this tool has options inside mise.toml
    pub(super) fn init_request_options(&self, requests: &mut Vec<ToolRequest>) {
        for tr in requests {
            if let Some(tvl) = self.versions.get(tr.ba()) {
                // Requests cloned from this toolset already carry their own
                // per-entry options, including platform filters. Do not
                // collapse duplicate selectors onto another config entry.
                if tvl.requests.contains(tr) {
                    continue;
                }
                // Use matching config options when available. If selection is
                // ambiguous, preserve options already carried by the request.
                if let Some(config_options) =
                    super::tool_request_set::configured_options_for_runtime_request(
                        &tvl.requests,
                        tr,
                    )
                {
                    tr.apply_config_options(config_options);
                }
            }
        }
    }

    #[async_backtrace::framed]
    pub async fn install_all_versions(
        &mut self,
        config: &mut Arc<Config>,
        versions: Vec<ToolRequest>,
        opts: &InstallOptions,
    ) -> Result<Vec<ToolVersion>> {
        self.install_all_versions_with_progress(config, versions, opts, None)
            .await
    }

    pub(crate) async fn install_all_versions_with_progress(
        &mut self,
        config: &mut Arc<Config>,
        mut versions: Vec<ToolRequest>,
        opts: &InstallOptions,
        progress: Option<Box<dyn InstallProgress>>,
    ) -> Result<Vec<ToolVersion>> {
        if versions.is_empty() {
            // Configured plugins are still installed when no tools need work
            // (for example, env-only plugins).
            Self::ensure_config_plugins_installed(config, opts.dry_run).await?;
            return Ok(vec![]);
        }

        self.init_request_options(&mut versions);
        ensure_compatible_install_requests(&versions)?;
        ensure_safe_install_options(&versions)?;

        // Validate shared install destinations before plugin installation or
        // hooks introduce side effects.
        Self::ensure_config_plugins_installed(config, opts.dry_run).await?;

        // Initialize a footer for the entire install session once (before batching)
        let mpr = MultiProgressReport::get();
        let footer_reason = if opts.dry_run {
            format!("{} (dry-run)", opts.reason)
        } else {
            opts.reason.clone()
        };
        let mut install_progress = progress.or_else(|| {
            (!opts.raw && !opts.dry_run)
                .then(|| {
                    install_progress(
                        &mpr,
                        versions.iter().map(|tr| (tool_key(tr), tr.to_string())),
                    )
                })
                .flatten()
        });
        if install_progress.is_none() {
            mpr.init_footer(opts.dry_run, &footer_reason, versions.len());
        }

        hooks::run_one_hook_with_context(
            config,
            self,
            Hooks::Preinstall,
            None,
            None,
            opts.dry_run,
            opts.global_hooks_only,
        )
        .await;

        show_python_install_hint(&versions);

        let mut disabled_backend_errors = vec![];
        versions.retain(|tr| {
            if let Ok(backend) = tr.backend()
                && let Err(err) = backend::ensure_backend_enabled(&backend.get_type())
            {
                disabled_backend_errors.push((tr.clone(), err));
                false
            } else {
                true
            }
        });

        // Ensure plugins are installed before building dependency graph
        let plugin_errors = self.ensure_plugins_installed(config, &versions, opts).await;

        // Filter out tools with plugin errors
        let tools_with_plugin_errors: HashSet<_> =
            plugin_errors.iter().map(|(tr, _)| tr.clone()).collect();
        versions.retain(|tr| !tools_with_plugin_errors.contains(tr));

        // Check plugin-declared system prerequisites before compiling anything.
        // Runs here (after plugins are installed, before parallel install tasks
        // spawn) so declarations are readable and the non-Send driver stays on
        // the main task.
        preflight_system_deps(config, &versions, opts).await;

        // Build dependency graph and install using Kahn's algorithm
        let (installed, failed, attempted_failures) = self
            .install_with_deps(config, versions, opts, install_progress.as_deref())
            .await;
        let failed_backends = attempted_failures
            .iter()
            .filter_map(|tr| tr.backend().ok())
            .unique_by(|backend| backend.ba().installs_path.clone())
            .collect_vec();

        // Update footer for errors found before install tasks are spawned.
        let pre_install_error_count = disabled_backend_errors.len() + plugin_errors.len();
        if pre_install_error_count > 0 {
            mpr.footer_inc(pre_install_error_count);
        }

        // Combine plugin errors with installation failures
        let mut all_failed = disabled_backend_errors;
        all_failed.extend(plugin_errors);
        all_failed.extend(failed);
        if let Some(progress) = install_progress.as_mut() {
            progress.finish(
                all_failed
                    .iter()
                    .map(|(tr, error)| (tool_key(tr), error.to_string()))
                    .collect(),
            );
        }

        // Skip config reload and resolve in dry-run mode
        if !opts.dry_run {
            // Reload config and resolve (ignoring errors like the original does)
            trace!("install: reloading config");
            *config = Config::reset().await?;
            trace!("install: resolving");
            if let Err(err) = self.resolve(config).await {
                debug!("error resolving versions after install: {err:#}");
            }
            if !failed_backends.is_empty()
                && let Err(err) =
                    runtime_symlinks::rebuild_for_backends(config, self, failed_backends).await
            {
                warn!("failed to restore runtime symlinks after install failure: {err:#}");
            }
            crate::packslip::auto_sync_skills(config).await;
        }

        // Debug logging for successful installations
        if log::log_enabled!(log::Level::Debug) {
            for tv in installed.iter() {
                let backend = tv.backend()?;
                let bin_paths = backend
                    .list_bin_paths(config, tv)
                    .await
                    .map_err(|e| {
                        warn!("Error listing bin paths for {tv}: {e:#}");
                    })
                    .unwrap_or_default();
                debug!("[{tv}] list_bin_paths: {bin_paths:?}");
                let env = backend
                    .exec_env(config, self, tv)
                    .await
                    .map_err(|e| {
                        warn!("Error running exec-env: {e:#}");
                    })
                    .unwrap_or_default();
                if !env.is_empty() {
                    debug!("[{tv}] exec_env: {env:?}");
                }
            }
        }

        // Finish the global footer before running hooks so output isn't masked
        if !opts.dry_run {
            mpr.footer_finish();
        }

        if opts.dry_run {
            hooks::run_one_hook_with_context(
                config,
                self,
                Hooks::Postinstall,
                None,
                None,
                opts.dry_run,
                opts.global_hooks_only,
            )
            .await;
        } else {
            // Run post-install hook with installed tools info
            // `self` was re-resolved after the config reload above and still
            // contains explicitly requested and task-only tools that are not
            // present in the reloaded project config.
            let installed_tools: Vec<InstalledToolInfo> =
                installed.iter().map(InstalledToolInfo::from).collect();
            hooks::run_one_hook_with_context(
                config,
                self,
                Hooks::Postinstall,
                None,
                Some(&installed_tools),
                opts.dry_run,
                opts.global_hooks_only,
            )
            .await;
        }

        // Return appropriate result
        if all_failed.is_empty() {
            Ok(installed)
        } else {
            Err(Error::InstallFailed {
                successful_installations: installed,
                failed_installations: all_failed,
            }
            .into())
        }
    }

    /// Ensure all plugins for the requested tools are installed
    async fn ensure_plugins_installed(
        &self,
        config: &Arc<Config>,
        versions: &[ToolRequest],
        opts: &InstallOptions,
    ) -> Vec<(ToolRequest, eyre::Error)> {
        let mut plugin_errors = Vec::new();
        let mut checked_backends = HashSet::new();

        for tr in versions {
            let ba = tr.ba();
            if checked_backends.contains(ba) {
                continue;
            }
            checked_backends.insert(ba.clone());

            if let Ok(backend) = tr.backend()
                && let Some(plugin) = backend.plugin()
                && !plugin.is_installed()
            {
                let mpr = MultiProgressReport::get();
                if let Err(e) = plugin
                    .ensure_installed(config, &mpr, false, opts.dry_run)
                    .await
                    .or_else(|err| {
                        if let Some(&Error::PluginNotInstalled(_)) = err.downcast_ref::<Error>() {
                            Ok(())
                        } else {
                            Err(err)
                        }
                    })
                {
                    // Collect errors for all tools using this plugin
                    for tr2 in versions {
                        if tr2.ba() == ba {
                            plugin_errors.push((
                                tr2.clone(),
                                eyre::eyre!("Plugin '{}' installation failed: {}", ba.short, e),
                            ));
                        }
                    }
                }
            }
        }

        plugin_errors
    }

    /// Install tools using Kahn's algorithm for dependency ordering.
    /// Returns (successful_installations, failed_installations, attempted_failures).
    /// The final collection excludes tools blocked before their installer was spawned.
    async fn install_with_deps(
        &self,
        config: &Arc<Config>,
        versions: Vec<ToolRequest>,
        opts: &InstallOptions,
        install_progress: Option<&dyn InstallProgress>,
    ) -> (
        Vec<ToolVersion>,
        Vec<(ToolRequest, eyre::Error)>,
        Vec<ToolRequest>,
    ) {
        if versions.is_empty() {
            return (vec![], vec![], vec![]);
        }

        // Build index map to preserve original request order
        let request_order: HashMap<String, usize> = versions
            .iter()
            .enumerate()
            .map(|(i, tr)| (tool_key(tr), i))
            .collect();

        // Build dependency graph
        let tool_deps = match ToolDeps::new(versions.clone()) {
            Ok(deps) => Arc::new(Mutex::new(deps)),
            Err(e) => {
                // If we can't build the graph, return error for all versions
                let failed: Vec<_> = versions
                    .into_iter()
                    .map(|tr| (tr, eyre::eyre!("Failed to build dependency graph: {}", e)))
                    .collect();
                return (vec![], failed, vec![]);
            }
        };

        // Tell the display which tools are held behind which, before anything
        // starts, so a row can say "waiting for node" instead of nothing.
        if let Some(progress) = install_progress {
            let deps = tool_deps.lock().await;
            for tr in &versions {
                let pending = deps.pending_dependencies(tr);
                if !pending.is_empty() {
                    progress.set_waiting(&tool_key(tr), pending);
                }
            }
        }

        let mut rx = tool_deps.lock().await.subscribe();

        let raw = opts.raw || Settings::get().raw;
        let jobs = match raw {
            true => 1,
            false => crate::jobs::resolve(Settings::get().jobs, opts.jobs),
        };
        let semaphore = Arc::new(Semaphore::new(jobs));
        let ts = Arc::new(self.clone());
        let opts = Arc::new(opts.clone());

        let mut installed = vec![];
        let mut failed = vec![];
        let mut attempted_failures = vec![];
        let mut jset: JoinSet<(ToolRequest, Result<ToolVersion>)> = JoinSet::new();
        // Track in-flight tools to recover from task panics
        let mut in_flight: HashMap<tokio::task::Id, ToolRequest> = HashMap::new();

        loop {
            tokio::select! {
                // Use `biased` to ensure completed installations are handled before starting new ones.
                // This priority ordering ensures dependency tracking stays correct: we must process
                // completions (which may unblock dependents) before spawning new installations.
                biased;

                // Handle completed installations first (higher priority)
                Some(result) = jset.join_next() => {
                    let mpr = MultiProgressReport::get();
                    match result {
                        Ok((tr, Ok(tv))) => {
                            mpr.footer_inc(1);
                            installed.push(tv);
                            tool_deps.lock().await.complete_success(&tr);
                        }
                        Ok((tr, Err(e))) => {
                            mpr.footer_inc(1);
                            attempted_failures.push(tr.clone());
                            failed.push((tr.clone(), e));
                            tool_deps.lock().await.complete_failure(&tr);
                        }
                        Err(e) => {
                            // Task panicked - try to recover the tool request from in_flight tracking
                            mpr.footer_inc(1);
                            if let Some(tr) = in_flight.remove(&e.id()) {
                                attempted_failures.push(tr.clone());
                                failed.push((tr.clone(), eyre::eyre!("Installation task panicked: {e:#}")));
                                tool_deps.lock().await.complete_failure(&tr);
                            } else {
                                warn!("Task panicked but tool request not found: {e:#}");
                            }
                        }
                    }
                }

                // Receive new tools to install
                Some(maybe_tr) = rx.recv() => {
                    match maybe_tr {
                        Some(tr) => {
                            // Spawn installation task
                            let permit = match semaphore.clone().acquire_owned().await {
                                Ok(p) => p,
                                Err(e) => {
                                    // Mark as failed and notify tool_deps so dependents are blocked
                                    MultiProgressReport::get().footer_inc(1);
                                    failed.push((tr.clone(), eyre::eyre!("Failed to acquire semaphore: {}", e)));
                                    tool_deps.lock().await.complete_failure(&tr);
                                    continue;
                                }
                            };

                            let config = config.clone();
                            let ts = ts.clone();
                            let opts = opts.clone();
                            let tr_clone = tr.clone();

                            let progress = install_progress.and_then(|p| p.start_tool(&tool_key(&tr)));
                            let handle = jset.spawn(async move {
                                let _permit = permit;
                                let result = Self::install_single_tool(&config, &ts, &tr, &opts, progress.as_deref()).await;
                                if let Some(progress) = progress {
                                    let error = result.as_ref().err().map(|e| e.to_string());
                                    progress.complete(error.as_deref());
                                }
                                (tr, result)
                            });
                            in_flight.insert(handle.id(), tr_clone);
                        }
                        None => {
                            // All tools have been emitted, wait for remaining tasks
                            break;
                        }
                    }
                }

                else => break,
            }
        }

        // Wait for all remaining tasks to complete
        while let Some(result) = jset.join_next().await {
            let mpr = MultiProgressReport::get();
            match result {
                Ok((tr, Ok(tv))) => {
                    mpr.footer_inc(1);
                    installed.push(tv);
                    tool_deps.lock().await.complete_success(&tr);
                }
                Ok((tr, Err(e))) => {
                    mpr.footer_inc(1);
                    attempted_failures.push(tr.clone());
                    failed.push((tr.clone(), e));
                    tool_deps.lock().await.complete_failure(&tr);
                }
                Err(e) => {
                    mpr.footer_inc(1);
                    if let Some(tr) = in_flight.remove(&e.id()) {
                        attempted_failures.push(tr.clone());
                        failed.push((tr.clone(), eyre::eyre!("Installation task panicked: {e:#}")));
                        tool_deps.lock().await.complete_failure(&tr);
                    } else {
                        warn!("Task panicked but tool request not found: {e:#}");
                    }
                }
            }
        }

        // Add blocked tools to failures
        let blocked = tool_deps.lock().await.blocked_tools();
        for tr in blocked {
            failed.push((tr.clone(), eyre::eyre!("Skipped due to failed dependency")));
            MultiProgressReport::get().footer_inc(1);
        }

        // Sort installed versions by original request order to preserve user's intended ordering
        installed.sort_by_key(|tv| {
            let key = tool_key(&tv.request);
            request_order.get(&key).copied().unwrap_or(usize::MAX)
        });

        (installed, failed, attempted_failures)
    }

    /// Install a single tool
    async fn install_single_tool(
        config: &Arc<Config>,
        ts: &Arc<Toolset>,
        tr: &ToolRequest,
        opts: &Arc<InstallOptions>,
        tool_progress: Option<&dyn ToolProgress>,
    ) -> Result<ToolVersion> {
        let mpr = MultiProgressReport::get();
        let pre_resolve_backend = tr.backend()?;
        backend::ensure_backend_enabled(&pre_resolve_backend.get_type())?;
        let mut resolve_options = opts.resolve_options.clone();
        if should_refresh_remote_versions(tr, &pre_resolve_backend, &resolve_options) {
            resolve_options.refresh_remote_versions = true;
        }
        let mut tv = crate::ui::resolve_progress::scope(
            tool_progress.map(|p| p.reporter()),
            tr.resolve(config, &resolve_options),
        )
        .await?;
        let backend = tv.backend()?;
        backend::ensure_backend_enabled(&backend.get_type())?;
        let install_dir = opts.install_dir.clone().or_else(|| {
            opts.scoped_install_dirs
                .then(|| scope_installs_dir(tr))
                .flatten()
        });
        if let Some(dir) = &install_dir {
            let tool_dir_name = tv.ba().tool_dir_name();
            tv.install_path = Some(dir.join(tool_dir_name).join(tv.tv_pathname()));
            tv.install_path_is_explicit = true;
        }
        let before_date = transitive_dependency_before_date(tr, &tv);

        let ctx = InstallContext {
            config: config.clone(),
            ts: ts.clone(),
            pr: Arc::from(if let Some(progress) = tool_progress {
                progress.set_prefix(tv.style());
                progress.reporter()
            } else {
                mpr.add_with_options(&tv.style(), opts.dry_run)
            }),
            force: opts.force,
            dry_run: opts.dry_run,
            locked: config.invocation_locked_for(tr.source(), opts.locked)
                || config.tool_config_locked(tr.source()),
            before_date,
            dependency_context: OnceCell::new(),
        };

        backend.install_version(ctx, tv).await
    }

    pub(crate) async fn install_missing_bin(
        &mut self,
        config: &mut Arc<Config>,
        bin_name: &str,
    ) -> Result<Option<Vec<ToolVersion>>> {
        // Registry bin metadata is the only provider signal available before a tool has ever
        // been installed. Prefer those configured providers, applying registry override order,
        // before falling back to executable discovery from existing installs.
        let mut plugins = IndexSet::new();
        let mut registry_providers = self
            .list_missing_versions_for_install(config)
            .await
            .into_iter()
            .filter(|tv| {
                REGISTRY
                    .get(&tv.ba().short)
                    .is_some_and(|tool| tool.provides_bin(bin_name))
            })
            .filter(|tv| match &Settings::get().auto_install_disable_tools {
                Some(disable_tools) => !disable_tools.contains(&tv.ba().short),
                None => true,
            })
            .map(|tv| eyre::Ok((tv.backend()?, tv)))
            .collect::<Result<Vec<_>>>()?;
        Self::sort_by_overrides(&mut registry_providers)?;
        plugins.extend(registry_providers.into_iter().map(|(backend, _)| backend));

        // Check currently active installed versions.
        for (p, tv) in self.list_current_installed_versions(config) {
            if let Ok(Some(_bin)) = p.which(config, &tv, bin_name).await {
                plugins.insert(p);
            }
        }

        // Also check backends that are requested but not currently active.
        // This handles the case where a user has tool@v1 globally and tool@v2 locally (not installed)
        // When looking for a bin provided by the tool, we check if any installed version provides it
        let all_installed = self.list_installed_versions(config).await?;
        for (backend, _versions) in self.list_versions_by_plugin() {
            // Skip if we already found this backend
            if plugins.contains(&backend) {
                continue;
            }

            // Check if this backend has ANY installed version that provides the bin
            let backend_versions: Vec<_> = all_installed
                .iter()
                .filter(|(p, _)| p.ba() == backend.ba())
                .collect();

            for (_, tv) in backend_versions {
                if let Ok(Some(_bin)) = backend.which(config, tv, bin_name).await {
                    plugins.insert(backend.clone());
                    break;
                }
            }
        }

        // Install missing versions for backends that provide this bin
        for plugin in plugins {
            let versions = self
                .list_missing_versions_for_install(config)
                .await
                .into_iter()
                .filter(|tv| tv.ba() == &**plugin.ba())
                .filter(|tv| match &Settings::get().auto_install_disable_tools {
                    Some(disable_tools) => !disable_tools.contains(&tv.ba().short),
                    None => true,
                })
                .map(|tv| tv.request)
                .collect_vec();
            if !versions.is_empty() {
                let versions = self
                    .install_all_versions(config, versions.clone(), &InstallOptions::default())
                    .await?;
                if !versions.is_empty() {
                    let ts = config.get_toolset().await?;
                    config::rebuild_shims_and_runtime_symlinks(
                        config,
                        ts,
                        &versions,
                        crate::lockfile::LockfileUpdateMode::Normal,
                    )
                    .await?;
                }
                for tv in &versions {
                    let backend = tv.backend()?;
                    if backend.which(config, tv, bin_name).await?.is_some() {
                        return Ok(Some(versions));
                    }
                }
            }
        }
        Ok(None)
    }

    /// Install all plugins defined in [plugins] config section
    pub(crate) async fn ensure_config_plugins_installed(
        config: &Arc<Config>,
        dry_run: bool,
    ) -> Result<()> {
        Self::ensure_config_plugins_installed_from_urls(config, &config.repo_urls, dry_run).await
    }

    /// Install all plugins from an explicit plugin URL map.
    pub(crate) async fn ensure_config_plugins_installed_from_urls(
        config: &Arc<Config>,
        repo_urls: &HashMap<String, String>,
        dry_run: bool,
    ) -> Result<()> {
        if repo_urls.is_empty() {
            return Ok(());
        }

        let mpr = MultiProgressReport::get();

        for (plugin_key, url) in repo_urls {
            let (plugin_type, name) = Self::parse_plugin_key(plugin_key);

            // Skip empty plugin names (e.g., from malformed keys like "" or "vfox:")
            if name.is_empty() {
                warn!("skipping empty plugin name from key: {plugin_key}");
                continue;
            }

            let plugin = plugin_type.plugin(name.to_string());
            plugin.set_remote_url(url.clone());

            if !plugin.is_installed() {
                plugin
                    .ensure_installed(config, &mpr, false, dry_run)
                    .await?;
            }
        }
        Ok(())
    }

    fn parse_plugin_key(key: &str) -> (PluginType, &str) {
        PluginType::from_plugin_config(key)
    }
}

/// The install directory a tool belongs in based on the scope of the config file that
/// declares it. Only system configuration relocates; everything else uses the default.
fn scope_installs_dir(tr: &ToolRequest) -> Option<PathBuf> {
    tr.source()
        .path()
        .and_then(|path| {
            (crate::config::provenance::ConfigProvenance::from_path(path).scope()
                == crate::config::provenance::ConfigFileScope::System)
                .then(|| Settings::get().system_installs_dir().to_path_buf())
        })
        .filter(|dir| dir != *crate::dirs::INSTALLS)
}

fn lazy_bin_names_eq(configured: &str, requested: &str) -> bool {
    if cfg!(windows) {
        shims::command_name_without_exe_suffix(configured)
            .eq_ignore_ascii_case(shims::command_name_without_exe_suffix(requested))
    } else {
        configured == requested
    }
}

fn ensure_safe_install_options(versions: &[ToolRequest]) -> Result<()> {
    for request in versions {
        request.ensure_safe_install_options()?;
    }
    Ok(())
}

/// Whether install-time resolution should refresh the remote-versions cache
/// before picking a version. Only selectors whose meaning depends on the
/// freshest upstream entry benefit: `latest`, `sub-N:latest`, and prefix
/// queries that have no matching installed version. Fully-pinned exact
/// versions, refs, paths, `system`, and prefix queries already satisfied by
/// an installed version are unaffected by cache staleness — for those the
/// cached answer is either correct or harmless, and refreshing is wasted
/// network traffic. Users who want to pull the absolute latest matching a
/// prefix can run `mise upgrade` or pin to `@latest`.
///
/// Skipped in `prefer_offline` mode (shims, hook-env, activate, etc.) because
/// the versions host is disabled there, so a refresh would bypass the
/// on-disk cache populated by an earlier non-prefer-offline command and fall
/// through to a backend listing that often has far fewer versions (e.g. the
/// GitHub releases listing only returns the most recent ~30), turning a
/// previously-resolvable prefix query into "no versions found".
fn should_refresh_remote_versions(
    tr: &ToolRequest,
    backend: &crate::backend::ABackend,
    opts: &ResolveOptions,
) -> bool {
    if opts.refresh_remote_versions || opts.offline || Settings::get().prefer_offline() {
        return false;
    }
    match tr {
        ToolRequest::Version { version, .. } => version == "latest",
        ToolRequest::Prefix { prefix, .. } => {
            backend.list_installed_versions_matching(prefix).is_empty()
        }
        ToolRequest::Sub { orig_version, .. } => orig_version == "latest",
        ToolRequest::Ref { .. } | ToolRequest::Path { .. } | ToolRequest::System { .. } => false,
    }
}

fn transitive_dependency_before_date(
    tr: &ToolRequest,
    tv: &ToolVersion,
) -> Option<jiff::Timestamp> {
    match tr {
        ToolRequest::Version { version, .. } if version != "latest" && version == &tv.version => {
            None
        }
        ToolRequest::Ref { .. } | ToolRequest::Path { .. } | ToolRequest::System { .. } => None,
        _ => tv.before_date,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::args::BackendArg;
    use crate::toolset::parse_tool_options;

    #[cfg(windows)]
    #[test]
    fn lazy_bin_names_match_windows_command_case() {
        assert!(lazy_bin_names_eq("dummy", "DUMMY"));
        assert!(lazy_bin_names_eq("dummy.exe", "DUMMY"));
        assert!(lazy_bin_names_eq("DUMMY.EXE", "dummy.exe"));
        assert!(!lazy_bin_names_eq("dummy", "other"));
    }

    #[tokio::test]
    async fn test_init_request_options_preserves_unmatched_request_options() {
        crate::toolset::install_state::init().await.unwrap();
        let ba = Arc::new(BackendArg::from("dummy"));
        let mut toolset = Toolset::new(ToolSource::Unknown);
        for version in ["1.0.0", "2.0.0"] {
            toolset.add_version(
                ToolRequest::new_with_options(
                    ba.clone(),
                    version,
                    parse_tool_options(&format!(r#"postinstall="echo configured {version}""#)),
                    ToolSource::Unknown,
                )
                .unwrap(),
            );
        }

        let mut requests = vec![
            ToolRequest::new_with_options(
                ba.clone(),
                "3.0.0",
                parse_tool_options(r#"postinstall="echo carried""#),
                ToolSource::Argument,
            )
            .unwrap(),
        ];
        toolset.init_request_options(&mut requests);

        assert_eq!(
            requests[0].options().get("postinstall"),
            Some("echo carried")
        );

        let mut inactive_options = parse_tool_options(r#"postinstall="echo inactive""#);
        let inactive_os = match crate::cli::version::OS.as_str() {
            "linux" => "macos",
            _ => "linux",
        };
        inactive_options.core.os = Some(vec![inactive_os.to_string()]);
        let inactive = ToolRequest::new_with_options(
            ba.clone(),
            "4.0.0",
            inactive_options,
            ToolSource::Unknown,
        )
        .unwrap();
        let active = ToolRequest::new_with_options(
            ba,
            "4.0.0",
            parse_tool_options(r#"postinstall="echo active""#),
            ToolSource::Unknown,
        )
        .unwrap();
        let mut toolset = Toolset::new(ToolSource::Unknown);
        toolset.add_version(inactive.clone());
        toolset.add_version(active.clone());
        let mut requests = vec![inactive.clone(), active.clone()];
        toolset.init_request_options(&mut requests);

        assert_eq!(requests, vec![inactive, active]);
    }

    #[tokio::test]
    async fn test_init_request_options_preserves_matching_request_options() {
        crate::toolset::install_state::init().await.unwrap();
        let ba = Arc::new(BackendArg::from("dummy[inline_only=inline]"));
        let configured = ToolRequest::new_with_options(
            ba.clone(),
            "1.0.0",
            parse_tool_options(r#"selected="config""#),
            ToolSource::Unknown,
        )
        .unwrap();
        let mut toolset = Toolset::new(ToolSource::Unknown);
        toolset.add_version(configured);
        let mut requests = vec![
            ToolRequest::new_with_options(
                ba,
                "1.0.0",
                parse_tool_options(r#"request_only="request""#),
                ToolSource::Argument,
            )
            .unwrap(),
        ];

        toolset.init_request_options(&mut requests);

        let options = requests[0].options();
        assert_eq!(options.get("selected"), Some("config"));
        assert_eq!(options.get("request_only"), Some("request"));
        assert_eq!(options.get("inline_only"), Some("inline"));
    }
}