From 6d720623b5e02aa3bcaf1a97b406fbf04dc67758 Mon Sep 17 00:00:00 2001 From: Dionisio Chiuratto Agourakis Date: Wed, 28 Oct 2026 03:57:14 -0300 Subject: [PATCH] fix(windows): harden POSIX assumptions across installer, MCP, hooks, and Rust runtime --- .gitattributes | 16 +++++ crates/leio-harness/src/acp.rs | 16 +++++ crates/leio-harness/src/agents.rs | 1 + crates/leio-harness/src/delivery.rs | 4 +- crates/leio-harness/src/embed.rs | 1 + crates/leio-harness/src/merge.rs | 16 ++--- crates/leio-harness/src/process.rs | 33 ++++++++++ crates/leio-harness/src/task.rs | 9 +-- crates/leio-harness/src/workflow.rs | 12 ++-- crates/leio-harness/src/worktree.rs | 10 +-- hooks/session-context.sh | 19 +++--- mcp/harness-review.js | 8 ++- mcp/harness-tasks.js | 9 ++- mcp/index.js | 1 + mcp/resolve-binary.js | 67 +++++++++++++++++---- mcp/resolve-binary.test.js | 15 +++++ mcp/watch-state.js | 20 +++++- packaging/npm/package.json | 1 + packaging/package.json | 5 ++ packaging/python/pyproject.toml | 2 +- packaging/python/src/leio_code/package.json | 5 ++ packaging/python/src/leio_code/register.py | 9 ++- packaging/register-mcp.js | 16 ++++- packaging/register-mcp.test.js | 12 ++++ scripts/install_codex_plugin.py | 17 ++++-- scripts/launch-stdio-mcp.sh | 33 ++++++++-- src/checkout.rs | 30 +++++++++ src/kb.rs | 8 ++- src/main.rs | 1 + src/sidecar.rs | 34 ++++++++++- src/update.rs | 60 ++++++++++++------ 31 files changed, 401 insertions(+), 89 deletions(-) create mode 100644 .gitattributes create mode 100644 packaging/package.json create mode 100644 packaging/python/src/leio_code/package.json diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..7c7597e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,16 @@ +# Ensure shell scripts and source files keep LF line endings on Windows checkouts +*.sh text eol=lf +*.bash text eol=lf +*.js text eol=lf +*.mjs text eol=lf +*.cjs text eol=lf +*.ts text eol=lf +*.py text eol=lf +*.rs text eol=lf +*.toml text eol=lf +*.json text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.md text eol=lf +Makefile* text eol=lf +Dockerfile* text eol=lf diff --git a/crates/leio-harness/src/acp.rs b/crates/leio-harness/src/acp.rs index c0bc788..b34703c 100644 --- a/crates/leio-harness/src/acp.rs +++ b/crates/leio-harness/src/acp.rs @@ -69,6 +69,22 @@ pub fn serve(spec: AgentSessionSpec) -> Result { "LOGNAME", "SHELL", "TMPDIR", + "TEMP", + "TMP", + "SystemRoot", + "SYSTEMROOT", + "WINDIR", + "COMSPEC", + "PATHEXT", + "USERPROFILE", + "APPDATA", + "LOCALAPPDATA", + "PROGRAMDATA", + "PROGRAMFILES", + "PROGRAMFILES(X86)", + "HOMEDRIVE", + "HOMEPATH", + "USERNAME", "LANG", "LC_ALL", "TERM", diff --git a/crates/leio-harness/src/agents.rs b/crates/leio-harness/src/agents.rs index a2019ea..572984e 100644 --- a/crates/leio-harness/src/agents.rs +++ b/crates/leio-harness/src/agents.rs @@ -71,6 +71,7 @@ const MIN_CONTEXT_LENGTH: u64 = 100_000; /// `~/.config/leio-harness/openrouter-models.json` (HOME-dependent). pub fn models_cache_path() -> Option { std::env::var("HOME") + .or_else(|_| std::env::var("USERPROFILE")) .ok() .filter(|home| !home.trim().is_empty()) .map(|home| Path::new(&home).join(".config/leio-harness/openrouter-models.json")) diff --git a/crates/leio-harness/src/delivery.rs b/crates/leio-harness/src/delivery.rs index 33f2b73..9d30413 100644 --- a/crates/leio-harness/src/delivery.rs +++ b/crates/leio-harness/src/delivery.rs @@ -73,7 +73,7 @@ fn safe_path(path: &Path) -> Result<()> { fn root(target: &Path) -> Result { boundary_path(target)?; fs::create_dir_all(target)?; - let target = target.canonicalize()?; + let target = crate::process::clean_canonicalize(target)?; for name in ["releases", "state.jsonld", ".lock"] { safe_path(&target.join(name))?; } @@ -292,7 +292,7 @@ fn authorization(target: &Path, action: &str, id: &str, current: &State) -> Resu /// Stage a directory containing actual build output. Does not claim to run a build. pub fn prepare(source: &Path, target: &Path) -> Result { boundary_path(source)?; - let source = source.canonicalize()?; + let source = crate::process::clean_canonicalize(source)?; let target = root(target)?; ensure!( !target.starts_with(&source) && !source.starts_with(&target), diff --git a/crates/leio-harness/src/embed.rs b/crates/leio-harness/src/embed.rs index fa29bc4..05fd14c 100644 --- a/crates/leio-harness/src/embed.rs +++ b/crates/leio-harness/src/embed.rs @@ -69,6 +69,7 @@ fn default_config_values() -> std::collections::HashMap { .map(std::path::PathBuf::from) .or_else(|| { std::env::var("HOME") + .or_else(|_| std::env::var("USERPROFILE")) .ok() .map(|home| std::path::Path::new(&home).join(".config/leio-harness/env")) }); diff --git a/crates/leio-harness/src/merge.rs b/crates/leio-harness/src/merge.rs index 011a03c..767e275 100644 --- a/crates/leio-harness/src/merge.rs +++ b/crates/leio-harness/src/merge.rs @@ -102,7 +102,7 @@ pub(crate) fn validate_merge_target( target_ref: &str, ) -> Result { let repo_root = canonical_repo_root(repo_root)?; - let worktree = std::fs::canonicalize(worktree) + let worktree = crate::process::clean_canonicalize(worktree) .with_context(|| format!("canonicalize {}", worktree.display()))?; assert_linked(&repo_root, &worktree)?; validate_ref(source_branch)?; @@ -174,10 +174,10 @@ fn combined_output(output: &Output) -> String { } fn canonical_repo_root(path: &Path) -> Result { - let expected = - std::fs::canonicalize(path).with_context(|| format!("canonicalize {}", path.display()))?; + let expected = crate::process::clean_canonicalize(path) + .with_context(|| format!("canonicalize {}", path.display()))?; let actual = git(&expected, &["rev-parse", "--show-toplevel"])?; - let actual = std::fs::canonicalize(actual.trim())?; + let actual = crate::process::clean_canonicalize(actual.trim())?; if expected != actual { bail!("repository root mismatch"); } @@ -188,18 +188,18 @@ fn canonical_repo_root(path: &Path) -> Result { /// checkout itself). Prevents merging into an arbitrary directory. fn assert_linked(repo_root: &Path, worktree: &Path) -> Result<()> { let top = git(worktree, &["rev-parse", "--show-toplevel"])?; - if std::fs::canonicalize(top.trim())? != worktree { + if crate::process::clean_canonicalize(top.trim())? != worktree { bail!("worktree is not a git checkout root"); } let common_raw = git(worktree, &["rev-parse", "--git-common-dir"])? .trim() .to_owned(); let common = if Path::new(&common_raw).is_absolute() { - std::fs::canonicalize(&common_raw)? + crate::process::clean_canonicalize(&common_raw)? } else { - std::fs::canonicalize(worktree.join(&common_raw))? + crate::process::clean_canonicalize(worktree.join(&common_raw))? }; - let repo_git = std::fs::canonicalize(repo_root.join(".git"))?; + let repo_git = crate::process::clean_canonicalize(repo_root.join(".git"))?; if common != repo_git { bail!("worktree is not linked to repository root"); } diff --git a/crates/leio-harness/src/process.rs b/crates/leio-harness/src/process.rs index b3a9d16..eb4fb3e 100644 --- a/crates/leio-harness/src/process.rs +++ b/crates/leio-harness/src/process.rs @@ -31,6 +31,23 @@ pub(crate) fn unique_id() -> String { ) } +/// Strip the Windows verbatim drive prefix (`\\?\C:\...` -> `C:\...`) added by +/// `std::fs::canonicalize` so paths match `git rev-parse --show-toplevel` and +/// Node `fs.realpathSync` on Windows. +pub(crate) fn strip_windows_verbatim(path: PathBuf) -> PathBuf { + if let Some(raw) = path.to_str() + && let Some(stripped) = raw.strip_prefix(r"\\?\") + && stripped.as_bytes().get(1) == Some(&b':') + { + return PathBuf::from(stripped); + } + path +} + +pub(crate) fn clean_canonicalize(path: impl AsRef) -> std::io::Result { + std::fs::canonicalize(path).map(strip_windows_verbatim) +} + pub fn run(spec: RunSpec) -> Result { run_observed(spec, None) } @@ -79,6 +96,22 @@ pub fn run_observed(spec: RunSpec, observer: Option>) -> Re "LOGNAME", "SHELL", "TMPDIR", + "TEMP", + "TMP", + "SystemRoot", + "SYSTEMROOT", + "WINDIR", + "COMSPEC", + "PATHEXT", + "USERPROFILE", + "APPDATA", + "LOCALAPPDATA", + "PROGRAMDATA", + "PROGRAMFILES", + "PROGRAMFILES(X86)", + "HOMEDRIVE", + "HOMEPATH", + "USERNAME", "LANG", "LC_ALL", "TERM", diff --git a/crates/leio-harness/src/task.rs b/crates/leio-harness/src/task.rs index f88b2ba..e446924 100644 --- a/crates/leio-harness/src/task.rs +++ b/crates/leio-harness/src/task.rs @@ -89,7 +89,7 @@ fn root(repo: &Path) -> Result { repo.is_absolute() && repo.is_dir(), "repo must be an absolute existing directory" ); - Ok(repo.canonicalize()?) + Ok(crate::process::clean_canonicalize(repo)?) } fn runs(repo: &Path) -> PathBuf { repo.join(".leio-code/harness/runs") @@ -252,10 +252,11 @@ pub fn submit( #[cfg(unix)] let checkout = { let top_bytes = top.stdout.strip_suffix(b"\n").unwrap_or(&top.stdout); - Path::new(std::ffi::OsStr::from_bytes(top_bytes)).canonicalize()? + crate::process::clean_canonicalize(Path::new(std::ffi::OsStr::from_bytes(top_bytes)))? }; #[cfg(not(unix))] - let checkout = Path::new(std::str::from_utf8(&top.stdout)?.trim()).canonicalize()?; + let checkout = + crate::process::clean_canonicalize(Path::new(std::str::from_utf8(&top.stdout)?.trim()))?; ensure!( repo == checkout, "task repo must be the Git checkout root ({}); constrain module scope in the task instead of submitting a subdirectory", @@ -638,7 +639,7 @@ fn collect(spec: &TaskSpec, dir: &Path, tracker: &Tracker) -> Result<()> { ); let source = repo.join(relative); let metadata = std::fs::symlink_metadata(&source)?; - if !metadata.is_file() || !source.canonicalize()?.starts_with(repo) { + if !metadata.is_file() || !crate::process::clean_canonicalize(&source)?.starts_with(repo) { truncated = true; continue; } diff --git a/crates/leio-harness/src/workflow.rs b/crates/leio-harness/src/workflow.rs index 61ea134..d17cc7d 100644 --- a/crates/leio-harness/src/workflow.rs +++ b/crates/leio-harness/src/workflow.rs @@ -153,12 +153,14 @@ pub fn apply_with_deployment_policy( let plan: Plan = serde_json::from_slice(&fs::read(input.context("--input plan required")?)?)?; validate(&plan)?; - let root = repo.context("--repo required")?.canonicalize()?; + let root = crate::process::clean_canonicalize(repo.context("--repo required")?)?; ensure!(root.is_dir(), "repository must be a directory"); let id = format!( "urn:leio:workflow:run:{}", hex::encode(Sha256::digest( - dir.canonicalize()?.to_string_lossy().as_bytes() + crate::process::clean_canonicalize(dir)? + .to_string_lossy() + .as_bytes() )) ); let state = Workflow { @@ -284,7 +286,9 @@ pub fn apply_with_deployment_policy( run_id: format!("attempt-{}", state.attempts), argv: step.argv, cwd: state.repo.display().to_string(), - output_dir: dir.canonicalize()?.display().to_string(), + output_dir: crate::process::clean_canonicalize(dir)? + .display() + .to_string(), timeout_ms: step.timeout_ms, kill_grace_ms: 1000, max_output_bytes: 1024 * 1024, @@ -298,7 +302,7 @@ pub fn apply_with_deployment_policy( let mut artifacts = Vec::new(); // Failed commands can still produce useful partial artifacts. for name in step.artifacts { - match state.repo.join(&name).canonicalize().and_then(|path| { + match crate::process::clean_canonicalize(state.repo.join(&name)).and_then(|path| { if !path.starts_with(&state.repo) { return Err(std::io::Error::other("artifact escapes repository")); } fs::read(path) }) { diff --git a/crates/leio-harness/src/worktree.rs b/crates/leio-harness/src/worktree.rs index 77b5341..0ac8346 100644 --- a/crates/leio-harness/src/worktree.rs +++ b/crates/leio-harness/src/worktree.rs @@ -132,10 +132,10 @@ pub fn retire( } fn canonical_repo_root(path: &Path) -> Result { - let expected = - std::fs::canonicalize(path).with_context(|| format!("canonicalize {}", path.display()))?; + let expected = crate::process::clean_canonicalize(path) + .with_context(|| format!("canonicalize {}", path.display()))?; let actual = git(&expected, &["rev-parse", "--show-toplevel"])?; - let actual = std::fs::canonicalize(actual.trim())?; + let actual = crate::process::clean_canonicalize(actual.trim())?; if expected != actual { bail!( "repository root mismatch: expected {}, got {}", @@ -148,10 +148,10 @@ fn canonical_repo_root(path: &Path) -> Result { fn normalize_absolute(path: &Path) -> Result { if path.exists() { - return Ok(std::fs::canonicalize(path)?); + return Ok(crate::process::clean_canonicalize(path)?); } let parent = path.parent().context("path has no parent")?; - let parent = std::fs::canonicalize(parent)?; + let parent = crate::process::clean_canonicalize(parent)?; Ok(parent.join(path.file_name().context("path has no file name")?)) } diff --git a/hooks/session-context.sh b/hooks/session-context.sh index d6c1823..de250f6 100755 --- a/hooks/session-context.sh +++ b/hooks/session-context.sh @@ -7,14 +7,11 @@ if [[ ! -f "$SKILL" ]]; then printf 'LEIO Code skill missing at %s\n' "$SKILL" exit 0 fi -python3 - "$SKILL" <<'PY' -from pathlib import Path -import sys - -text = Path(sys.argv[1]).read_text() -if text.startswith("---"): - parts = text.split("---", 2) - if len(parts) >= 3: - text = parts[2].lstrip("\n") -print(text, end="") -PY +awk ' + { line = $0; sub(/\r$/, "", line) } + NR == 1 && line == "---" { in_fm = 1; next } + in_fm && line == "---" { in_fm = 0; skip_blank = 1; next } + in_fm { next } + skip_blank && line == "" { next } + { skip_blank = 0; print line } +' "$SKILL" diff --git a/mcp/harness-review.js b/mcp/harness-review.js index 096ca66..93844e7 100644 --- a/mcp/harness-review.js +++ b/mcp/harness-review.js @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import os from 'node:os'; import path from 'node:path'; import {createHash,randomUUID} from 'node:crypto'; @@ -18,7 +19,7 @@ function directory(target) { function readRegular(target,max) { if(fs.realpathSync(path.dirname(target)) !== path.dirname(target)) throw new Error('Review path must not contain symlinks'); - const fd=fs.openSync(target,fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); + const fd=fs.openSync(target,(fs.constants.O_RDONLY ?? 0) | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0)); try { const before=fs.fstatSync(fd); if(!before.isFile() || before.size>max) throw new Error('Review input must be a regular file within the byte limit'); @@ -42,7 +43,7 @@ console.log(JSON.stringify({selected_files_unchanged:true,files:files.length,sco export async function captureReview(input,runProcess) { const git=async(args,cwd=input.repo_root)=>{ - const result=await runProcess('git',args,cwd,15000,{GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_CONFIG_COUNT:'0'}); + const result=await runProcess('git',args,cwd,15000,{GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:os.devNull,GIT_CONFIG_COUNT:'0'}); if(result.code!==0)throw new Error(result.stderr.trim() || 'Review Git setup failed'); return result.stdout.replace(/\r?\n$/,''); }; @@ -59,12 +60,13 @@ export async function captureReview(input,runProcess) { } const catalog=path.join(input.repo_root,'.leio-code/harness/reviews');directory(catalog); const id=`${Date.now()}-${randomUUID()}`,owner=path.join(catalog,id),root=path.join(owner,'snapshot');directory(root); + const emptyHooks=path.join(owner,'empty-hooks');directory(emptyHooks); for(const file of selected) { const target=path.join(root,file.path);directory(path.dirname(target)); fs.writeFileSync(target,file.bytes,{flag:'wx',mode:file.mode}); } await git(['init','-q','--template='],root); - await git(['config','core.hooksPath','/dev/null'],root); + await git(['config','core.hooksPath',emptyHooks],root); directory(path.join(root,'.git/info')); fs.writeFileSync(path.join(root,'.git/info/exclude'),'.leio-code/\n'); await git(['--literal-pathspecs','add','--force','--',...selected.map(f=>f.path)],root); diff --git a/mcp/harness-tasks.js b/mcp/harness-tasks.js index 2c5eae5..d39fbf9 100644 --- a/mcp/harness-tasks.js +++ b/mcp/harness-tasks.js @@ -40,9 +40,12 @@ function executable(candidate) { } export function codexArguments(input, {home = os.homedir(), find = findInstalledBinary, readOnly = false, servers = []} = {}) { + const standaloneDir = path.join(home, '.codex/packages/standalone/current/bin'); const binary = input.codex_binary ? executable(input.codex_binary) - : executable(path.join(home,'.codex/packages/standalone/current/bin/codex')) || executable(find('codex',{homeDir:home,accept:candidate=>Boolean(executable(candidate))})); + : executable(path.join(standaloneDir, 'codex')) + || (process.platform === 'win32' && (executable(path.join(standaloneDir, 'codex.exe')) || executable(path.join(standaloneDir, 'codex.cmd')))) + || executable(find('codex',{homeDir:home,accept:candidate=>Boolean(executable(candidate))})); if (!binary) throw new Error('No executable Codex found; supply codex_binary as an absolute executable path. Existing Codex login is required.'); if(readOnly && servers.some(name=>!/^[-A-Za-z0-9_]+$/.test(name)))throw new Error('Cannot isolate an MCP server name containing dots or special characters with Codex CLI overrides; review was not started'); const constraints = [...DEFAULT_CONSTRAINTS,...(input.constraints ?? [])]; @@ -70,7 +73,7 @@ export function artifactPreview(repo, id, relative, bytes, tail = false) { const target = path.join(run,relative); empty.path = target; if (fs.realpathSync(path.dirname(target)) !== path.dirname(target)) throw new Error('redirected artifact directory'); - fd = fs.openSync(target,fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); + fd = fs.openSync(target,(fs.constants.O_RDONLY ?? 0) | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0)); const info = fs.fstatSync(fd); if (!info.isFile()) throw new Error('artifact is not a regular file'); const count = Math.min(info.size,bytes); @@ -107,7 +110,7 @@ function newFilePreviews(task, bytes) { } const preview=artifactPreview(task.repoRoot,task.runId,path.join('untracked',relative),remaining); remaining-=Buffer.byteLength(preview.text); - files.push({file:relative,preview}); + files.push({file:relative.split(path.sep).join('/'),preview}); } return {new_files:files,new_files_incomplete:Boolean(task.untrackedTruncated || files.length!f.preview.available || f.preview.truncated))}; } diff --git a/mcp/index.js b/mcp/index.js index 4886ef8..82d2eb5 100644 --- a/mcp/index.js +++ b/mcp/index.js @@ -472,6 +472,7 @@ function startDetachedLeio(subcommandArgs, repoRoot, { pidName, logName }) { const child = spawn(invocation.command, invocation.args, { cwd: invocation.cwd, detached: true, + windowsHide: true, stdio: ["ignore", logFd, logFd], env: process.env, }); diff --git a/mcp/resolve-binary.js b/mcp/resolve-binary.js index 05c9342..ed53acc 100644 --- a/mcp/resolve-binary.js +++ b/mcp/resolve-binary.js @@ -12,14 +12,18 @@ export function isCargoTargetBinary( candidate, { cargoTargetDir = process.env.CARGO_TARGET_DIR ?? "" } = {}, ) { - const normalized = String(candidate ?? "").split(path.sep).join("/"); - if (/\/target\/(?:[^/]+\/)?(?:release|debug)(?:\/|$)/.test(normalized)) { + const normalized = String(candidate ?? "").replace(/\\/g, "/"); + if (/\/target\/(?:[^/]+\/)?(?:release|debug)(?:\/|$)/i.test(normalized)) { return true; } const targetDir = String(cargoTargetDir ?? "").trim(); if (targetDir) { - const prefix = path.resolve(targetDir).split(path.sep).join("/"); - if (normalized === prefix || normalized.startsWith(`${prefix}/`)) { + const prefix = path.resolve(targetDir).replace(/\\/g, "/"); + const normCmp = + process.platform === "win32" ? normalized.toLowerCase() : normalized; + const prefixCmp = + process.platform === "win32" ? prefix.toLowerCase() : prefix; + if (normCmp === prefixCmp || normCmp.startsWith(`${prefixCmp}/`)) { return TARGET_PROFILE.test(normalized.slice(prefix.length)); } } @@ -109,6 +113,36 @@ export function findBinaryUpwards( * `~/.cargo/bin`) keeps the executable source user-owned and avoids running an * arbitrary `target/release/leio-code` from the repository being inspected. */ +function binaryVariants(binaryName) { + if (process.platform === "win32" && binaryName && !path.extname(binaryName)) { + return [binaryName, `${binaryName}.exe`, `${binaryName}.cmd`]; + } + return [binaryName]; +} + +function resolveEnvCandidate( + candidate, + { homeDir = os.homedir(), exists = fs.existsSync, stat = defaultStat } = {}, +) { + let trimmed = String(candidate ?? "").trim(); + if (!trimmed) { + return null; + } + if (homeDir && /^\$\{HOME\}[/\\]/.test(trimmed)) { + trimmed = path.join(homeDir, trimmed.slice("${HOME}/".length)); + } + if (isTrustedEnvBinary(trimmed, { exists, stat })) { + return path.resolve(trimmed); + } + if ( + path.basename(trimmed) === "leio-code" && + isTrustedEnvBinary(`${trimmed}.exe`, { exists, stat }) + ) { + return path.resolve(`${trimmed}.exe`); + } + return null; +} + export function findInstalledBinary( binaryName, { @@ -121,6 +155,7 @@ export function findInstalledBinary( } = {}, ) { const candidates = []; + const names = binaryVariants(binaryName); const cargoRoot = cargoHome.trim() ? path.resolve(cargoHome) : homeDir @@ -128,13 +163,17 @@ export function findInstalledBinary( : null; if (cargoRoot) { - candidates.push(path.join(cargoRoot, "bin", binaryName)); + for (const name of names) { + candidates.push(path.join(cargoRoot, "bin", name)); + } } for (const entry of pathValue.split(path.delimiter)) { const trimmed = entry.trim(); if (trimmed) { - candidates.push(path.join(path.resolve(trimmed), binaryName)); + for (const name of names) { + candidates.push(path.join(path.resolve(trimmed), name)); + } } } @@ -168,13 +207,17 @@ export function resolveBinaryPath({ exists = fs.existsSync, stat = defaultStat, } = {}) { - const trimmed = String(envPath ?? "").trim(); - if (trimmed && isTrustedEnvBinary(trimmed, { exists, stat })) { - return path.resolve(trimmed); + const resolvedEnv = resolveEnvCandidate(envPath, { homeDir, exists, stat }); + if (resolvedEnv) { + return resolvedEnv; } - const bundled = String(bundledBinaryPath ?? "").trim(); - if (bundled && isTrustedEnvBinary(bundled, { exists, stat })) { - return path.resolve(bundled); + const resolvedBundled = resolveEnvCandidate(bundledBinaryPath, { + homeDir, + exists, + stat, + }); + if (resolvedBundled) { + return resolvedBundled; } if (!binaryName) { return null; diff --git a/mcp/resolve-binary.test.js b/mcp/resolve-binary.test.js index 2bef559..fcccf2d 100644 --- a/mcp/resolve-binary.test.js +++ b/mcp/resolve-binary.test.js @@ -339,3 +339,18 @@ test("isTrustedEnvBinary rejects directories and wrong basenames", () => { null, ); }); + +test("resolveBinaryPath expands ${HOME} and falls back to .exe for LEIO_CODE_BIN on Windows", () => { + const homeDir = "/Users/win-test"; + const exePath = `${homeDir}/.cargo/bin/leio-code.exe`; + assert.equal( + resolveBinaryPath({ + binaryName: "leio-code.exe", + envPath: "${HOME}/.cargo/bin/leio-code", + homeDir, + exists: (candidate) => candidate === exePath, + stat: () => ({ isFile: () => true, isDirectory: () => false }), + }), + exePath, + ); +}); diff --git a/mcp/watch-state.js b/mcp/watch-state.js index bd30aec..d6ff319 100644 --- a/mcp/watch-state.js +++ b/mcp/watch-state.js @@ -29,7 +29,7 @@ export function encodeWatchRecord({ pid, token, binaryPath }) { export function parseWatchRecord(raw) { const lines = String(raw ?? "") .trim() - .split("\n"); + .split(/\r?\n/); const pid = Number.parseInt(lines[0] ?? "", 10); if (!Number.isFinite(pid) || pid <= 0) { return null; @@ -86,6 +86,24 @@ export function rememberedSpawn(key) { export function processLooksLikeBinary(pid, binaryPath) { const base = path.basename(binaryPath || "leio-code"); let cmd = ""; + if (process.platform === "win32") { + try { + cmd = execFileSync( + "tasklist", + ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], + { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + timeout: 1500, + windowsHide: true, + }, + ); + } catch { + return false; + } + const lower = cmd.toLowerCase(); + return lower.includes(base.toLowerCase()) || lower.includes("leio-code"); + } try { cmd = fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").replace(/\0/g, " "); } catch { diff --git a/packaging/npm/package.json b/packaging/npm/package.json index 6ffe5b2..0be7e16 100644 --- a/packaging/npm/package.json +++ b/packaging/npm/package.json @@ -23,6 +23,7 @@ "files": [ "bin", "server", + "skills", "install.js", "register-mcp.js", "README.md" diff --git a/packaging/package.json b/packaging/package.json new file mode 100644 index 0000000..47e3c0b --- /dev/null +++ b/packaging/package.json @@ -0,0 +1,5 @@ +{ + "name": "leio-code-packaging", + "private": true, + "type": "module" +} diff --git a/packaging/python/pyproject.toml b/packaging/python/pyproject.toml index 24ef1ce..2f36ef5 100644 --- a/packaging/python/pyproject.toml +++ b/packaging/python/pyproject.toml @@ -31,4 +31,4 @@ leio-mcp = "leio_code.mcp:main" where = ["src"] [tool.setuptools.package-data] -leio_code = ["bin/*", "mcp/**/*", "register-mcp.js"] +leio_code = ["bin/*", "mcp/**/*", "skills/**/*", "register-mcp.js", "package.json"] diff --git a/packaging/python/src/leio_code/package.json b/packaging/python/src/leio_code/package.json new file mode 100644 index 0000000..029a39a --- /dev/null +++ b/packaging/python/src/leio_code/package.json @@ -0,0 +1,5 @@ +{ + "name": "leio-code-wheel-runtime", + "private": true, + "type": "module" +} diff --git a/packaging/python/src/leio_code/register.py b/packaging/python/src/leio_code/register.py index b46a760..fed59a8 100644 --- a/packaging/python/src/leio_code/register.py +++ b/packaging/python/src/leio_code/register.py @@ -30,7 +30,14 @@ def _ensure(home: str | None) -> None: env["LEIO_MCP_HOME"] = str(home_dir) env["LEIO_MCP_COMMAND"] = node env["LEIO_MCP_ARGS"] = json.dumps([str(launcher)]) - subprocess.run([node, str(script)], env=env, check=False) + subprocess.run( + [node, str(script)], + env=env, + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) def _already(path: Path, node: str, launcher: Path) -> bool: diff --git a/packaging/register-mcp.js b/packaging/register-mcp.js index 9ac369d..490194c 100644 --- a/packaging/register-mcp.js +++ b/packaging/register-mcp.js @@ -168,7 +168,7 @@ export function mergeToml(file, spec) { `command = ${JSON.stringify(spec.command)}`, `args = ${JSON.stringify(spec.args)}`, ]; - const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + const current = (fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "").replace(/\r\n/g, "\n"); if ( current.includes(`[mcp_servers.leio-code]`) && current.includes(`command = ${JSON.stringify(spec.command)}`) @@ -202,7 +202,19 @@ function readSpec() { return serverSpec(command, args); } -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { +function isDirectExecution() { + if (!process.argv[1]) return false; + try { + return ( + fs.realpathSync(fileURLToPath(import.meta.url)) === + fs.realpathSync(process.argv[1]) + ); + } catch { + return import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href; + } +} + +if (isDirectExecution()) { const home = process.env.LEIO_MCP_HOME || os.homedir(); applyRegistration(home, readSpec()); } diff --git a/packaging/register-mcp.test.js b/packaging/register-mcp.test.js index ba05f00..83f3668 100644 --- a/packaging/register-mcp.test.js +++ b/packaging/register-mcp.test.js @@ -137,6 +137,18 @@ test("mergeJson, mergeToml, and skill sync handle malformed inputs and updates", assert.match(updatedToml, /\[other_section\]/); assert.equal(mergeToml(tomlFile, spec), false); + const crlfToml = path.join(dir, "crlf-config.toml"); + fs.writeFileSync( + crlfToml, + "[mcp_servers.other]\r\ncommand = \"other\"\r\n\r\n[mcp_servers.leio-code]\r\ncommand = \"old\"\r\nargs = []\r\n", + ); + assert.equal(mergeToml(crlfToml, spec), true); + assert.equal(mergeToml(crlfToml, spec), false); + assert.equal( + fs.readFileSync(crlfToml, "utf8").match(/\[mcp_servers\.leio-code\]/g).length, + 1, + ); + assert.equal(resolveDefaultSkillSource(path.join(dir, "missing-skill")), null); assert.deepEqual(installDefaultSkill(dir, path.join(dir, "missing-skill")), []); diff --git a/scripts/install_codex_plugin.py b/scripts/install_codex_plugin.py index 39d0013..4e80822 100644 --- a/scripts/install_codex_plugin.py +++ b/scripts/install_codex_plugin.py @@ -124,10 +124,15 @@ def install_plugin(source_root: Path, repo_root: Path, mode: str, force: bool) - else: shutil.rmtree(dest) + symlinked = False if mode == "symlink" and source_root.is_dir(): symlink_target = Path(os.path.relpath(source_root, dest.parent)) - dest.symlink_to(symlink_target, target_is_directory=True) - else: + try: + dest.symlink_to(symlink_target, target_is_directory=True) + symlinked = True + except OSError: + symlinked = False + if not symlinked: dest.mkdir(parents=True, exist_ok=True) for rel in INCLUDED_PATHS: src = source_root / rel @@ -171,7 +176,10 @@ def ensure_marketplace_root_compatibility(repo_root: Path, installed_path: Path) shutil.rmtree(compat_dest) compat_target = Path(os.path.relpath(installed_path, compat_dest.parent)) - compat_dest.symlink_to(compat_target, target_is_directory=True) + try: + compat_dest.symlink_to(compat_target, target_is_directory=True) + except OSError: + shutil.copytree(installed_path, compat_dest, dirs_exist_ok=True, symlinks=False) return compat_dest @@ -186,7 +194,8 @@ def prepare_mcp_dependencies(plugin_root: Path) -> None: if node_modules.is_dir(): return - base_cmd = ["npm", "ci", "--omit=dev"] if lockfile.is_file() else ["npm", "install", "--omit=dev"] + npm_bin = shutil.which("npm") or "npm" + base_cmd = [npm_bin, "ci", "--omit=dev"] if lockfile.is_file() else [npm_bin, "install", "--omit=dev"] try: subprocess.run(base_cmd, cwd=mcp_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except FileNotFoundError as exc: diff --git a/scripts/launch-stdio-mcp.sh b/scripts/launch-stdio-mcp.sh index e1b84cf..91068dd 100755 --- a/scripts/launch-stdio-mcp.sh +++ b/scripts/launch-stdio-mcp.sh @@ -2,13 +2,19 @@ # Single stdio MCP bootstrap for the Claude plugin and project .mcp.json. set -euo pipefail +HOME="${HOME:-${USERPROFILE:-}}" + # Claude Desktop often starts MCP with a stripped PATH. Prefer the cargo-installed # binary so a stale unpacked snapshot cannot win via walk-up `target/`. -if [[ -z "${LEIO_CODE_BIN:-}" && -x "${HOME}/.cargo/bin/leio-code" ]]; then - export LEIO_CODE_BIN="${HOME}/.cargo/bin/leio-code" +if [[ -z "${LEIO_CODE_BIN:-}" && -n "${HOME}" ]]; then + if [[ -x "${HOME}/.cargo/bin/leio-code.exe" ]]; then + export LEIO_CODE_BIN="${HOME}/.cargo/bin/leio-code.exe" + elif [[ -x "${HOME}/.cargo/bin/leio-code" ]]; then + export LEIO_CODE_BIN="${HOME}/.cargo/bin/leio-code" + fi fi for dir in "${HOME}/.cargo/bin" "${HOME}/.local/bin" "/opt/homebrew/bin" "/usr/local/bin"; do - if [[ -d "${dir}" ]]; then + if [[ -n "${dir}" && -d "${dir}" ]]; then case ":${PATH}:" in *":${dir}:"*) ;; *) export PATH="${dir}:${PATH}" ;; @@ -20,8 +26,14 @@ if ! command -v node >/dev/null 2>&1; then for candidate in \ "${HOME}"/.nvm/versions/node/*/bin \ "${HOME}"/.local/share/fnm/node-versions/*/installation/bin \ - "${HOME}/Library/Application Support/fnm/node-versions"/*/installation/bin; do - if [[ -x "${candidate}/node" ]]; then + "${HOME}/Library/Application Support/fnm/node-versions"/*/installation/bin \ + "${HOME}/.volta/bin" \ + "/c/Program Files/nodejs" \ + "${PROGRAMFILES:-}/nodejs" \ + "${APPDATA:-}/nvm"/* \ + "${APPDATA:-}/fnm/node-versions"/*/installation \ + "${LOCALAPPDATA:-}/fnm_multishells"/*; do + if [[ -n "${candidate}" ]] && [[ -x "${candidate}/node" || -x "${candidate}/node.exe" ]]; then export PATH="${candidate}:${PATH}" fi done @@ -50,4 +62,13 @@ if [[ ! -d "${MCP_DIR}/node_modules/@modelcontextprotocol/sdk" ]] \ fi fi -exec node "${MCP_DIR}/index.js" +ENTRYPOINT="${MCP_DIR}/index.js" +if command -v cygpath >/dev/null 2>&1; then + case "$(uname -s 2>/dev/null || true)" in + MINGW*|MSYS*|CYGWIN*) + ENTRYPOINT="$(cygpath -w "${ENTRYPOINT}")" + ;; + esac +fi + +exec node "${ENTRYPOINT}" diff --git a/src/checkout.rs b/src/checkout.rs index e06624a..d79f050 100644 --- a/src/checkout.rs +++ b/src/checkout.rs @@ -154,8 +154,22 @@ fn git(cwd: &Path, args: &[&str]) -> Option { if text.is_empty() { None } else { Some(text) } } +/// Strip the Windows verbatim drive prefix (`\\?\C:\...` -> `C:\...`) added by +/// `std::fs::canonicalize` so paths match `git rev-parse --show-toplevel` and +/// Node `fs.realpathSync` on Windows. +pub fn strip_windows_verbatim(path: std::path::PathBuf) -> std::path::PathBuf { + if let Some(raw) = path.to_str() + && let Some(stripped) = raw.strip_prefix(r"\\?\") + && stripped.as_bytes().get(1) == Some(&b':') + { + return std::path::PathBuf::from(stripped); + } + path +} + fn canonicalize_or(path: &Path) -> String { path.canonicalize() + .map(strip_windows_verbatim) .unwrap_or_else(|_| path.to_path_buf()) .display() .to_string() @@ -195,6 +209,22 @@ mod tests { use std::fs; use std::process::Command; + #[test] + fn strip_windows_verbatim_removes_drive_prefix_only() { + assert_eq!( + strip_windows_verbatim(std::path::PathBuf::from(r"\\?\C:\Users\dev\repo")), + std::path::PathBuf::from(r"C:\Users\dev\repo") + ); + assert_eq!( + strip_windows_verbatim(std::path::PathBuf::from(r"\\?\UNC\server\share")), + std::path::PathBuf::from(r"\\?\UNC\server\share") + ); + assert_eq!( + strip_windows_verbatim(std::path::PathBuf::from("/Users/dev/repo")), + std::path::PathBuf::from("/Users/dev/repo") + ); + } + #[test] fn normalize_origin_joins_ssh_and_https() { assert_eq!( diff --git a/src/kb.rs b/src/kb.rs index 902e4fc..201bb47 100644 --- a/src/kb.rs +++ b/src/kb.rs @@ -88,9 +88,10 @@ pub struct KbRegistry { } pub fn kb_home() -> PathBuf { - Path::new(&std::env::var("HOME").unwrap_or_else(|_| ".".to_string())) - .join(".leio-code") - .join("kb") + let home = std::env::var("HOME") + .or_else(|_| std::env::var("USERPROFILE")) + .unwrap_or_else(|_| ".".to_string()); + Path::new(&home).join(".leio-code").join("kb") } pub fn registry_path() -> PathBuf { @@ -128,6 +129,7 @@ pub fn save_registry(registry: &KbRegistry) -> Result<()> { pub fn add_source(name: &str, source: &Path) -> Result> { let source = source .canonicalize() + .map(crate::checkout::strip_windows_verbatim) .with_context(|| format!("resolve {}", source.display()))?; let mut registry = load_registry(); let sources = registry.bases.entry(name.to_owned()).or_default(); diff --git a/src/main.rs b/src/main.rs index 6d8e972..a7e050b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1835,6 +1835,7 @@ fn index_file_age_secs(index_path: &Path) -> Option { fn canonical_repo(path: &Path) -> Result { let canonical = path .canonicalize() + .map(leio_code::checkout::strip_windows_verbatim) .with_context(|| format!("failed to resolve repo path {}", path.display()))?; // When running from a subdirectory with default or current directory path, diff --git a/src/sidecar.rs b/src/sidecar.rs index d6e6071..022e30e 100644 --- a/src/sidecar.rs +++ b/src/sidecar.rs @@ -525,7 +525,24 @@ fn pid_alive(pid: u32) -> bool { let rc = unsafe { kill_bind::kill(pid as i32, 0) }; rc == 0 } - #[cfg(not(unix))] + #[cfg(windows)] + { + const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000; + const STILL_ACTIVE: u32 = 259; + const ERROR_ACCESS_DENIED: u32 = 5; + // Safety: OpenProcess / GetExitCodeProcess / CloseHandle are standard Win32 kernel32 probes. + unsafe { + let handle = win_bind::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if handle.is_null() { + return win_bind::GetLastError() == ERROR_ACCESS_DENIED; + } + let mut exit_code: u32 = 0; + let ok = win_bind::GetExitCodeProcess(handle, &mut exit_code); + let _ = win_bind::CloseHandle(handle); + ok != 0 && exit_code == STILL_ACTIVE + } + } + #[cfg(not(any(unix, windows)))] { let _ = pid; true @@ -540,6 +557,21 @@ mod kill_bind { } } +#[cfg(windows)] +mod win_bind { + #[link(name = "kernel32")] + unsafe extern "system" { + pub fn OpenProcess( + desired_access: u32, + inherit_handle: i32, + process_id: u32, + ) -> *mut core::ffi::c_void; + pub fn GetExitCodeProcess(process: *mut core::ffi::c_void, exit_code: *mut u32) -> i32; + pub fn CloseHandle(object: *mut core::ffi::c_void) -> i32; + pub fn GetLastError() -> u32; + } +} + fn lock_wait_secs() -> u64 { env_u64("LEIO_LOCK_WAIT_SECS").unwrap_or(DEFAULT_LOCK_WAIT_SECS) } diff --git a/src/update.rs b/src/update.rs index 719b09a..e1cd684 100644 --- a/src/update.rs +++ b/src/update.rs @@ -80,9 +80,17 @@ fn git(cwd: &Path, args: &[&str]) -> Result { fn on_path(program: &str) -> Option { let path = std::env::var_os("PATH")?; - std::env::split_paths(&path) - .map(|dir| dir.join(program)) - .find(|candidate| candidate.is_file()) + let suffixes: &[&str] = if cfg!(windows) && !program.contains('.') { + &["", ".exe", ".cmd"] + } else { + &[""] + }; + std::env::split_paths(&path).find_map(|dir| { + suffixes + .iter() + .map(|suffix| dir.join(format!("{program}{suffix}"))) + .find(|candidate| candidate.is_file()) + }) } /// Verify the routing artifacts actually installed, even for same-version refreshes. @@ -218,11 +226,16 @@ fn prune_cache_fat(cache_root: &Path) { recurse(cache_root, 0); } +fn user_home() -> PathBuf { + std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("/root")) +} + /// Cache roots the two harness CLIs snapshot plugins into. fn plugin_cache_roots() -> [PathBuf; 2] { - let home = std::env::var_os("HOME") - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from("/root")); + let home = user_home(); [ home.join(".codex/plugins/cache/leio-code"), home.join(".claude/plugins/cache/leio-code"), @@ -234,7 +247,17 @@ fn install_binary(source: &Path, dest: &Path) -> Result<()> { let tmp = dest.with_extension("tmp-update"); std::fs::copy(source, &tmp) .with_context(|| format!("copy {} -> {}", source.display(), tmp.display()))?; + #[cfg(windows)] + if dest.exists() { + let old = dest.with_extension("old-exe"); + let _ = std::fs::remove_file(&old); + let _ = std::fs::rename(dest, &old); + } std::fs::rename(&tmp, dest).with_context(|| format!("publish {}", dest.display()))?; + #[cfg(windows)] + { + let _ = std::fs::remove_file(dest.with_extension("old-exe")); + } Ok(()) } @@ -294,8 +317,9 @@ pub fn run_update(force: bool, refresh_plugins: bool) -> Result { let _ = std::fs::write(&build_script, source); } + let exe = std::env::consts::EXE_SUFFIX; let cargo = on_path("cargo") - .or_else(|| Some(home_cargo_bin().join("cargo"))) + .or_else(|| Some(home_cargo_bin().join(format!("cargo{exe}")))) .context("cargo not found on PATH")?; let build = Command::new(&cargo) .current_dir(&checkout) @@ -332,13 +356,15 @@ pub fn run_update(force: bool, refresh_plugins: bool) -> Result { let target_dir = std::env::var("CARGO_TARGET_DIR") .map(PathBuf::from) .unwrap_or_else(|_| checkout.join("target")); + let leio_bin = format!("leio-code{exe}"); + let harness_bin = format!("leio-harness{exe}"); install_binary( - &target_dir.join("release/leio-code"), - &dest_dir.join("leio-code"), + &target_dir.join("release").join(&leio_bin), + &dest_dir.join(&leio_bin), )?; install_binary( - &target_dir.join("release/leio-harness"), - &dest_dir.join("leio-harness"), + &target_dir.join("release").join(&harness_bin), + &dest_dir.join(&harness_bin), )?; steps.push(Step { name: "install", @@ -346,13 +372,13 @@ pub fn run_update(force: bool, refresh_plugins: bool) -> Result { }); evidence.push(EvidenceItem { kind: "binary".to_string(), - path: dest_dir.join("leio-code").display().to_string(), + path: dest_dir.join(&leio_bin).display().to_string(), line: None, detail: "installed binary".to_string(), }); evidence.push(EvidenceItem { kind: "binary".to_string(), - path: dest_dir.join("leio-harness").display().to_string(), + path: dest_dir.join(&harness_bin).display().to_string(), line: None, detail: "installed binary".to_string(), }); @@ -362,7 +388,8 @@ pub fn run_update(force: bool, refresh_plugins: bool) -> Result { let dest_dir = std::env::var("DEST_DIR") .map(PathBuf::from) .unwrap_or_else(|_| home_cargo_bin()); - Command::new(dest_dir.join("leio-code")) + let leio_bin = format!("leio-code{}", std::env::consts::EXE_SUFFIX); + Command::new(dest_dir.join(leio_bin)) .arg("--version") .output() .ok() @@ -432,10 +459,7 @@ pub fn run_update(force: bool, refresh_plugins: bool) -> Result { } fn home_cargo_bin() -> PathBuf { - std::env::var_os("HOME") - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from("/root")) - .join(".cargo/bin") + user_home().join(".cargo/bin") } #[cfg(test)]