Skip to main content

agentmux_srv_core/backend/blockcontroller/
acp_prelaunch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Files two ACP agents need in their own config dirs before they start.
5//! SPEC_NINE_NEW_HARNESSES_2026_10_14.md §7.5 (Grok Build), §7.6 (DeepSeek Harness).
6
7use std::collections::HashMap;
8use std::path::Path;
9
10/// Run before an ACP agent spawns, with its env and absolute session cwd. A
11/// failure is logged and the launch goes on: the agent still runs, only
12/// without what the file gives it.
13pub(super) fn prepare(provider: &str, env: &HashMap<String, String>, cwd: &str) {
14    let result = match provider {
15        "grok" => env.get("GROK_HOME").map(|home| trust_grok_folder(Path::new(home), cwd)),
16        "dsh" => env.get("DSH_HOME").map(|home| seed_dsh_patch(Path::new(home))),
17        _ => None,
18    };
19    if let Some(Err(e)) = result {
20        tracing::warn!(provider, error = %e, "[acp] pre-launch file not written");
21    }
22}
23
24/// Run on an ACP agent's spawn env before it spawns. DeepSeek Harness drops every variable whose name
25/// holds `KEY`, `TOKEN`, `SECRET` or `PASSWORD` from the shells it starts, which would split git's
26/// `GIT_CONFIG_*` list, so its git config is handed over as `GIT_CONFIG_PARAMETERS`
27/// (`publish_guard::git_config_as_parameters`).
28pub(super) fn prepare_env(provider: &str, env: &mut HashMap<String, String>) {
29    if provider == "dsh" {
30        crate::backend::publish_guard::git_config_as_parameters(env, |k| std::env::var(k).ok());
31    }
32}
33
34/// The Node.js DeepSeek Harness needs (its package's `engines`). The install flow checks the same
35/// minimum before the first launch (`systemPrereqs` in `frontend/app/view/agent/providers/catalog.ts`);
36/// an agent that is already set up is not run through that, so a restart on an older Node would end in
37/// dsh's own startup error. Keep the two in step.
38const DSH_MIN_NODE: [u64; 3] = [24, 9, 0];
39
40/// `major.minor.patch` of a `node --version` answer (`v24.19.0`, `24.19.0`); a missing part is 0.
41fn version_parts(text: &str) -> Option<[u64; 3]> {
42    let mut parts = [0u64; 3];
43    let mut numbers = text.trim().trim_start_matches('v').split('.');
44    parts[0] = numbers.next()?.trim().parse().ok()?;
45    for part in parts.iter_mut().skip(1) {
46        match numbers.next() {
47            Some(n) => *part = n.split(|c: char| !c.is_ascii_digit()).next().unwrap_or("").parse().ok()?,
48            None => break,
49        }
50    }
51    Some(parts)
52}
53
54/// What to tell the person when `version` is older than DeepSeek Harness needs; `None` when it is
55/// new enough or cannot be read (dsh then says what it makes of it).
56fn node_too_old(version: &str) -> Option<String> {
57    let found = version_parts(version)?;
58    (found < DSH_MIN_NODE).then(|| {
59        let [major, minor, patch] = DSH_MIN_NODE;
60        format!(
61            "DeepSeek Harness needs Node.js {major}.{minor}.{patch} or later, and the Node.js on this agent's PATH is {}. Update Node.js (https://nodejs.org/), then start the agent again.",
62            version.trim().trim_start_matches('v')
63        )
64    })
65}
66
67/// Refuse to start DeepSeek Harness on a Node.js older than it needs, with the reason, instead of
68/// letting it fail with its own startup error. Every other provider, and a machine with no `node` on
69/// the agent's PATH (the spawn then says so), goes on.
70pub(super) fn check_runtime(provider: &str, env: &HashMap<String, String>) -> Result<(), String> {
71    if provider != "dsh" {
72        return Ok(());
73    }
74    let path = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH")).map(|(_, v)| std::ffi::OsString::from(v)).or_else(|| std::env::var_os("PATH"));
75    let Ok(cwd) = std::env::current_dir() else { return Ok(()) };
76    let Ok(node) = which::which_in("node", path, cwd) else { return Ok(()) };
77    let version = crate::backend::tool_store::probe_version(&node.to_string_lossy(), &Some("--version".to_string()));
78    match version.as_deref().and_then(node_too_old) {
79        Some(reason) => Err(reason),
80        None => Ok(()),
81    }
82}
83
84/// Grok reads project rules (the agent's AGENTS.md) only in a trusted folder,
85/// and its stdio agent takes no `--trust`. So the agent's own working folder
86/// is trusted in `$GROK_HOME/trusted_folders.toml`, the file `grok --trust`
87/// writes. Only that folder: `GROK_FOLDER_TRUST=0` would also load any repo's
88/// own MCP servers and hooks. An entry already there, trusted or not, is left
89/// as the user decided.
90fn trust_grok_folder(grok_home: &Path, cwd: &str) -> std::io::Result<()> {
91    let folder = if cfg!(windows) { cwd.replace('/', "\\") } else { cwd.to_string() };
92    // A TOML literal key can't hold a quote or a line break.
93    if folder.is_empty() || folder.contains('\'') || folder.contains('\n') {
94        return Ok(());
95    }
96    let file = grok_home.join("trusted_folders.toml");
97    let existing = std::fs::read_to_string(&file).unwrap_or_default();
98    let header = format!("[folders.'{folder}']");
99    if existing.lines().any(|l| l.trim() == header) {
100        return Ok(());
101    }
102    std::fs::create_dir_all(grok_home)?;
103    let sep = if existing.is_empty() || existing.ends_with('\n') { "" } else { "\n" };
104    let now = agentmux_common::time::now_secs();
105    std::fs::write(&file, format!("{existing}{sep}{header}\ntrusted = true\ndecided_at = {now}\n"))
106}
107
108/// DeepSeek Harness uploads its session logs with requests to DeepSeek's API
109/// unless a profile patch turns that off, and no env var can. Written only
110/// when there is no `$DSH_HOME/cordis.patch.yml` yet, so a user's own patch
111/// is never replaced.
112fn seed_dsh_patch(dsh_home: &Path) -> std::io::Result<()> {
113    let file = dsh_home.join("cordis.patch.yml");
114    if file.exists() {
115        return Ok(());
116    }
117    std::fs::create_dir_all(dsh_home)?;
118    std::fs::write(file, DSH_NO_SESSION_LOG)
119}
120
121const DSH_NO_SESSION_LOG: &str = "# Written by AgentMux: no session-log upload to DeepSeek. Delete or edit to change.\n\
122- id: session-log-deepseek\n  config:\n    enabled: false\n";
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    #[test]
129    fn grok_trusts_the_agents_folder_once_and_keeps_other_entries() {
130        let home = tempfile::tempdir().unwrap();
131        let file = home.path().join("trusted_folders.toml");
132        std::fs::write(&file, "[folders.'C:\\other']\ntrusted = false\ndecided_at = 1").unwrap();
133        trust_grok_folder(home.path(), "C:/agents/a").unwrap();
134        trust_grok_folder(home.path(), "C:/agents/a").unwrap();
135        let s = std::fs::read_to_string(&file).unwrap();
136        let folder = if cfg!(windows) { "C:\\agents\\a" } else { "C:/agents/a" };
137        assert_eq!(s.matches(&format!("[folders.'{folder}']")).count(), 1);
138        assert!(s.starts_with("[folders.'C:\\other']\ntrusted = false\ndecided_at = 1\n"));
139        assert!(s.contains(&format!("[folders.'{folder}']\ntrusted = true\n")));
140    }
141
142    #[test]
143    fn grok_leaves_a_folder_the_user_decided_on() {
144        let home = tempfile::tempdir().unwrap();
145        let file = home.path().join("trusted_folders.toml");
146        let folder = if cfg!(windows) { "C:\\agents\\b" } else { "/agents/b" };
147        let before = format!("[folders.'{folder}']\ntrusted = false\n");
148        std::fs::write(&file, &before).unwrap();
149        trust_grok_folder(home.path(), folder).unwrap();
150        assert_eq!(std::fs::read_to_string(&file).unwrap(), before);
151    }
152
153    #[test]
154    fn grok_skips_a_folder_a_toml_literal_key_cannot_hold() {
155        let home = tempfile::tempdir().unwrap();
156        trust_grok_folder(home.path(), "C:/it's").unwrap();
157        assert!(!home.path().join("trusted_folders.toml").exists());
158    }
159
160    #[test]
161    fn dsh_gets_the_no_upload_patch_only_when_it_has_none() {
162        let home = tempfile::tempdir().unwrap();
163        seed_dsh_patch(home.path()).unwrap();
164        let patch = std::fs::read_to_string(home.path().join("cordis.patch.yml")).unwrap();
165        assert!(patch.contains("- id: session-log-deepseek\n  config:\n    enabled: false\n"));
166        std::fs::write(home.path().join("cordis.patch.yml"), "mine").unwrap();
167        seed_dsh_patch(home.path()).unwrap();
168        assert_eq!(std::fs::read_to_string(home.path().join("cordis.patch.yml")).unwrap(), "mine");
169    }
170
171    #[test]
172    fn a_node_older_than_dsh_needs_is_refused_with_both_versions_and_the_rest_go_on() {
173        let old = node_too_old("v22.1.0
174").expect("too old");
175        assert!(old.contains("24.9.0 or later") && old.contains("is 22.1.0.") && old.contains("start the agent again"), "{old}");
176        assert!(node_too_old("24.8.9").is_some(), "one patch short");
177        assert!(node_too_old("v24.9.0").is_none(), "exactly the minimum");
178        assert!(node_too_old("v24.19.0").is_none() && node_too_old("25.0.0").is_none() && node_too_old("v26").is_none());
179        assert!(node_too_old("v24.10.0-nightly2025").is_none(), "a suffix after the numbers is ignored");
180        assert_eq!(node_too_old("v24").map(|_| ()), Some(()), "24 alone reads as 24.0.0, which is short");
181        for unreadable in ["", "node", "vx.y"] {
182            assert!(node_too_old(unreadable).is_none(), "{unreadable:?}: dsh decides");
183        }
184    }
185
186    #[test]
187    fn only_dsh_is_checked_and_a_path_with_no_node_goes_on() {
188        let empty = tempfile::tempdir().unwrap();
189        let env = HashMap::from([("PATH".to_string(), empty.path().to_string_lossy().into_owned())]);
190        assert!(check_runtime("dsh", &env).is_ok(), "no node on the PATH: the spawn says so");
191        assert!(check_runtime("claude", &env).is_ok());
192    }
193
194    #[test]
195    fn other_providers_and_missing_dirs_write_nothing() {
196        let env = HashMap::new();
197        prepare("grok", &env, "C:/x");
198        prepare("dsh", &env, "C:/x");
199        prepare("claude", &env, "C:/x");
200    }
201}