Skip to main content

mj_controller/
setup.rs

1//! Additive first-run discovery shared by the dashboard and `mj setup`.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Path, PathBuf};
5
6use crate::doctor::{
7    ApplePlatform, CheckStatus, apple_container_runtime_check, current_apple_platform,
8    local_docker_runtime_check, local_podman_runtime_check,
9};
10use crate::targets::{CommandExecutor, CommandSpec};
11use mj_core::config::{
12    Config, ContainerTemplate, HarnessHost, HarnessKind, HarnessProfile, ProjectBundle,
13    ProjectRepository, TargetTemplate, unique_config_id as unique_id,
14};
15
16mod startup;
17pub use startup::{SetupReport, actionable_errors, run_setup, run_setup_command};
18
19// Published from containers/Containerfile.agent-dev by
20// .github/workflows/publish-agent-dev-image.yml. It already carries Node, Rust,
21// Git, gh, and the pinned ACP bridges, so a first session does not have to
22// install them.
23pub use mj_client::target::DEFAULT_IMAGE;
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct DiscoveredHome {
27    pub kind: HarnessKind,
28    pub path: PathBuf,
29    pub authenticated: bool,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct GithubRepository {
34    pub owner: String,
35    pub repository: String,
36}
37
38impl GithubRepository {
39    fn source(&self) -> String {
40        format!("{}/{}", self.owner, self.repository)
41    }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum RuntimeKind {
46    Podman,
47    Docker,
48    AppleContainer,
49}
50
51impl RuntimeKind {
52    pub fn label(self) -> &'static str {
53        match self {
54            Self::Podman => "Podman",
55            Self::Docker => "Docker",
56            Self::AppleContainer => "Apple container",
57        }
58    }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct RuntimeProbe {
63    pub kind: RuntimeKind,
64    pub status: CheckStatus,
65    pub detail: String,
66    /// The fix `mj doctor` would print for this runtime, carried through so
67    /// setup never invents its own remediation wording.
68    pub remediation: Option<String>,
69}
70
71impl RuntimeProbe {
72    pub fn usable(&self) -> bool {
73        self.status == CheckStatus::Ready
74    }
75}
76
77/// The installed agent homes alone. Callers that only add profiles use this
78/// without probing unrelated runtimes or remote targets.
79pub fn discover_profiles(executor: &impl CommandExecutor) -> Vec<DiscoveredHome> {
80    let home = dirs::home_dir();
81    let overrides = HarnessKind::ALL
82        .into_iter()
83        .filter_map(|kind| {
84            std::env::var_os(kind.home_env()).map(|path| (kind, kind.home_from_environment(path)))
85        })
86        .collect::<BTreeMap<_, _>>();
87    let mut homes =
88        discover_harness_homes_with_executor(home.as_deref(), overrides.clone(), executor);
89    discover_installed_harnesses(home.as_deref(), &overrides, &mut homes, executor);
90    homes
91}
92
93/// The container runtimes on this machine alone, usable or not, so a caller
94/// can report why an unusable one was skipped.
95pub fn discover_runtimes(executor: &impl CommandExecutor) -> Vec<RuntimeProbe> {
96    probe_local_runtimes(executor, &current_apple_platform(executor))
97}
98
99/// A configuration holding the discovered profiles and nothing else, for
100/// merging into an existing configuration.
101pub fn profiles_config(homes: &[DiscoveredHome]) -> Config {
102    build_config(homes, None)
103}
104
105/// Read the concrete `Host` aliases from `~/.ssh/config`.
106///
107/// This is a pure read: setup never runs `ssh` while discovering. `Include`
108/// directives are deliberately not followed, because resolving them correctly
109/// means reimplementing OpenSSH's glob and relative-path rules; aliases that
110/// live in an included file simply are not offered, and the user can still
111/// type a host by hand.
112pub fn discover_ssh_hosts(home: Option<&Path>) -> Vec<String> {
113    let Some(home) = home else {
114        return Vec::new();
115    };
116    let Ok(contents) = std::fs::read_to_string(home.join(".ssh").join("config")) else {
117        return Vec::new();
118    };
119    ssh_config_aliases(&contents)
120}
121
122/// Extract the usable `Host` aliases from SSH config text.
123///
124/// Pattern entries (`*`, `?`, `!`) are skipped: they configure other hosts
125/// rather than naming one Hel could connect to.
126pub fn ssh_config_aliases(contents: &str) -> Vec<String> {
127    let mut aliases: Vec<String> = Vec::new();
128    for line in contents.lines() {
129        let line = line.trim();
130        if line.is_empty() || line.starts_with('#') {
131            continue;
132        }
133        let Some((keyword, rest)) = line.split_once(char::is_whitespace) else {
134            continue;
135        };
136        if !keyword.eq_ignore_ascii_case("host") {
137            continue;
138        }
139        for alias in rest.split_whitespace() {
140            let alias = alias.trim_matches('"');
141            if alias.is_empty() || alias.contains(['*', '?', '!']) {
142                continue;
143            }
144            if !aliases.iter().any(|existing| existing == alias) {
145                aliases.push(alias.to_owned());
146            }
147        }
148    }
149    aliases
150}
151
152/// A newly installed CLI may not create its profile directory until login.
153/// Run these probes through setup's bounded, cancellable executor.
154fn discover_installed_harnesses(
155    user_home: Option<&Path>,
156    overrides: &BTreeMap<HarnessKind, PathBuf>,
157    homes: &mut Vec<DiscoveredHome>,
158    executor: &impl CommandExecutor,
159) {
160    for kind in HarnessKind::ALL {
161        if homes.iter().any(|home| home.kind == kind) {
162            continue;
163        }
164        let Some(home) = overrides
165            .get(&kind)
166            .cloned()
167            .or_else(|| user_home.map(|home| home.join(kind.default_home_leaf())))
168        else {
169            continue;
170        };
171        let probe = CommandSpec::new(kind.cli_binary_name(), ["--version"])
172            .purpose("detect installed harness before first login");
173        match executor.execute(&probe) {
174            Ok(output) if output.status == 0 => homes.push(DiscoveredHome {
175                kind,
176                path: home,
177                authenticated: false,
178            }),
179            Ok(_) => {}
180            Err(error) => tracing::debug!(
181                harness = kind.id(),
182                "installation probe unavailable: {error:#}"
183            ),
184        }
185    }
186}
187
188pub(crate) fn discover_harness_homes_with_executor(
189    home: Option<&Path>,
190    overrides: impl IntoIterator<Item = (HarnessKind, PathBuf)>,
191    executor: &impl CommandExecutor,
192) -> Vec<DiscoveredHome> {
193    let mut candidates = Vec::new();
194    if let Some(home) = home {
195        candidates.extend(
196            HarnessKind::ALL
197                .into_iter()
198                .map(|kind| (kind, home.join(kind.default_home_leaf()), true)),
199        );
200    }
201    candidates.extend(
202        overrides
203            .into_iter()
204            .map(|(kind, path)| (kind, path, false)),
205    );
206
207    let mut seen = BTreeSet::new();
208    candidates
209        .into_iter()
210        .filter(|(kind, path, _)| seen.insert((*kind, path.clone())) && path.is_dir())
211        .map(|(kind, path, is_default_home)| DiscoveredHome {
212            authenticated: harness_is_authenticated_with(
213                &probe_profile(kind, &path),
214                is_default_home,
215                executor,
216            ),
217            kind,
218            path,
219        })
220        .collect()
221}
222
223/// A profile standing in for a home discovery found but the user has not
224/// configured. It carries no environment, so cloud backends must be configured
225/// explicitly before their authentication can be recognized.
226fn probe_profile(kind: HarnessKind, home: &Path) -> HarnessProfile {
227    HarnessProfile {
228        enabled: true,
229        kind,
230        home: home.to_path_buf(),
231        environment: Default::default(),
232        context_window_bytes: None,
233        subagents: Default::default(),
234        guardian_review_model: None,
235    }
236}
237
238pub(crate) fn harness_is_authenticated_with_executor(
239    profile: &HarnessProfile,
240    executor: &impl CommandExecutor,
241) -> bool {
242    let is_default_home = dirs::home_dir()
243        .is_some_and(|user_home| profile.home == user_home.join(profile.kind.default_home_leaf()));
244    harness_is_authenticated_with(profile, is_default_home, executor)
245}
246
247/// Whether this profile can talk to its service without a login first.
248///
249/// An API-key profile is proven by its harness configuration file, because its
250/// key lives in the profile's `environment` rather than in a credential file;
251/// [`HarnessProfile::authentication_marker`] already names the right file for
252/// either case.
253fn harness_is_authenticated_with(
254    profile: &HarnessProfile,
255    is_default_home: bool,
256    executor: &impl CommandExecutor,
257) -> bool {
258    let kind = profile.kind;
259    let home = profile.home.as_path();
260    // AWS credentials can come from a role or an external credential process;
261    // there is no harness login file. Doctor probes the chain separately.
262    if profile.auth_scheme() == mj_core::config::AuthScheme::AwsCredentialChain {
263        return true;
264    }
265    if profile.authentication_marker().is_file()
266        || (kind == HarnessKind::Kimi && home.join("credentials").is_file())
267    {
268        return true;
269    }
270    if kind != HarnessKind::Claude {
271        return false;
272    }
273    // Where the login does not live in the home, every Claude profile shares
274    // the one Keychain item, so asking the CLI about a scoped home would only
275    // report the default profile's state again.
276    if is_default_home || !kind.keeps_login_in_home(HarnessHost::current()) {
277        return claude_keychain_reports_authenticated(executor);
278    }
279    claude_cli_reports_authenticated(home, executor)
280}
281
282/// Ask Claude Code about a scoped profile. Setting `CLAUDE_CONFIG_DIR` for the
283/// default home changes Claude's profile selection, so the default macOS
284/// profile is checked directly in the Keychain instead.
285fn claude_cli_reports_authenticated(home: &Path, executor: &impl CommandExecutor) -> bool {
286    let mut command = CommandSpec::new("claude", ["auth", "status", "--json"])
287        .purpose("check Claude Code authentication");
288    command.env.insert(
289        HarnessKind::Claude.home_env().to_owned(),
290        home.to_string_lossy().into_owned(),
291    );
292    let Ok(output) = executor.execute(&command) else {
293        return false;
294    };
295    if output.status != 0 {
296        return false;
297    }
298    serde_json::from_slice::<serde_json::Value>(&output.stdout)
299        .ok()
300        .and_then(|status| status.get("loggedIn").and_then(serde_json::Value::as_bool))
301        == Some(true)
302}
303
304/// Mjolnir and Claude Code use this service for the default macOS profile.
305/// `security` is already authorized for the item, so this does not raise a
306/// Keychain prompt; the shared executor still bounds a wedged lookup.
307#[cfg(target_os = "macos")]
308fn claude_keychain_reports_authenticated(executor: &impl CommandExecutor) -> bool {
309    let command = CommandSpec::new(
310        "security",
311        [
312            "find-generic-password",
313            "-s",
314            "Claude Code-credentials",
315            "-w",
316        ],
317    )
318    .purpose("check Claude Code authentication in the macOS Keychain");
319    let Ok(output) = executor.execute(&command) else {
320        return false;
321    };
322    output.status == 0 && claude_credentials_contain_login(&output.stdout)
323}
324
325#[cfg(not(target_os = "macos"))]
326fn claude_keychain_reports_authenticated(_executor: &impl CommandExecutor) -> bool {
327    false
328}
329
330#[cfg(any(target_os = "macos", test))]
331fn claude_credentials_contain_login(credentials: &[u8]) -> bool {
332    let Ok(document) = serde_json::from_slice::<serde_json::Value>(credentials) else {
333        return false;
334    };
335    [
336        "/claudeAiOauth/accessToken",
337        "/claudeAiOauth/refreshToken",
338        "/oauth/accessToken",
339        "/apiKey",
340    ]
341    .into_iter()
342    .any(|pointer| {
343        document
344            .pointer(pointer)
345            .and_then(serde_json::Value::as_str)
346            .is_some_and(|value| !value.trim().is_empty())
347    })
348}
349
350pub fn github_repository_from_origin(origin: &str) -> Option<GithubRepository> {
351    let (owner, repository) = mj_core::remote_git::github_owner_repo(origin)?;
352    Some(GithubRepository { owner, repository })
353}
354
355/// Read the current directory's GitHub origin, through the same executor every
356/// other discovery probe uses so it is bounded and can be faked in tests.
357///
358/// `git -C` selects the directory instead of a working-directory field on the
359/// command, which no executor carries.
360fn discover_github_repository(
361    executor: &impl CommandExecutor,
362    cwd: &Path,
363) -> Option<GithubRepository> {
364    let command = CommandSpec::new(
365        "git",
366        [
367            "-C".to_owned(),
368            cwd.to_string_lossy().into_owned(),
369            "remote".to_owned(),
370            "get-url".to_owned(),
371            "origin".to_owned(),
372        ],
373    )
374    .purpose("detect the current repository's GitHub origin");
375    let output = executor.execute(&command).ok()?;
376    if output.status != 0 {
377        return None;
378    }
379    github_repository_from_origin(&String::from_utf8_lossy(&output.stdout))
380}
381
382/// Probe the container runtimes setup can configure, reusing the doctor checks
383/// so an unavailable runtime carries doctor's detail and remediation.
384pub fn probe_local_runtimes(
385    executor: &impl CommandExecutor,
386    platform: &ApplePlatform,
387) -> Vec<RuntimeProbe> {
388    let mut probes = vec![
389        runtime_probe_from_check(
390            RuntimeKind::Podman,
391            local_podman_runtime_check(executor, platform),
392        ),
393        runtime_probe_from_check(RuntimeKind::Docker, local_docker_runtime_check(executor)),
394    ];
395    if matches!(platform, ApplePlatform::Macos { .. }) {
396        probes.push(runtime_probe_from_check(
397            RuntimeKind::AppleContainer,
398            apple_container_runtime_check(platform, executor),
399        ));
400    }
401    probes
402}
403
404fn runtime_probe_from_check(kind: RuntimeKind, check: crate::doctor::DoctorCheck) -> RuntimeProbe {
405    RuntimeProbe {
406        kind,
407        status: check.status,
408        detail: check.detail,
409        remediation: check.remediation,
410    }
411}
412
413/// Configuration additions for installed profiles and the current repository.
414pub fn build_config(homes: &[DiscoveredHome], repository: Option<&GithubRepository>) -> Config {
415    let mut config = Config::default();
416    for home in homes {
417        let id = unique_id(&config.profiles, home.kind.id());
418        config.profiles.insert(
419            id,
420            HarnessProfile {
421                enabled: true,
422                kind: home.kind,
423                home: home.path.clone(),
424                environment: Default::default(),
425                context_window_bytes: None,
426                subagents: Default::default(),
427                guardian_review_model: None,
428            },
429        );
430    }
431
432    if let Some(repository) = repository {
433        let repository_id = config_id(&repository.repository);
434        config.bundles.insert(
435            "current-repository".to_owned(),
436            ProjectBundle {
437                primary_repo: repository_id.clone(),
438                repositories: vec![ProjectRepository {
439                    id: repository_id.clone(),
440                    github: Some(repository.source()),
441                    local: None,
442                    destination: PathBuf::from(repository_id),
443                    git_ref: None,
444                }],
445            },
446        );
447    }
448
449    #[cfg(unix)]
450    config
451        .targets
452        .insert("localhost".to_owned(), TargetTemplate::LocalBare);
453    config
454}
455
456/// The shared setup/startup template for a locally available container engine.
457pub fn local_runtime_target(runtime: RuntimeKind, image: &str) -> (&'static str, TargetTemplate) {
458    let container = ContainerTemplate {
459        build_cache: None,
460        image: image.trim().to_owned(),
461        pull_policy: Default::default(),
462        platform: None,
463        cpus: None,
464        memory: None,
465        environment: Default::default(),
466        workspace_storage: Default::default(),
467    };
468    match runtime {
469        RuntimeKind::Podman => ("podman", TargetTemplate::LocalPodman { container }),
470        RuntimeKind::Docker => ("docker", TargetTemplate::LocalDocker { container }),
471        RuntimeKind::AppleContainer => (
472            "apple-container",
473            TargetTemplate::AppleContainer { container },
474        ),
475    }
476}
477
478fn config_id(value: &str) -> String {
479    let mut id = value
480        .chars()
481        .filter(|character| {
482            character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
483        })
484        .take(64)
485        .collect::<String>();
486    if id.is_empty() || matches!(id.as_str(), "." | "..") {
487        id = "repository".to_owned();
488    }
489    id
490}
491
492#[cfg(test)]
493mod tests;