Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(macrod): run npm-installed Claude Code on Windows (#9337)
Wolf Mermelsteina898dce2dfb5
diff --git a/.github/workflows/test_macrod_update.yml b/.github/workflows/test_macrod_update.ymlindex c3eff52356..47fa0dc079 100644--- a/.github/workflows/test_macrod_update.yml+++ b/.github/workflows/test_macrod_update.yml@@ -136,3 +136,10 @@ jobs:- name: Self-update end to endrun: '& ./crates/coding_agent_worker/e2e/windows_update_test.ps1 -Releases "$env:RUNNER_TEMP/releases" -V1 v2000.1.1.1 -V2 v2000.1.1.2'shell: pwsh+ - name: Setup Node+ uses: actions/setup-node@v4+ with:+ node-version: '24'+ - name: Claude Code from npm+ run: '& ./crates/coding_agent_worker/e2e/windows_claude_code_test.ps1 -Releases "$env:RUNNER_TEMP/releases" -Version v2000.1.1.2'+ shell: pwshdiff --git a/apps/docs/AI/bring-your-own.mdx b/apps/docs/AI/bring-your-own.mdxindex ab96139e58..6498a7b9d9 100644--- a/apps/docs/AI/bring-your-own.mdx+++ b/apps/docs/AI/bring-your-own.mdx@@ -89,7 +89,7 @@ You need a macOS, Linux, or Windows computer that can stay online and an installSelect **Create and pair** to generate your device code.<Note>- Claude Code and Codex use ACP adapters. Their presets require the agent's command, `npm`, and `npx` to be available in the shell where you start `macrod`.+ Claude Code and Codex use ACP adapters, which `macrod` installs with `npm` the first time you select them. Their presets require the agent's command and `npm` to be available in the shell where you start `macrod`. On Windows, Claude Code works from either its native installer or `npm install -g @anthropic-ai/claude-code`.</Note></Step>diff --git a/crates/coding_agent_worker/AGENTS.md b/crates/coding_agent_worker/AGENTS.mdindex 5c9f5f2a64..91c248fbe4 100644--- a/crates/coding_agent_worker/AGENTS.md+++ b/crates/coding_agent_worker/AGENTS.md@@ -26,7 +26,11 @@ the local ACP process (Claude Code, Codex, ...), and drives native`#[cfg(unix)]`. `src/herdr/cli.rs` picks herdr 0.9 (`herdr`) or herdr-core(`hc`) by environment; both stay supported.- `src/executable.rs`: `PATH` lookup; every spawn of a bare command name goes- through `launchable`, which finds Windows `.cmd` shims (`npm`, `npx`).+ through `launchable`, which finds Windows `.cmd` shims (`npm`, `npx`) and+ never npm's extensionless shell script beside them. The Claude Code adapter+ gets the program behind an npm `claude.cmd` (`npm_shim_target_or_self`):+ the Claude SDK spawns `CLAUDE_CODE_EXECUTABLE` without a shell, and Node+ refuses `.cmd` files there.- `install/`: `install.sh` and `install.ps1`, the one-line installers the docsserve from `main`. `install.sh` adds `~/.local/bin` to the shell's startupfile once (`--no-modify-path` opts out); `install.ps1` installs the Windows@@ -53,7 +57,9 @@ the local ACP process (Claude Code, Codex, ...), and drives native- `e2e/`: end-to-end update and installer tests (`build_releases.sh`,`update_e2e.py` (update, prompt-in-gap, output-in-gap, and the negativecases), `installer_test.sh`, `windows_test.ps1` for the launcher- layout, `windows_update_test.ps1` for a running macrod updating itself), run+ layout, `windows_update_test.ps1` for a running macrod updating itself,+ `windows_claude_code_test.ps1` for npm-installed Claude Code served over+ ACP), runby the `test_macrod_update` workflow on Linux, macOS and Windows.- `README.md`: native Herdr session behavior (repositories, reconnect, modelswitching, MCP) — read before changing anything under `src/herdr/`.diff --git a/crates/coding_agent_worker/e2e/windows_claude_code_test.ps1 b/crates/coding_agent_worker/e2e/windows_claude_code_test.ps1new file mode 100644index 0000000000..e289405ec4--- /dev/null+++ b/crates/coding_agent_worker/e2e/windows_claude_code_test.ps1@@ -0,0 +1,111 @@+# Claude Code installed from npm, served by macrod on Windows: `detect-agents`+# offers it, `service --agent claude-code` installs the ACP adapter through+# npm's `.cmd` shim and points it at the binary behind `claude.cmd`, and the+# adapter it configured opens an ACP session, which starts Claude Code itself.+# No sign-in is needed for that, and pairing goes to a closed local port.+#+# pwsh windows_claude_code_test.ps1 -Releases DIR -Version TAG+param(+ [Parameter(Mandatory)] [string] $Releases,+ [Parameter(Mandatory)] [string] $Version+)+$ErrorActionPreference = 'Stop'+$work = Join-Path ([IO.Path]::GetTempPath()) ([Guid]::NewGuid())+$npmPrefix = Join-Path $work 'npm'+$workspace = Join-Path $work 'workspace'+$config = Join-Path $work 'macrod.toml'+New-Item -ItemType Directory -Path $npmPrefix, $workspace | Out-Null++function Check($condition, $message) {+ if (-not $condition) { throw "FAIL: $message" }+ Write-Host "ok: $message"+}+# The JSON lines `$process` prints until `$last` matches one or `$seconds`+# pass; then its stdin closes and the whole process tree stops.+function Read-Json-Lines($process, $seconds, $last) {+ $lines = @()+ $deadline = [DateTime]::UtcNow.AddSeconds($seconds)+ try {+ while ([DateTime]::UtcNow -lt $deadline) {+ $read = $process.StandardOutput.ReadLineAsync()+ if (-not $read.Wait($deadline - [DateTime]::UtcNow) -or $null -eq $read.Result) { break }+ $line = $read.Result | ConvertFrom-Json+ $lines += $line+ if (& $last $line) { break }+ }+ }+ finally {+ $process.StandardInput.Close()+ if (-not $process.WaitForExit(10000)) { $process.Kill($true) }+ }+ return $lines+}++try {+ Expand-Archive (Join-Path $Releases "macrod-$Version-windows-x86_64.zip") $work+ $macrod = Join-Path $work 'macrod.exe'++ # A global npm install, laid out as in %APPDATA%\npm: `claude`, `claude.cmd`+ # and `claude.ps1` side by side.+ & npm install --global --prefix $npmPrefix --no-audit --no-fund --loglevel=error '@anthropic-ai/claude-code'+ Check ($LASTEXITCODE -eq 0) 'npm installs Claude Code'+ $env:Path = "$npmPrefix;$env:Path"+ $env:USERPROFILE = $work+ $env:MACROD_NO_UPDATE = '1'++ $detected = (& $macrod detect-agents | ConvertFrom-Json).agents+ Check (@($detected | Where-Object id -eq 'claude-code').Count -eq 1) 'detect-agents offers Claude Code'++ @"+[macro]+api_url = "http://127.0.0.1:9/agent-harness"+storage_url = "http://127.0.0.1:9/dss"++[harness]+command = "hermes"+args = ["acp"]++[workspace]+path = "."+"@ | Set-Content $config+ # The service reports a fatal error as an event and exits once its stdin+ # closes, like it does under the desktop app.+ $service = [Diagnostics.ProcessStartInfo]::new($macrod)+ foreach ($argument in 'service', '--config', $config, '--agent', 'claude-code', '--workspace', $workspace) {+ $service.ArgumentList.Add($argument)+ }+ $service.UseShellExecute = $false+ $service.RedirectStandardInput = $true+ $service.RedirectStandardOutput = $true+ $events = Read-Json-Lines ([Diagnostics.Process]::Start($service)) 300 { param($line) $line.event -eq 'fatal' }+ Check (@($events | Where-Object event -eq 'adapter_installed').Count -eq 1) 'service installs the ACP adapter with npm'+ Check (($events | Where-Object event -eq 'fatal').message -like '*pairing*') 'service then fails only at pairing with the closed port'++ # The harness env is an inline table, and toml_edit writes a path with+ # backslashes as a literal string.+ function Toml-String($key) {+ $found = [regex]::Match((Get-Content $config -Raw), "\b$key = (?:'([^']*)'|`"((?:[^`"\\]|\\.)*)`")")+ if ($found.Groups[1].Success) { return $found.Groups[1].Value }+ return $found.Groups[2].Value -replace '\\\\', '\'+ }+ $adapter = Toml-String 'command'+ $claude = Toml-String 'CLAUDE_CODE_EXECUTABLE'+ Check ($adapter -like '*\node_modules\.bin\claude-agent-acp.cmd' -and (Test-Path $adapter)) "the harness launches the installed adapter ($adapter)"+ Check ($claude -like '*\claude.exe' -and (Test-Path $claude)) "CLAUDE_CODE_EXECUTABLE is the binary behind claude.cmd ($claude)"++ $start = [Diagnostics.ProcessStartInfo]::new($adapter)+ $start.UseShellExecute = $false+ $start.RedirectStandardInput = $true+ $start.RedirectStandardOutput = $true+ $start.Environment['CLAUDE_CODE_EXECUTABLE'] = $claude+ $agent = [Diagnostics.Process]::Start($start)+ $agent.StandardInput.WriteLine('{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}}')+ $cwd = $workspace | ConvertTo-Json+ $agent.StandardInput.WriteLine("{`"jsonrpc`":`"2.0`",`"id`":2,`"method`":`"session/new`",`"params`":{`"cwd`":$cwd,`"mcpServers`":[]}}")+ $answer = Read-Json-Lines $agent 120 { param($line) $line.id -eq 2 } | Where-Object id -eq 2+ Check ($null -ne $answer) 'the adapter answers session/new'+ Check ($null -ne $answer.result.sessionId) "the adapter starts Claude Code for a session ($($answer | ConvertTo-Json -Compress -Depth 6))"+}+finally {+ Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue+}diff --git a/crates/coding_agent_worker/src/executable.rs b/crates/coding_agent_worker/src/executable.rsindex 77450e8390..d70f3d8063 100644--- a/crates/coding_agent_worker/src/executable.rs+++ b/crates/coding_agent_worker/src/executable.rs@@ -24,21 +24,33 @@ pub fn search_paths() -> Vec<PathBuf> {/// The first `command` in `paths`, trying the Windows launcher extensions.pub fn find(paths: &[PathBuf], command: &str) -> Option<PathBuf> {#[cfg(windows)]- let names = [- command.to_owned(),- format!("{command}.exe"),- format!("{command}.cmd"),- format!("{command}.bat"),- ];+ let names = windows_launcher_names(command);#[cfg(not(windows))]let names = [command.to_owned()];+ find_named(paths, &names)+}+fn find_named(paths: &[PathBuf], names: &[String]) -> Option<PathBuf> {paths.iter().flat_map(|directory| names.iter().map(move |name| directory.join(name))).find(|candidate| is_executable(candidate))}+/// The file names Windows can launch for `command`. A bare name never matches+/// as it is: npm puts an extensionless shell script beside every `.cmd` shim,+/// and Windows cannot run it.+#[cfg(any(windows, test))]+fn windows_launcher_names(command: &str) -> Vec<String> {+ if Path::new(command).extension().is_some() {+ return vec![command.to_owned()];+ }+ ["exe", "cmd", "bat", "com"]+ .iter()+ .map(|extension| format!("{command}.{extension}"))+ .collect()+}+/// The program to hand `Command::new` for `command`: on Windows a bare name is/// resolved to its full path, extension included. A name that is not found is/// passed through, so the spawn reports it missing.@@ -67,3 +79,35 @@ fn is_executable(path: &Path) -> bool {fn is_executable(path: &Path) -> bool {path.is_file()}++/// The program an npm `.cmd` shim runs, for a caller that cannot launch+/// `.cmd` files: Node's `child_process.spawn` refuses them without a shell.+/// Any other path comes back unchanged.+pub fn npm_shim_target_or_self(path: &Path) -> PathBuf {+ if path+ .extension()+ .is_some_and(|extension| extension.eq_ignore_ascii_case("cmd"))+ && let Ok(script) = std::fs::read_to_string(path)+ && let Some(target) = npm_shim_target(path, &script)+ {+ return target;+ }+ path.to_owned()+}++/// The path npm's `cmd-shim` runs, written relative to the shim's directory as+/// `"%dp0%\…"`. A shim for a Node script first names `%dp0%\node.exe`, so the+/// last such path is the target.+fn npm_shim_target(shim: &Path, script: &str) -> Option<PathBuf> {+ const SHIM_DIRECTORY: &str = "\"%dp0%\\";+ let start = script.rfind(SHIM_DIRECTORY)? + SHIM_DIRECTORY.len();+ let relative = script[start..].split('"').next()?;+ Some(+ relative+ .split('\\')+ .fold(shim.parent()?.to_owned(), |path, part| path.join(part)),+ )+}++#[cfg(all(test, unix))]+mod test;diff --git a/crates/coding_agent_worker/src/executable/test.rs b/crates/coding_agent_worker/src/executable/test.rsnew file mode 100644index 0000000000..5d651096eb--- /dev/null+++ b/crates/coding_agent_worker/src/executable/test.rs@@ -0,0 +1,101 @@+use std::os::unix::fs::PermissionsExt as _;+use std::path::{Path, PathBuf};++use super::*;++#[test]+fn windows_lookup_takes_the_cmd_shim_over_npms_shell_script() {+ // Node's Windows installer and every global npm package put an+ // extensionless shell script beside the `.cmd` shim. Windows cannot launch+ // the script.+ let directory = tempfile::tempdir().expect("temp dir");+ for name in ["npm", "npm.cmd", "npm.ps1"] {+ let path = directory.path().join(name);+ std::fs::write(&path, "").expect("write stand-in");+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))+ .expect("mark executable");+ }++ let found = find_named(+ &[directory.path().to_owned()],+ &windows_launcher_names("npm"),+ );++ assert_eq!(found, Some(directory.path().join("npm.cmd")));+}++#[test]+fn windows_lookup_keeps_a_name_that_carries_its_extension() {+ let directory = tempfile::tempdir().expect("temp dir");+ let path = directory.path().join("claude.exe");+ std::fs::write(&path, "").expect("write stand-in");+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))+ .expect("mark executable");++ let found = find_named(+ &[directory.path().to_owned()],+ &windows_launcher_names("claude.exe"),+ );++ assert_eq!(found, Some(path));+}++#[test]+fn an_npm_shim_for_a_native_binary_names_the_binary() {+ // What npm writes to `%APPDATA%\npm\claude.cmd` for `@anthropic-ai/claude-code`.+ let script = "@ECHO off\r\n\+GOTO start\r\n\+:find_dp0\r\n\+SET dp0=%~dp0\r\n\+EXIT /b\r\n\+:start\r\n\+SETLOCAL\r\n\+CALL :find_dp0\r\n\+\"%dp0%\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe\" %*\r\n";++ assert_eq!(+ npm_shim_target(Path::new("/npm/claude.cmd"), script),+ Some(PathBuf::from(+ "/npm/node_modules/@anthropic-ai/claude-code/bin/claude.exe"+ ))+ );+}++#[test]+fn an_npm_shim_for_a_node_script_names_the_script() {+ let script = "@ECHO off\r\n\+GOTO start\r\n\+:find_dp0\r\n\+SET dp0=%~dp0\r\n\+EXIT /b\r\n\+:start\r\n\+SETLOCAL\r\n\+CALL :find_dp0\r\n\+\r\n\+IF EXIST \"%dp0%\\node.exe\" (\r\n\+ SET \"_prog=%dp0%\\node.exe\"\r\n\+) ELSE (\r\n\+ SET \"_prog=node\"\r\n\+ SET PATHEXT=%PATHEXT:;.JS;=;%\r\n\+)\r\n\+\r\n\+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js\" %*\r\n";++ assert_eq!(+ npm_shim_target(Path::new("/npm/claude.cmd"), script),+ Some(PathBuf::from(+ "/npm/node_modules/@anthropic-ai/claude-code/cli.js"+ ))+ );+}++#[test]+fn a_hand_written_cmd_file_has_no_npm_target() {+ assert_eq!(+ npm_shim_target(+ Path::new("/tools/claude.cmd"),+ "@echo off\r\nclaude.exe %*\r\n"+ ),+ None+ );+}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rs b/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rsindex d30d456522..6ba4ea4bc7 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rs@@ -7,6 +7,7 @@ const ADAPTER: NpmAdapter = NpmAdapter {bin: "claude-agent-acp",cli: "claude",cli_path_env: "CLAUDE_CODE_EXECUTABLE",+ cli_spawned_by_node: true,};pub(super) struct ClaudeCode;diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/codex.rs b/crates/coding_agent_worker/src/tui/agent_catalog/codex.rsindex 714e8ca882..7d7925fe6d 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog/codex.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog/codex.rs@@ -7,6 +7,7 @@ const ADAPTER: NpmAdapter = NpmAdapter {bin: "codex-acp",cli: "codex",cli_path_env: "CODEX_PATH",+ cli_spawned_by_node: false,};pub(super) struct Codex;diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/npm_adapter.rs b/crates/coding_agent_worker/src/tui/agent_catalog/npm_adapter.rsindex 069aab28e0..d3c6cca802 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog/npm_adapter.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog/npm_adapter.rs@@ -26,6 +26,10 @@ pub(super) struct NpmAdapter {/// catalogue. The value must be absolute: a bare name is looked up on the/// adapter's `PATH`, where its own `node_modules/.bin` comes first.pub(super) cli_path_env: &'static str,+ /// Whether the adapter starts the CLI with Node's `child_process.spawn`,+ /// which refuses Windows `.cmd` files without a shell. The variable then+ /// names the program an npm `.cmd` shim runs instead of the shim.+ pub(super) cli_spawned_by_node: bool,}impl NpmAdapter {@@ -47,6 +51,11 @@ impl NpmAdapter {missing: vec!["HOME"],};};+ let cli_path = if self.cli_spawned_by_node {+ crate::executable::npm_shim_target_or_self(cli_path)+ } else {+ cli_path.to_owned()+ };let install = AdapterInstall {package: self.package,prefix: root.join(self.package),@@ -56,7 +65,7 @@ impl NpmAdapter {kind: preset.kind(),name: preset.name(),launch: LaunchSpec::new(&install.bin.to_string_lossy(), [])- .with_env(self.cli_path_env, cli_path),+ .with_env(self.cli_path_env, &cli_path),note: Some("via npm ACP adapter"),install: Some(install),})diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/test.rs b/crates/coding_agent_worker/src/tui/agent_catalog/test.rsindex 332d876f32..2109ab4e70 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog/test.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog/test.rs@@ -103,6 +103,52 @@ fn adapter_agents_point_the_adapter_at_the_installed_cli() {);}+#[test]+fn claude_code_gets_the_program_behind_an_npm_cmd_shim() {+ // Windows npm installs `claude.cmd`. The Claude SDK spawns+ // `CLAUDE_CODE_EXECUTABLE` without a shell, and Node refuses `.cmd` files+ // there, so the adapter must get the binary the shim runs. codex-acp is a+ // native program that launches `.cmd` files itself.+ let npm = tempfile::tempdir().expect("temp dir");+ let claude = npm.path().join("claude.cmd");+ std::fs::write(+ &claude,+ "@ECHO off\r\nCALL :find_dp0\r\n\"%dp0%\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe\" %*\r\n",+ )+ .expect("write shim");+ let codex = npm.path().join("codex.cmd");+ std::fs::write(+ &codex,+ "@ECHO off\r\n\"%_prog%\" \"%dp0%\\node_modules\\@openai\\codex\\bin\\codex.js\" %*\r\n",+ )+ .expect("write shim");+ let commands = Commands(HashMap::from([+ ("claude", claude),+ ("codex", codex.clone()),+ ("npm", npm.path().join("npm.cmd")),+ ]));++ let agents = discover(&commands);++ assert_eq!(+ agents[0].launch.env,+ BTreeMap::from([(+ "CLAUDE_CODE_EXECUTABLE".to_owned(),+ npm.path()+ .join("node_modules/@anthropic-ai/claude-code/bin/claude.exe")+ .to_string_lossy()+ .into_owned()+ )])+ );+ assert_eq!(+ agents[1].launch.env,+ BTreeMap::from([(+ "CODEX_PATH".to_owned(),+ codex.to_string_lossy().into_owned()+ )])+ );+}+#[test]fn existing_launch_specs_are_recognized() {assert_eq!(name_for(&harness("hermes", &["acp"])), Some("Hermes Agent"));diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/test_macrod_update.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/test_macrod_update.rsindex e399110da1..3e6a1235bc 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/test_macrod_update.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/test_macrod_update.rs@@ -85,8 +85,9 @@ fn macos_job() -> Job {)}-/// Windows has no hot handoff: this checks the launcher layout and the-/// installer, with builds from the runner's MSVC toolchain.+/// Windows has no hot handoff: this checks the launcher layout, the+/// installer, and Claude Code installed from npm, with builds from the+/// runner's MSVC toolchain.fn windows_job() -> Job {Job::default().name("macrod update (windows)")@@ -111,6 +112,17 @@ fn windows_job() -> Job {"& ./{E2E}/windows_update_test.ps1 -Releases \"$env:RUNNER_TEMP/releases\" -V1 {V1} -V2 {V2}")).shell("pwsh"),+ ) .add_step(+ Step::new("Setup Node")+ .uses("actions", "setup-node", "v4")+ .add_with(("node-version", "24")),+ )+ .add_step(+ Step::new("Claude Code from npm")+ .run(format!(+ "& ./{E2E}/windows_claude_code_test.ps1 -Releases \"$env:RUNNER_TEMP/releases\" -Version {V2}"+ ))+ .shell("pwsh"),)}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/test_macrod_update/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/test_macrod_update/test.rsindex 3657ee9c05..553002cafe 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/test_macrod_update/test.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/test_macrod_update/test.rs@@ -14,5 +14,6 @@ fn runs_the_end_to_end_tests_on_every_platform() {}assert!(yaml.contains("update_e2e.py"));assert!(yaml.contains("windows_test.ps1"));+ assert!(yaml.contains("windows_claude_code_test.ps1"));assert!(yaml.contains("crates/coding_agent_worker/**"));}