Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Find Node in nvm for Windows' folders and say when it's missing (#985)

Cleyson6ec2888128f4
diff --git a/crates/platform/src/process.rs b/crates/platform/src/process.rs
index c297e05b..e312f6f4 100644
--- a/crates/platform/src/process.rs
+++ b/crates/platform/src/process.rs
@@ -385,6 +385,9 @@ fn use_search_path(cmd: &mut std::process::Command) {
}
fn spawn_error(name: &str, program: &OsStr, cwd: Option<&std::path::Path>, e: std::io::Error, remediation: Option<&str>) -> ToolError {
+ if let Some(interpreter) = crate::which::shim_missing_interpreter(program) {
+ return interpreter_missing_error(name, program, &interpreter, &e);
+ }
// Unix starts a relative path from the folder the child runs in; Windows from ours.
let looked_up = if cfg!(unix) { started_from(program, cwd) } else { std::path::PathBuf::from(program) };
let found = crate::which::which_in(&looked_up.to_string_lossy(), crate::which::search_path()).into_iter().next();
@@ -419,6 +422,17 @@ fn spawn_error_for(name: &str, program: &OsStr, e: std::io::Error, remediation:
}
}
+/// An npm shim whose interpreter isn't anywhere we look. Rust then refuses to hand the `.cmd` an
+/// argument with a line break ("batch file arguments are invalid"), which says nothing about Node.
+/// It's a missing program, so builder turns aren't retried.
+fn interpreter_missing_error(name: &str, program: &OsStr, interpreter: &str, e: &std::io::Error) -> ToolError {
+ ToolError::new(ErrorCode::EngineMissing, format!("{name} was installed with npm and needs `{interpreter}` (Node.js) to run, but `{interpreter}` wasn't found."))
+ .with_remediation(format!(
+ "Install Node.js, or if you use nvm for Windows, run `nvm use <version>` in a terminal opened as administrator. Then restart Craft Anything. Installing {name} without npm also works, when it offers that."
+ ))
+ .with_details(serde_json::json!({"program": program.to_string_lossy(), "reason": "interpreter_missing", "interpreter": interpreter, "error": e.to_string()}))
+}
+
fn spawn_error_kind(name: &str, program: &OsStr, e: std::io::Error, kind: std::io::ErrorKind, remediation: Option<&str>) -> ToolError {
match kind {
// A program given by its path (a saved setting, say) that isn't there: PATH has nothing to
@@ -1301,6 +1315,19 @@ mod launch_tests {
mod error_tests {
use super::*;
+ /// An npm shim whose Node is missing is a missing program, named, with what to do about it.
+ #[test]
+ fn a_shim_without_its_interpreter_says_so() {
+ let e = std::io::Error::new(std::io::ErrorKind::InvalidInput, "batch file arguments are invalid");
+ let err = interpreter_missing_error("Claude Code", OsStr::new("claude"), "node", &e);
+ assert_eq!(err.code, ErrorCode::EngineMissing);
+ assert!(err.message.contains("needs `node`") && !err.message.contains("batch file"), "{}", err.message);
+ assert!(err.remediation.as_deref().is_some_and(|r| r.contains("nvm use")), "{:?}", err.remediation);
+ let details = err.details.unwrap();
+ assert_eq!((details["reason"].as_str(), details["interpreter"].as_str()), (Some("interpreter_missing"), Some("node")));
+ assert_eq!(details["error"].as_str(), Some("batch file arguments are invalid"));
+ }
+
/// A busy program file is tried again; any other error, or a file that stays busy, is returned.
#[test]
fn a_busy_program_file_is_tried_again() {
diff --git a/crates/platform/src/which.rs b/crates/platform/src/which.rs
index d5322f46..70a7a104 100644
--- a/crates/platform/src/which.rs
+++ b/crates/platform/src/which.rs
@@ -51,27 +51,16 @@ pub fn search_path() -> Option<OsString> {
/// by its full path.
#[cfg(windows)]
pub(crate) fn launch_target(program: &std::ffi::OsStr) -> (OsString, Vec<OsString>) {
- let Some(found) = which_in(&program.to_string_lossy(), search_path()).into_iter().next() else { return (program.to_owned(), Vec::new()) };
+ let path = search_path();
// Started by the path it was found at, not by name: a child with a cleared environment, or a
// lookup that differs from ours, would say "not found" for a program that is there (#152).
- if !found.extension().is_some_and(|e| e.eq_ignore_ascii_case("cmd") || e.eq_ignore_ascii_case("bat")) {
- return (found.into_os_string(), Vec::new());
- }
- let dir = found.parent().map(Path::to_path_buf).unwrap_or_default();
- let shim = std::fs::metadata(&found)
- .ok()
- .filter(|m| m.len() <= 64 * 1024)
- .and_then(|_| std::fs::read_to_string(&found).ok())
- .and_then(|text| parse_npm_shim(&text));
- match shim {
- Some((None, target)) if is_executable(&dir.join(&target)) => (dir.join(target).into_os_string(), Vec::new()),
- Some((Some(interpreter), target)) if dir.join(&target).is_file() => {
- let local = dir.join(format!("{interpreter}.exe"));
- match if local.is_file() { Some(local) } else { which_in(&interpreter, search_path()).into_iter().next() } {
- Some(i) => (i.into_os_string(), vec![dir.join(target).into_os_string()]),
- None => (found.into_os_string(), Vec::new()),
- }
- }
+ let Some(found) = which_in(&program.to_string_lossy(), path.clone()).into_iter().next() else { return (program.to_owned(), Vec::new()) };
+ match read_shim(&found) {
+ Some((dir, None, target)) if is_executable(&dir.join(&target)) => (dir.join(target).into_os_string(), Vec::new()),
+ Some((dir, Some(interpreter), target)) if dir.join(&target).is_file() => match find_interpreter(&dir, &interpreter, path) {
+ Some(i) => (i.into_os_string(), vec![dir.join(target).into_os_string()]),
+ None => (found.into_os_string(), Vec::new()),
+ },
_ => (found.into_os_string(), Vec::new()),
}
}
@@ -81,6 +70,46 @@ pub(crate) fn launch_target(program: &std::ffi::OsStr) -> (OsString, Vec<OsStrin
(program.to_owned(), Vec::new())
}
+/// The interpreter (`node`) an npm shim needs when it can't be found: then [`launch_target`] can
+/// only start the `.cmd` itself, which can't take an argument with a line break.
+#[cfg(windows)]
+pub(crate) fn shim_missing_interpreter(program: &std::ffi::OsStr) -> Option<String> {
+ let path = search_path();
+ let found = which_in(&program.to_string_lossy(), path.clone()).into_iter().next()?;
+ missing_interpreter_in(&found, path)
+}
+
+#[cfg(not(windows))]
+pub(crate) fn shim_missing_interpreter(_program: &std::ffi::OsStr) -> Option<String> {
+ None
+}
+
+#[cfg(windows)]
+fn missing_interpreter_in(shim: &Path, path: Option<OsString>) -> Option<String> {
+ let (dir, interpreter, target) = read_shim(shim)?;
+ let interpreter = interpreter?;
+ (dir.join(&target).is_file() && find_interpreter(&dir, &interpreter, path).is_none()).then_some(interpreter)
+}
+
+/// A `.cmd`/`.bat` npm shim's folder, interpreter and target (see [`parse_npm_shim`]).
+#[cfg(windows)]
+fn read_shim(found: &Path) -> Option<(PathBuf, Option<String>, String)> {
+ if !found.extension().is_some_and(|e| e.eq_ignore_ascii_case("cmd") || e.eq_ignore_ascii_case("bat")) {
+ return None;
+ }
+ let dir = found.parent().map(Path::to_path_buf).unwrap_or_default();
+ let text = std::fs::metadata(found).ok().filter(|m| m.len() <= 64 * 1024).and_then(|_| std::fs::read_to_string(found).ok())?;
+ let (interpreter, target) = parse_npm_shim(&text)?;
+ Some((dir, interpreter, target))
+}
+
+/// The shim's interpreter: `node.exe` beside it, as npm's shim prefers, else on `path`.
+#[cfg(windows)]
+fn find_interpreter(dir: &Path, interpreter: &str, path: Option<OsString>) -> Option<PathBuf> {
+ let local = dir.join(format!("{interpreter}.exe"));
+ if local.is_file() { Some(local) } else { which_in(interpreter, path).into_iter().next() }
+}
+
/// What an npm (or pnpm) `.cmd` shim runs: its interpreter (`node`; none when the target is an
/// `.exe`) and the target, relative to the shim's folder.
#[cfg(any(windows, test))]
@@ -105,22 +134,39 @@ fn parse_npm_shim(text: &str) -> Option<(Option<String>, String)> {
/// installs there, and only a shell that loaded nvm has them on `PATH` (#112).
#[cfg(unix)]
fn nvm_bins(home: &Path) -> Vec<PathBuf> {
- let Ok(versions) = std::fs::read_dir(home.join(".nvm/versions/node")) else { return Vec::new() };
+ newest_versions(&home.join(".nvm/versions/node")).into_iter().map(|v| v.join("bin")).collect()
+}
+
+/// nvm for Windows' version folders (`node.exe` and the agents npm installed with it), newest
+/// first. `PATH` reaches them only through the link `nvm use` makes (`C:\Program Files\nodejs`),
+/// which is gone when no version is in use; npm shims then had no Node and failed with "batch file
+/// arguments are invalid".
+#[cfg(windows)]
+fn nvm_bins(home: &Path) -> Vec<PathBuf> {
+ let root = std::env::var_os("NVM_HOME").filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| home.join(r"AppData\Roaming\nvm"));
+ newest_versions(&root)
+}
+
+#[cfg(not(any(unix, windows)))]
+fn nvm_bins(_home: &Path) -> Vec<PathBuf> {
+ Vec::new()
+}
+
+/// The `v<number>…` folders in `root`, newest version first, at most eight.
+#[cfg(any(unix, windows))]
+fn newest_versions(root: &Path) -> Vec<PathBuf> {
+ let Ok(versions) = std::fs::read_dir(root) else { return Vec::new() };
let mut found: Vec<(Vec<u64>, PathBuf)> = versions
.flatten()
.filter_map(|e| {
let name = e.file_name().into_string().ok()?;
- let version = name.trim_start_matches('v').split('.').map(|n| n.parse().unwrap_or(0)).collect();
- Some((version, e.path().join("bin")))
+ let number = name.strip_prefix('v').filter(|n| n.starts_with(|c: char| c.is_ascii_digit()))?;
+ let path = e.path();
+ path.is_dir().then(|| (number.split('.').map(|n| n.parse().unwrap_or(0)).collect(), path))
})
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0));
- found.into_iter().map(|(_, bin)| bin).take(8).collect()
-}
-
-#[cfg(not(unix))]
-fn nvm_bins(_home: &Path) -> Vec<PathBuf> {
- Vec::new()
+ found.into_iter().map(|(_, dir)| dir).take(8).collect()
}
/// Where npm puts what it installs globally when the person moved its prefix
@@ -402,9 +448,11 @@ mod tests {
let dirs: Vec<PathBuf> = std::env::split_paths(&with_usual_dirs(Some(path), Some(home.clone()), None).unwrap()).collect();
assert_eq!(dirs[..3], [PathBuf::from(r"C:\Windows"), home.join(r".local\bin"), home.join(r"AppData\Roaming\npm")]);
// PATH's two less `.local\bin`, which is a usual one too; Antigravity's two folders (plus
- // npm's prefix where the environment sets one).
+ // npm's prefix where the environment sets one, and nvm for Windows' versions where
+ // `NVM_HOME` names them).
let npm = usize::from(npm_global_bin(&home).is_some());
- assert_eq!(dirs.len(), 1 + USUAL_HOME_DIRS.len() + 2 + USUAL_DIRS.len() + npm, "nothing twice");
+ let nvm = nvm_bins(&home).len();
+ assert_eq!(dirs.len(), 1 + USUAL_HOME_DIRS.len() + 2 + USUAL_DIRS.len() + npm + nvm, "nothing twice");
assert!(dirs.contains(&home.join("AppData").join("Local").join("agy").join("bin")));
assert!(dirs.contains(&home.join("AppData").join("Local").join("Antigravity")));
// Each way Claude Code installs on Windows: native, npm, WinGet (per user and machine-wide).
@@ -446,6 +494,45 @@ mod tests {
assert_eq!(launch_target(dir.path().join("node").as_os_str()), (dir.path().join("node.exe").into_os_string(), Vec::new()));
}
+ /// nvm for Windows keeps each version's `node.exe` in `v<version>` beside its own files.
+ #[cfg(any(unix, windows))]
+ #[test]
+ fn node_versions_are_listed_newest_first_without_other_files() {
+ let root = tempfile::tempdir().unwrap();
+ for v in ["v18.17.0", "v22.22.1", "v20.18.0", "v20.20.1", "temp", "vendor"] {
+ std::fs::create_dir_all(root.path().join(v)).unwrap();
+ }
+ for f in ["elevate.cmd", "nvm.exe", "settings.txt", "v9.0.0"] {
+ std::fs::write(root.path().join(f), "").unwrap();
+ }
+ let names: Vec<String> = newest_versions(root.path()).iter().filter_map(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).collect();
+ assert_eq!(names, ["v22.22.1", "v20.20.1", "v20.18.0", "v18.17.0"]);
+ assert!(newest_versions(&root.path().join("missing")).is_empty());
+ }
+
+ /// An npm shim with its script but no Node anywhere: the interpreter is named, so the error can
+ /// say what's missing instead of "batch file arguments are invalid".
+ #[cfg(windows)]
+ #[test]
+ fn a_shim_without_node_names_it() {
+ let dir = tempfile::tempdir().unwrap();
+ let shim = dir.path().join("claude.cmd");
+ std::fs::write(&shim, NPM_SHIM).unwrap();
+ let empty = tempfile::tempdir().unwrap();
+ let path = || Some(empty.path().as_os_str().to_owned());
+ assert_eq!(missing_interpreter_in(&shim, path()), None, "no script: not a shim we can run anyway");
+ let script = dir.path().join(r"node_modules\@google\gemini-cli\dist\index.js");
+ std::fs::create_dir_all(script.parent().unwrap()).unwrap();
+ std::fs::write(&script, "").unwrap();
+ assert_eq!(missing_interpreter_in(&shim, path()), Some("node".into()));
+ std::fs::write(empty.path().join("node.exe"), "").unwrap();
+ assert_eq!(missing_interpreter_in(&shim, path()), None, "Node on the search path");
+ std::fs::remove_file(empty.path().join("node.exe")).unwrap();
+ std::fs::write(dir.path().join("node.exe"), "").unwrap();
+ assert_eq!(missing_interpreter_in(&shim, path()), None, "Node beside the shim");
+ assert_eq!(missing_interpreter_in(&dir.path().join("node.exe"), path()), None, "not a shim");
+ }
+
/// A prompt with line breaks and quotes reaches the agent whole (needs Node; skipped without).
#[cfg(windows)]
#[test]
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 49fa0cad..cacb8612 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -16,6 +16,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| OpenCode models and thinking | OpenCode V2 locally and over SSH; Settings → AI lists only that instance's enabled chat models and supported Low/Medium/High/Xhigh/Max variants. Selection is validated and saved through UI, CLI and `ai_models_list` / `ai_model_set`. Explicit selections run natively with the Craft Anything MCP server (local runs; none over SSH yet). See [OpenCode](opencode.md). | Stand-in catalogue/process, persistence, remote-command and UI tests; local live catalogue checks (34 models, all five depths represented). Regression checks route explicit selections natively and parse V2 tool events. Live (2026-11-04, Windows, OpenCode 2.2.5, opencode-go/deepseek-v4.1-flash): a `--standalone` run connected the server (38 tools) and called `core_session_show`. No live SSH host or paid generation used |
| Claude desktop app without Claude Code | When the `claude` command isn't found but the Claude desktop app is (Windows: the Store package's `claude-desktop` app alias or the older installer's `AnthropicClaude` folder; macOS: `Claude.app`), the builder dialog under "No coding agent was found" and `ai detect` (on stderr) say the desktop app is installed but building needs Claude Code, installed apart (#259). Typed as `DetectHint` from `AiHub::detect_hints` | A regression finds the app in temp folders laid out as each Windows installer leaves it, and nothing on Linux; a UI test shows the hint in the dialog. On Windows 10 the real Store package's alias was found. Not checked: macOS, the older installer, and a computer with no `claude` installed |
| Missing program paths | A program started by its path (a saved agent program, for one) that has no file there is reported with that path, as possibly moved by an update, with reason `path_missing`, instead of "isn't installed or isn't on your PATH"; a bare name still speaks of PATH. A relative path is looked up where the program starts (on Unix, its working folder), so a script there whose interpreter is missing isn't called a path with no file. It stays a missing program (`EngineMissing`), so builder turns aren't retried (#721). `ai test` names the agent program it ran and the saved one it replaced (`program`, `saved_program_replaced`), and `doctor` says a saved path has no program there | `a_saved_program_that_is_gone_is_named_by_test_and_doctor` runs both with a removed path. A regression starts a program at a path with no file on Windows 10 and checks the message, remediation and reason, with a bare-name control; on Linux (Docker), a relative script with a missing interpreter started in its folder, through `Process` and `Launch`. Not checked: a real Codex desktop update, or the app's Settings screen with a stale path |
+| npm agents without Node on Windows | Programs are also looked for in nvm for Windows' version folders (`NVM_HOME`, else `%APPDATA%\nvm`, newest first, after `PATH`), so an npm shim such as `claude.cmd` finds Node when no `nvm use` link exists. When a shim's interpreter is still missing, starting it fails with `EngineMissing`, reason `interpreter_missing`, naming `node` and `nvm use`, instead of Rust's "batch file arguments are invalid" | On Windows 10 (Rust 1.99.1): unit tests for version-folder listing with nvm's own files beside the versions, the missing-interpreter check (no Node, Node on the search path, Node beside the shim) and the error's fields; the existing shim tests, including a real multi-line prompt through Node, and the platform crate's 70 tests pass. The failure was seen with Craft Anything 0.4.0 (Claude Code 1.0.96 npm shim, nvm with no version in use). Not checked: the fixed desktop app or CLI on that machine, and a build through a shim found only in nvm's folders |
| Mach-O Objective-C pointers | Chained offsets mapped only into file-empty `__PAGEZERO` reach the image-base fallback; pointer candidates must be backed by file bytes | Synthetic thin and fat Mach-O regression, plain-pointer and authenticated-rebase controls, null and unmapped-pointer checks. Real binaries were not checked for this correction |
| Runtime UI evidence | A denied macOS Accessibility permission is an error (`no_permission`, naming System Settings → Privacy & Security → Accessibility), not a successful read of an empty tree (#240). Any other refusal from the helper is also an error, never `nodes: []` | Unit regression maps the helper's refusal object, keeps a genuinely empty tree a success, and covers the unknown refusal; live `runtime_ui_read --pid 1` on macOS with the permission denied returned the structured error. The granted-permission path was not re-run for this correction |
| Apple app graphs | Selecting a macOS bundle recognises its root-relative `Contents/Info.plist` and retains its service/extension type; nested XPC bundles appear in `services` and as `xpc-service` graph nodes, including their executables when hosted in frameworks | Synthetic inventory tests, including parent-directory and flat bundle layouts, selected services/extensions, framework-hosted service executables, and bare-program controls. Ordinary selected directories with `Contents/Info.plist` need an Apple bundle suffix; archives retain layout-based recognition. Framework libraries and dylibs stay excluded from executables. Real app bundles were not checked for this correction |
diff --git a/docs/pitfalls.md b/docs/pitfalls.md
index ebd3b7b9..19eb14ab 100644
--- a/docs/pitfalls.md
+++ b/docs/pitfalls.md
@@ -314,6 +314,10 @@ Node directly (`which::launch_target`); test a new program on Windows with a mul
npm also writes an extensionless POSIX script beside each shim, and `which` returned that first,
so OpenCode was offered and then every run said it wasn't installed (#41): look up the kinds
Windows can start (`PATHEXT`) before the bare name.
+And when the shim's Node couldn't be found (nvm for Windows with no version in use, so its
+`C:\Program Files\nodejs` link was gone), we fell back to the `.cmd`, and Rust refused the
+multi-line prompt: "batch file arguments are invalid", which named neither Node nor nvm. Search
+nvm's version folders too, and when a shim's interpreter is missing, say so (`interpreter_missing`).
**A first analysis that waited for a lock it could never take.** Ghidra's analysis lock is created
with `create_new` in `ghidra-cache/`, which only existed on machines that had used it before; on a