Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host): run on Windows
leepokaie0a97f2540a5
diff --git a/.github/workflows/host.yml b/.github/workflows/host.ymlindex 90cade28..fb90069a 100644--- a/.github/workflows/host.yml+++ b/.github/workflows/host.yml@@ -12,7 +12,8 @@ jobs:test:strategy:matrix:- os: [ubuntu-latest, macos-latest]+ # Windows hosts ship inside the desktop app (release-desktop.yml), so no release archive below.+ os: [ubuntu-latest, macos-latest, windows-latest]runs-on: ${{ matrix.os }}defaults:run:diff --git a/host/Cargo.lock b/host/Cargo.lockindex f5b90c0d..ef121310 100644--- a/host/Cargo.lock+++ b/host/Cargo.lock@@ -337,6 +337,12 @@ version = "0.23.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"+[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"+[[package]]name = "bitflags"version = "2.13.2"@@ -395,6 +401,12 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"+[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"+[[package]]name = "bytes"version = "1.12.1"@@ -437,6 +449,12 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"+[[package]]+name = "cfg_aliases"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"+[[package]]name = "cfg_aliases"version = "0.2.2"@@ -590,7 +608,7 @@ dependencies = ["hmac 0.13.0","if-addrs","keyring",- "pty-process",+ "portable-pty","qrcode","ratatui","reqwest",@@ -742,7 +760,7 @@ version = "0.29.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"dependencies = [- "bitflags",+ "bitflags 2.13.2","crossterm_winapi","derive_more","document-features",@@ -1049,6 +1067,12 @@ dependencies = ["litrs",]+[[package]]+name = "downcast-rs"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"+[[package]]name = "dunce"version = "1.0.5"@@ -1170,6 +1194,17 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"+[[package]]+name = "filedescriptor"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d"+dependencies = [+ "libc",+ "thiserror 1.0.69",+ "winapi",+]+[[package]]name = "filetime"version = "0.2.29"@@ -1842,7 +1877,7 @@ dependencies = ["jni-sys","log","simd_cesu8",- "thiserror",+ "thiserror 2.0.21","walkdir","windows-link",]@@ -1908,7 +1943,7 @@ checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899"dependencies = ["hashbrown 0.16.1","portable-atomic",- "thiserror",+ "thiserror 2.0.21",][[package]]@@ -1917,12 +1952,14 @@ version = "3.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"dependencies = [+ "byteorder","dbus-secret-service","log","openssl","secret-service","security-framework 2.11.1","security-framework 3.7.0",+ "windows-sys 0.60.2","zeroize",]@@ -1980,7 +2017,7 @@ version = "0.3.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e"dependencies = [- "bitflags",+ "bitflags 2.13.2",][[package]]@@ -2089,15 +2126,27 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "nix"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4"+dependencies = [+ "bitflags 2.13.2",+ "cfg-if",+ "cfg_aliases 0.1.1",+ "libc",+]+[[package]]name = "nix"version = "0.29.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"dependencies = [- "bitflags",+ "bitflags 2.13.2","cfg-if",- "cfg_aliases",+ "cfg_aliases 0.2.2","libc","memoffset",]@@ -2216,7 +2265,7 @@ version = "0.10.81"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"dependencies = [- "bitflags",+ "bitflags 2.13.2","cfg-if","foreign-types","libc",@@ -2418,6 +2467,27 @@ version = "1.15.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"+[[package]]+name = "portable-pty"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e"+dependencies = [+ "anyhow",+ "bitflags 1.3.2",+ "downcast-rs",+ "filedescriptor",+ "lazy_static",+ "libc",+ "log",+ "nix 0.28.0",+ "serial2",+ "shared_library",+ "shell-words",+ "winapi",+ "winreg",+]+[[package]]name = "potential_utf"version = "0.1.6"@@ -2460,16 +2530,6 @@ dependencies = ["unicode-ident",]-[[package]]-name = "pty-process"-version = "0.5.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "71cec9e2670207c5ebb9e477763c74436af3b9091dd550b9fb3c1bec7f3ea266"-dependencies = [- "rustix",- "tokio",-]-[[package]]name = "qrcode"version = "0.14.1"@@ -2483,14 +2543,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"dependencies = ["bytes",- "cfg_aliases",+ "cfg_aliases 0.2.2","pin-project-lite","quinn-proto","quinn-udp","rustc-hash","rustls","socket2",- "thiserror",+ "thiserror 2.0.21","tokio","tracing","web-time",@@ -2513,7 +2573,7 @@ dependencies = ["rustls","rustls-pki-types","slab",- "thiserror",+ "thiserror 2.0.21","tinyvec","tracing","web-time",@@ -2525,7 +2585,7 @@ version = "0.5.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"dependencies = [- "cfg_aliases",+ "cfg_aliases 0.2.2","libc","once_cell","socket2",@@ -2658,7 +2718,7 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c"dependencies = [- "bitflags",+ "bitflags 2.13.2","compact_str","hashbrown 0.17.1","itertools",@@ -2667,7 +2727,7 @@ dependencies = ["palette","serde","strum 0.28.0",- "thiserror",+ "thiserror 2.0.21","unicode-segmentation","unicode-truncate","unicode-width",@@ -2691,7 +2751,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1"dependencies = [- "bitflags",+ "bitflags 2.13.2","hashbrown 0.17.1","indoc","instability",@@ -2711,7 +2771,7 @@ version = "0.5.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"dependencies = [- "bitflags",+ "bitflags 2.13.2",][[package]]@@ -2721,7 +2781,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"dependencies = ["libredox",- "thiserror",+ "thiserror 2.0.21",][[package]]@@ -2802,7 +2862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c"dependencies = ["hashbrown 0.16.1",- "thiserror",+ "thiserror 2.0.21",][[package]]@@ -2811,7 +2871,7 @@ version = "0.40.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3"dependencies = [- "bitflags",+ "bitflags 2.13.2","fallible-iterator","fallible-streaming-iterator","hashlink",@@ -2841,7 +2901,7 @@ version = "1.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"dependencies = [- "bitflags",+ "bitflags 2.13.2","errno","libc","linux-raw-sys",@@ -2984,7 +3044,7 @@ version = "2.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"dependencies = [- "bitflags",+ "bitflags 2.13.2","core-foundation 0.9.4","core-foundation-sys","libc",@@ -2997,7 +3057,7 @@ version = "3.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"dependencies = [- "bitflags",+ "bitflags 2.13.2","core-foundation 0.10.1","core-foundation-sys","libc",@@ -3098,6 +3158,17 @@ dependencies = ["serde",]+[[package]]+name = "serial2"+version = "0.2.38"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b16809bc35793b19ce4e0c53924bc0dce3937f15487997cfdaed936004180730"+dependencies = [+ "cfg-if",+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "sha1"version = "0.10.7"@@ -3140,6 +3211,22 @@ dependencies = ["lazy_static",]+[[package]]+name = "shared_library"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11"+dependencies = [+ "lazy_static",+ "libc",+]++[[package]]+name = "shell-words"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"+[[package]]name = "shlex"version = "2.0.1"@@ -3377,13 +3464,33 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]+[[package]]name = "thiserror"version = "2.0.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"dependencies = [- "thiserror-impl",+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",][[package]]@@ -3574,7 +3681,7 @@ version = "0.6.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"dependencies = [- "bitflags",+ "bitflags 2.13.2","bytes","futures-util","http",@@ -3681,7 +3788,7 @@ dependencies = ["rustls","rustls-pki-types","sha1",- "thiserror",+ "thiserror 2.0.21",][[package]]@@ -4044,7 +4151,7 @@ version = "0.52.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"dependencies = [- "windows-targets",+ "windows-targets 0.52.6",][[package]]@@ -4053,7 +4160,16 @@ version = "0.59.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"dependencies = [- "windows-targets",+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"+dependencies = [+ "windows-targets 0.53.5",][[package]]@@ -4071,14 +4187,31 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"dependencies = [- "windows_aarch64_gnullvm",- "windows_aarch64_msvc",- "windows_i686_gnu",- "windows_i686_gnullvm",- "windows_i686_msvc",- "windows_x86_64_gnu",- "windows_x86_64_gnullvm",- "windows_x86_64_msvc",+ "windows_aarch64_gnullvm 0.52.6",+ "windows_aarch64_msvc 0.52.6",+ "windows_i686_gnu 0.52.6",+ "windows_i686_gnullvm 0.52.6",+ "windows_i686_msvc 0.52.6",+ "windows_x86_64_gnu 0.52.6",+ "windows_x86_64_gnullvm 0.52.6",+ "windows_x86_64_msvc 0.52.6",+]++[[package]]+name = "windows-targets"+version = "0.53.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"+dependencies = [+ "windows-link",+ "windows_aarch64_gnullvm 0.53.1",+ "windows_aarch64_msvc 0.53.1",+ "windows_i686_gnu 0.53.1",+ "windows_i686_gnullvm 0.53.1",+ "windows_i686_msvc 0.53.1",+ "windows_x86_64_gnu 0.53.1",+ "windows_x86_64_gnullvm 0.53.1",+ "windows_x86_64_msvc 0.53.1",][[package]]@@ -4087,48 +4220,96 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"+[[package]]+name = "windows_aarch64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"+[[package]]name = "windows_aarch64_msvc"version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"+[[package]]+name = "windows_aarch64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"+[[package]]name = "windows_i686_gnu"version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"+[[package]]+name = "windows_i686_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"+[[package]]name = "windows_i686_gnullvm"version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"+[[package]]+name = "windows_i686_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"+[[package]]name = "windows_i686_msvc"version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"+[[package]]+name = "windows_i686_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"+[[package]]name = "windows_x86_64_gnu"version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"+[[package]]+name = "windows_x86_64_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"+[[package]]name = "windows_x86_64_gnullvm"version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"+[[package]]+name = "windows_x86_64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"+[[package]]name = "windows_x86_64_msvc"version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"+[[package]]+name = "windows_x86_64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"+[[package]]name = "winnow"version = "1.0.4"@@ -4138,6 +4319,15 @@ dependencies = ["memchr",]+[[package]]+name = "winreg"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"+dependencies = [+ "winapi",+]+[[package]]name = "wit-bindgen"version = "0.57.1"@@ -4220,7 +4410,7 @@ dependencies = ["futures-sink","futures-util","hex",- "nix",+ "nix 0.29.0","ordered-stream","rand 0.8.8","serde",diff --git a/host/Cargo.toml b/host/Cargo.tomlindex ceeb33e8..aa28e77e 100644--- a/host/Cargo.toml+++ b/host/Cargo.toml@@ -4,6 +4,7 @@ version = "2.8.0"edition = "2024"# let-chains (`if let … && let …`) need 1.88.rust-version = "1.88"+default-run = "codync-host"description = "Runs your coding-agent bots and serves the Codync apps"license = "MIT"repository = "https://github.com/leepokai/Codync"@@ -27,7 +28,7 @@ gethostname = "1.1.0"getrandom = "0.4"hkdf = "0.13.0"if-addrs = "0.15.0"-pty-process = { version = "0.5.3", features = ["async"] }+portable-pty = "0.9.0"qrcode = { version = "0.14.1", default-features = false, features = ["svg"] }ratatui = { version = "0.30", default-features = false, features = ["crossterm"] }reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "stream"] }@@ -56,6 +57,9 @@ keyring = { version = "3.6.3", features = ["apple-native"] }[target.'cfg(target_os = "linux")'.dependencies]keyring = { version = "3.6.3", features = ["sync-secret-service", "crypto-rust", "vendored"] }+[target.'cfg(windows)'.dependencies]+keyring = { version = "3.6.3", features = ["windows-native"] }+# rust-skills lint-* rules: all default groups plus pedantic, with the# library-oriented pedantic lints turned off for this binary crate.[lints.rust]diff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rsindex 806dd5b7..c02f4965 100644--- a/host/src/agent/acp.rs+++ b/host/src/agent/acp.rs@@ -74,25 +74,25 @@ pub struct Acp {}impl Acp {- /// Spawns `command` through `sh -c` so user-provided commands (npx, env vars) just work.+ /// Spawns `command` through the shell so user-provided commands (npx, env vars) just work./// `env` stays out of the command line (it can hold API keys).pub fn spawn(command: &str,cwd: &str,env: &[(String, String)],) -> Result<(Arc<Self>, mpsc::UnboundedReceiver<Incoming>)> {- let mut child = Command::new("/bin/sh")- .arg("-c")- .arg(format!("exec {command}"))+ let mut process = crate::shell::exec(command).tokio();+ process.envs(env.iter().map(|(k, v)| (k, v))).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())- .kill_on_drop(true)- .process_group(0)- .spawn()- .with_context(|| format!("starting `{command}`"))?;+ .kill_on_drop(true);+ // Its own group, so `kill` can stop everything it started.+ #[cfg(unix)]+ process.process_group(0);+ let mut child = process.spawn().with_context(|| format!("starting `{command}`"))?;let stdin = child.stdin.take().expect("stdin is piped");let stdout = child.stdout.take().expect("stdout is piped");let stderr = child.stderr.take().expect("stderr is piped");@@ -203,14 +203,19 @@ impl Acp {pub async fn kill(&self) {let mut child = self.child.lock().await;- // ACP adapters spawn MCP servers and tools. Give each adapter its own- // group and stop that group before reaping its leader.+ // ACP adapters spawn MCP servers and tools. Stop the adapter's whole+ // process group (Windows: process tree) before reaping its leader.if let Some(pid) = child.id() {- let _ = Command::new("/bin/kill")- .args(["-KILL", "--", &format!("-{pid}")])- .stderr(Stdio::null())- .status()- .await;+ let mut tree = if cfg!(windows) {+ let mut c = Command::new("taskkill");+ c.args(["/T", "/F", "/PID", &pid.to_string()]);+ c+ } else {+ let mut c = Command::new("/bin/kill");+ c.args(["-KILL", "--", &format!("-{pid}")]);+ c+ };+ let _ = tree.stdout(Stdio::null()).stderr(Stdio::null()).status().await;}// Already exited is fine; anything else is worth a log line.if let Err(error) = child.kill().await@@ -264,6 +269,7 @@ mod tests {assert_eq!(truncate("héllo", 2), "h…");}+ #[cfg(unix)]#[tokio::test]async fn stopping_an_agent_closes_its_descendants_pipes() {let (acp, mut rx) = Acp::spawn(@@ -280,6 +286,7 @@ mod tests {assert!(matches!(closed, Some(Incoming::Closed { .. })));}+ #[cfg(unix)]#[tokio::test]async fn request_response_roundtrip() {// A fake agent: answers `initialize`, then sends a notification and exits.diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rsindex f45f0e6a..bab466aa 100644--- a/host/src/agent/auth.rs+++ b/host/src/agent/auth.rs@@ -13,7 +13,8 @@use crate::LockExt;use crate::agent::acp::{AUTH_REQUIRED, Acp, Incoming, RpcError};use crate::agent::backends;-use crate::agent::registry::{Cmd, env_prefix, shell_quote};+use crate::agent::registry::{Cmd, env_prefix};+use crate::shell::quote as shell_quote;use crate::store::Store;use anyhow::{Context, Result, anyhow, bail};use serde::Serialize;@@ -425,7 +426,9 @@ mod tests {]});let m = methods("x", &init, &cmd());let kinds: Vec<_> = m.iter().map(|m| (m.id.as_str(), &m.kind)).collect();- assert!(matches!(kinds[0], ("a", MethodKind::Terminal { command }) if command == "/bin/tool login '--x y'"));+ assert!(+ matches!(kinds[0], ("a", MethodKind::Terminal { command }) if command == &format!("/bin/tool login {}", shell_quote("--x y")))+ );assert!(matches!(kinds[1], ("b", MethodKind::Terminal { command }) if command == "npx -y pkg@1 --terminal-login"));diff --git a/host/src/agent/backends.rs b/host/src/agent/backends.rsindex 6474cf15..344d1d02 100644--- a/host/src/agent/backends.rs+++ b/host/src/agent/backends.rs@@ -8,6 +8,7 @@use crate::LockExt;use crate::agent::registry;+use crate::shell;use serde_json::{Value, json};use std::collections::HashSet;use std::path::{Path, PathBuf};@@ -35,19 +36,27 @@ pub struct Harness {#[derive(Clone, Copy)]pub enum Install {- /// A vendor install script (`curl … | bash`).+ /// A vendor install script (`curl … | bash`), Unix only.Script(&'static str),+ /// Vendor install scripts for Unix and for Windows (PowerShell).+ Scripts { unix: &'static str, windows: &'static str },/// A global npm package.Npm(&'static str),}impl Install {- pub fn command(self) -> String {+ /// `None`: nothing Codync can run on this platform.+ pub fn command(self) -> Option<String> {match self {- Self::Script(s) => s.to_owned(),- Self::Npm(pkg) => format!(+ Self::Script(s) | Self::Scripts { unix: s, .. } if cfg!(unix) => Some(s.to_owned()),+ Self::Script(_) => None,+ Self::Scripts { windows, .. } => Some(windows.to_owned()),+ Self::Npm(pkg) if cfg!(windows) => Some(format!(+ "where npm >nul 2>nul || (echo This needs Node.js first: https://nodejs.org & exit /b 1) & npm install -g {pkg}"+ )),+ Self::Npm(pkg) => Some(format!("command -v npm >/dev/null || {{ echo 'This needs Node.js first: https://nodejs.org'; exit 1; }}; npm install -g {pkg}"- ),+ )),}}}@@ -84,7 +93,10 @@ pub const HARNESSES: &[Harness] = &[local: None,registry: Some("claude-acp"),setup: "Install Claude Code and run `claude auth login`.",- install: Some(Install::Script("curl -fsSL https://claude.ai/install.sh | bash")),+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://claude.ai/install.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://claude.ai/install.ps1 | iex\"",+ }),login: "{bin} auth login",signed_in: Some(SignInCheck { args: "auth status", ok: claude_signed_in }),},@@ -376,8 +388,12 @@ pub fn harness(id: &str) -> Option<&'static Harness> {static SEARCH_PATH: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());/// Login-shell PATH, via `$SHELL -ilc` with a timeout (nvm/conda can make shells slow).+/// Windows has no login shell: every process already gets the user's PATH.fn login_shell_path() -> Option<String> {const MARK: &str = "__CODYNC_PATH__";+ if cfg!(windows) {+ return None;+ }let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into());let mut child = std::process::Command::new(shell).args(["-ilc", &format!("printf '%s%s%s' '{MARK}' \"$PATH\" '{MARK}'")])@@ -419,6 +435,11 @@ fn well_known_dirs() -> Vec<PathBuf> {.iter().map(PathBuf::from).collect();+ if cfg!(windows) {+ // Global npm CLIs (%APPDATA%\npm), and Node itself.+ dirs.extend(dirs::data_dir().map(|d| d.join("npm")));+ dirs.extend(std::env::var_os("ProgramFiles").map(|d| PathBuf::from(d).join("nodejs")));+ }for rel in [".local/bin",".bun/bin",@@ -477,7 +498,14 @@ pub fn which(bin: &str) -> Option<PathBuf> {cached.clone()}};- dirs.into_iter().map(|d| d.join(bin)).find(|p| is_executable(p))+ dirs.into_iter().flat_map(|d| executable_names(bin).map(move |name| d.join(name))).find(|p| is_executable(p))+}++/// What `bin` can be called on disk: Windows adds the extensions it runs.+fn executable_names(bin: &str) -> impl Iterator<Item = String> + '_ {+ let extensions: &[&str] =+ if cfg!(windows) && Path::new(bin).extension().is_none() { &[".exe", ".cmd", ".bat"] } else { &[""] };+ extensions.iter().map(move |e| format!("{bin}{e}"))}fn is_executable(p: &Path) -> bool {@@ -517,7 +545,7 @@ pub fn list() -> Vec<Value> {"description": reg.and_then(|a| a["description"].as_str()).unwrap_or_default(),"installHint": h.setup,"signedIn": signed_in(h.id),- "canInstall": h.install.is_some(),+ "canInstall": h.install.and_then(Install::command).is_some(),"command": h.local.unwrap_or_default(),"registry": h.registry,"curated": true,@@ -647,7 +675,7 @@ pub fn login_available(id: &str) -> bool {pub async fn login_command(id: &str) -> anyhow::Result<String> {let h = harness(id).ok_or_else(|| anyhow::anyhow!("no sign-in command for {id}"))?;let bin = match h.bins.iter().find_map(|b| which(b)) {- Some(p) => shell_quote(&p.to_string_lossy()),+ Some(p) => shell::quote(&p.to_string_lossy()),None => match registry_cli(h) {Some(agent) => registry::command(&agent, |_| {}).await?.program,None if !h.login.contains("{bin}") => String::new(),@@ -663,21 +691,14 @@ pub fn local_candidate(id: &str) -> Option<registry::Cmd> {let template = h.local?;let path = h.bins.iter().find_map(|b| which(b))?;let args = template.strip_prefix("{bin}").unwrap_or(template).trim().to_owned();- Some(registry::Cmd { program: shell_quote(&path.to_string_lossy()), args })-}--fn shell_quote(s: &str) -> String {- if s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)) {- s.to_owned()- } else {- format!("'{}'", s.replace('\'', "'\\''"))- }+ Some(registry::Cmd { program: shell::quote(&path.to_string_lossy()), args })}#[cfg(test)]mod tests {use super::*;+ #[cfg(unix)]#[test]fn detects_executables_on_search_path() {let dir = std::env::temp_dir().join(format!("codync-bin-{}", uuid::Uuid::new_v4()));diff --git a/host/src/agent/registry.rs b/host/src/agent/registry.rsindex b84a874d..e8f6cf3b 100644--- a/host/src/agent/registry.rs+++ b/host/src/agent/registry.rs@@ -6,6 +6,7 @@//! disk, so they're checked before use.use crate::LockExt;+use crate::shell;use anyhow::{Context, Result, anyhow, bail};use serde_json::Value;use sha2::{Digest, Sha256};@@ -77,6 +78,8 @@ pub fn platform() -> Option<&'static str> {("macos", "x86_64") => "darwin-x86_64",("linux", "aarch64") => "linux-aarch64",("linux", "x86_64") => "linux-x86_64",+ ("windows", "aarch64") => "windows-aarch64",+ ("windows", "x86_64") => "windows-x86_64",_ => return None,})}@@ -98,34 +101,16 @@ pub fn launch_kind(agent: &Value) -> Option<Launch> {None}-pub fn shell_quote(s: &str) -> String {- if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=@:+,".contains(c)) {- s.to_owned()- } else {- format!("'{}'", s.replace('\'', "'\\''"))- }-}-fn args_of(v: &Value) -> String {v["args"].as_array()- .map(|a| a.iter().filter_map(Value::as_str).map(shell_quote).collect::<Vec<_>>().join(" "))+ .map(|a| a.iter().filter_map(Value::as_str).map(shell::quote).collect::<Vec<_>>().join(" ")).unwrap_or_default()}-/// `KEY=value ` pairs; keys that aren't plain identifiers are dropped (they'd be shell syntax).-/// Goes through `env` so the result still works after `exec`.+/// `KEY=value ` pairs from a registry `env` object.pub fn env_prefix(env: &Value) -> String {- let pairs = env- .as_object()- .map(|m| {- m.iter()- .filter(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))- .filter_map(|(k, v)| Some(format!("{k}={} ", shell_quote(v.as_str()?))))- .collect::<String>()- })- .unwrap_or_default();- if pairs.is_empty() { pairs } else { format!("env {pairs}") }+ shell::env_prefix(env.as_object().into_iter().flatten().filter_map(|(k, v)| Some((k.as_str(), v.as_str()?))))}/// One path component made only of `[A-Za-z0-9._-]` and not `.`/`..`.@@ -170,7 +155,7 @@ pub async fn command(agent: &Value, progress: impl Fn(&str)) -> Result<Cmd> {target["cmd"].as_str().and_then(contained).ok_or_else(|| anyhow!("registry entry has a bad cmd"))?;let dir = install_binary(agent, target, cmd, &progress).await?;Ok(Cmd {- program: format!("{}{}", env_prefix(&target["env"]), shell_quote(&dir.join(cmd).to_string_lossy())),+ program: format!("{}{}", env_prefix(&target["env"]), shell::quote(&dir.join(cmd).to_string_lossy())),args: args_of(target),})}@@ -182,7 +167,7 @@ pub async fn command(agent: &Value, progress: impl Fn(&str)) -> Result<Cmd> {program: format!("{}uvx {}",env_prefix(&d["uvx"]["env"]),- shell_quote(d["uvx"]["package"].as_str().unwrap_or_default())+ shell::quote(d["uvx"]["package"].as_str().unwrap_or_default())),args: args_of(&d["uvx"]),}),@@ -198,7 +183,7 @@ fn npx_cmd(npx: &Value) -> Cmd {program: format!("{}npx -y {}",env_prefix(&npx["env"]),- shell_quote(npx["package"].as_str().unwrap_or_default())+ shell::quote(npx["package"].as_str().unwrap_or_default())),args: args_of(npx),}@@ -218,7 +203,7 @@ async fn prepare_npx(package: &str, name: &str, progress: &impl Fn(&str)) -> Res}let _ = tokio::fs::remove_dir_all(&dir).await;progress(&format!("Downloading {name}…"));- let install = tokio::process::Command::new("npm")+ let install = tokio::process::Command::new(shell::program("npm")).args(["exec", "--yes", "--package", package, "-c", "true"])// Away from any project, so npx doesn't settle for a local node_modules..current_dir(crate::service::data_dir())@@ -240,7 +225,7 @@ async fn npm_cache() -> Result<&'static Path> {static DIR: tokio::sync::OnceCell<PathBuf> = tokio::sync::OnceCell::const_new();let dir = DIR.get_or_try_init(|| async {- let out = tokio::process::Command::new("npm")+ let out = tokio::process::Command::new(shell::program("npm")).args(["config", "get", "cache"]).stdin(std::process::Stdio::null()).output()@@ -336,9 +321,10 @@ fn extract(archive: &Path, dir: &Path, cmd: &Path) -> Result<()> {let name = archive.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();// Multi-part extensions (`.tar.gz`) rule out `Path::extension`; `name` is already lowercased.#[allow(clippy::case_sensitive_file_extension_comparisons)]- let status = if name.ends_with(".zip") {+ // Windows' bsdtar (`tar.exe`) reads zips too; it has no `unzip`.+ let status = if name.ends_with(".zip") && cfg!(unix) {std::process::Command::new("unzip").arg("-q").arg("-o").arg(archive).arg("-d").arg(dir).status()- } else if [".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".tar"].iter().any(|e| name.ends_with(e)) {+ } else if [".zip", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".tar"].iter().any(|e| name.ends_with(e)) {// Both GNU tar and bsdtar refuse `..` members by default.std::process::Command::new("tar").arg("-xf").arg(archive).arg("-C").arg(dir).status()} else {@@ -348,6 +334,7 @@ fn extract(archive: &Path, dir: &Path, cmd: &Path) -> Result<()> {std::fs::create_dir_all(parent)?;}std::fs::rename(archive, &exe)?;+ #[cfg(unix)]chmod_x(&exe)?;return Ok(());}@@ -356,21 +343,19 @@ fn extract(archive: &Path, dir: &Path, cmd: &Path) -> Result<()> {bail!("couldn't extract {}", archive.display());}let _ = std::fs::remove_file(archive);- let exe = dir.join(cmd);- if exe.exists() {- chmod_x(&exe)?;+ #[cfg(unix)]+ if dir.join(cmd).exists() {+ chmod_x(&dir.join(cmd))?;}Ok(())}+#[cfg(unix)]fn chmod_x(path: &Path) -> Result<()> {- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mut p = std::fs::metadata(path)?.permissions();- p.set_mode(p.mode() | 0o755);- std::fs::set_permissions(path, p)?;- }+ use std::os::unix::fs::PermissionsExt;+ let mut p = std::fs::metadata(path)?.permissions();+ p.set_mode(p.mode() | 0o755);+ std::fs::set_permissions(path, p)?;Ok(())}@@ -382,7 +367,9 @@ mod tests {#[test]fn npx_command_is_quoted() {let npx = json!({"package": "@s/[email protected]", "args": ["--acp", "a b"], "env": {"K": "v", "BAD;rm": "x"}});- assert_eq!(npx_cmd(&npx).acp(), "env K=v npx -y @s/[email protected] --acp 'a b'");+ let expected =+ if cfg!(windows) { "K=v npx -y @s/[email protected] --acp \"a b\"" } else { "env K=v npx -y @s/[email protected] --acp 'a b'" };+ assert_eq!(npx_cmd(&npx).acp(), expected);}#[test]@@ -402,6 +389,7 @@ mod tests {assert!(root.join("1.1.0").exists());}+ #[cfg(unix)]#[test]fn raw_binary_extract_marks_executable() {let dir = std::env::temp_dir().join(format!("codync-reg-{}", uuid::Uuid::new_v4()));diff --git a/host/src/agent/term.rs b/host/src/agent/term.rsindex 4d46f9b8..8efc0bae 100644--- a/host/src/agent/term.rs+++ b/host/src/agent/term.rs@@ -7,12 +7,13 @@ use crate::agent::backends;use anyhow::{Result, anyhow, bail};use base64::Engine as _;use base64::engine::general_purpose::STANDARD as B64;+use portable_pty::{Child, CommandBuilder, MasterPty, PtyPair, PtySize, native_pty_system};use serde::Deserialize;use serde_json::{Value, json};use std::collections::HashMap;+use std::io::{Read as _, Write as _};use std::sync::{Arc, Mutex};use std::time::Duration;-use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::sync::{broadcast, mpsc};/// Output kept for a client that (re)attaches mid-run.@@ -104,7 +105,7 @@ impl Terms {let command = match step {Step::Install => {let h = h.ok_or_else(|| anyhow!("Codync downloads {name} by itself"))?;- h.install.ok_or_else(|| anyhow!("{}", h.setup))?.command()+ h.install.and_then(backends::Install::command).ok_or_else(|| anyhow!("{}", h.setup))?}// Some CLIs (codex) delete the current credentials the moment a new sign-in starts.Step::Login if backends::signed_in(backend) == Some(true) => bail!("{name} is already signed in"),@@ -122,16 +123,19 @@ impl Terms {if let Some((id, _)) = map.iter().find(|(_, t)| t.key == key && t.output.locked().exit.is_none()) {return Ok(id.clone());}- let (pty, pts) = pty_process::open()?;- pty.resize(pty_process::Size::new(rows.max(4), cols.max(20)))?;- let child = pty_process::Command::new("/bin/sh")- .arg("-c")- .arg(command)- .env("TERM", "xterm-256color")- .env("COLORTERM", "truecolor")- .current_dir(dirs::home_dir().unwrap_or_else(|| "/".into()))- .kill_on_drop(true)- .spawn(pts)?;+ let PtyPair { master, slave } = native_pty_system().openpty(size(cols, rows))?;+ let shell = crate::shell::line(command);+ let mut builder = CommandBuilder::new(shell.program);+ builder.args(&shell.args);+ for (k, v) in &shell.env {+ builder.env(k, v);+ }+ builder.env("TERM", "xterm-256color");+ builder.env("COLORTERM", "truecolor");+ builder.cwd(dirs::home_dir().unwrap_or_else(|| "/".into()));+ let child = slave.spawn_command(builder)?;+ // Only the child may hold the terminal side, or the output never ends.+ drop(slave);let (tx, rx) = mpsc::unbounded_channel();let term = Arc::new(Term {key,@@ -143,7 +147,7 @@ impl Terms {let id = uuid::Uuid::new_v4().to_string();map.insert(id.clone(), term.clone());tracing::info!(backend = term.key.0, step = ?term.key.1, term = %id, "setup terminal started");- tokio::spawn(run(self.clone(), id.clone(), term, pty, child, rx));+ tokio::spawn(run(self.clone(), id.clone(), term, master, child, rx));Ok(id)}@@ -170,46 +174,67 @@ impl Terms {}}+fn size(cols: u16, rows: u16) -> PtySize {+ PtySize { rows: rows.max(4), cols: cols.max(20), pixel_width: 0, pixel_height: 0 }+}+async fn run(terms: Arc<Terms>,id: String,term: Arc<Term>,- pty: pty_process::Pty,- mut child: tokio::process::Child,+ master: Box<dyn MasterPty + Send>,+ mut child: Box<dyn Child + Send + Sync>,mut rx: mpsc::UnboundedReceiver<Input>,) {- let (mut reader, mut writer) = pty.into_split();- let pump = {+ let mut killer = child.clone_killer();+ let streams = master.try_clone_reader().and_then(|reader| Ok((reader, master.take_writer()?)));+ let (mut reader, mut writer) = match streams {+ Ok(streams) => streams,+ Err(error) => {+ tracing::warn!(error = format!("{error:#}"), "setup terminal has no streams");+ let _ = killer.kill();+ term.finish(-1);+ return;+ }+ };+ let mut pump = {let term = term.clone();- tokio::spawn(async move {+ tokio::task::spawn_blocking(move || {let mut buf = vec![0u8; 16 * 1024];- // EOF or EIO once the child and its children are gone.- while let Ok(n @ 1..) = reader.read(&mut buf).await {+ // EOF or an error once the child and its children are gone.+ while let Ok(n @ 1..) = reader.read(&mut buf) {term.push(&buf[..n]);}})};+ let mut wait = tokio::task::spawn_blocking(move || child.wait());let status = loop {tokio::select! {- status = child.wait() => break status,+ status = &mut wait => break status,input = rx.recv() => match input {+ // Keystrokes are small; a PTY takes them without blocking.Some(Input::Data(bytes)) => {- if let Err(error) = writer.write_all(&bytes).await {+ if let Err(error) = writer.write_all(&bytes) {tracing::info!(%error, "setup terminal write failed");}}Some(Input::Resize(cols, rows)) => {- let _ = writer.resize(pty_process::Size::new(rows.max(4), cols.max(20)));+ let _ = master.resize(size(cols, rows));}Some(Input::Kill) | None => {- let _ = child.start_kill();+ let _ = killer.kill();}},}};- // Let the last output drain; a background grandchild can hold the PTY open forever.- let _ = tokio::time::timeout(Duration::from_secs(1), pump).await;- let code = status.ok().and_then(|s| s.code()).unwrap_or(-1);+ // Let the last output drain; a background grandchild can hold the PTY open forever, and+ // Windows' pseudo console keeps it open until the master side closes.+ let _ = tokio::time::timeout(Duration::from_secs(1), &mut pump).await;+ drop((writer, master));+ let code = match status {+ Ok(Ok(status)) => i32::try_from(status.exit_code()).unwrap_or(-1),+ _ => -1,+ };tracing::info!(term = %id, code, "setup terminal finished");term.finish(code);tokio::time::sleep(LINGER).await;@@ -223,11 +248,16 @@ mod tests {#[tokio::test]async fn runs_in_a_pty_and_takes_input() {let terms = Arc::new(Terms::default());- let id =- terms.spawn(("test".into(), Step::Login), "[ -t 0 ] && echo tty; read x; echo got-$x", 80, 24).unwrap();+ // `call` expands `%x%` again once `set /p` has read it.+ let (command, enter) = if cfg!(windows) {+ ("echo tty& set /p x=& call echo got-%x%", "\r")+ } else {+ ("[ -t 0 ] && echo tty; read x; echo got-$x", "\n")+ };+ let id = terms.spawn(("test".into(), Step::Login), command, 80, 24).unwrap();let term = terms.get(&id).unwrap();let (_, mut rx) = term.attach();- terms.write(&id, &B64.encode("hi\n")).unwrap();+ terms.write(&id, &B64.encode(format!("hi{enter}"))).unwrap();let code = tokio::time::timeout(Duration::from_secs(10), async {loop {let v = rx.recv().await.unwrap();diff --git a/host/src/bin/codync-hostw.rs b/host/src/bin/codync-hostw.rsnew file mode 100644index 00000000..3793f482--- /dev/null+++ b/host/src/bin/codync-hostw.rs@@ -0,0 +1,42 @@+//! Windows' service runner: starts `codync-host.exe` beside it with the given+//! arguments and no console window, and starts it again when it exits (what+//! launchd's `KeepAlive` and systemd's `Restart=always` do elsewhere). It is a+//! GUI-subsystem program, so signing in doesn't flash a console either.+#![cfg_attr(windows, windows_subsystem = "windows")]++#[cfg(windows)]+fn main() {+ use std::os::windows::process::CommandExt as _;+ use std::time::Duration;+ /// The host gets a hidden console, which the agents it starts share.+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;++ let Ok(exe) = std::env::current_exe() else { return };+ let host = exe.with_file_name("codync-host.exe");+ let args: Vec<_> = std::env::args_os().skip(1).collect();+ let data = std::env::var_os("CODYNC_HOME")+ .map(std::path::PathBuf::from)+ .or_else(|| dirs::home_dir().map(|h| h.join(".codync")));+ loop {+ let mut command = std::process::Command::new(&host);+ command.args(&args).creation_flags(CREATE_NO_WINDOW);+ let log = data.as_ref().and_then(|d| {+ std::fs::create_dir_all(d).ok()?;+ std::fs::OpenOptions::new().create(true).append(true).open(d.join("host.log")).ok()+ });+ if let Some(log) = log+ && let Ok(err) = log.try_clone()+ {+ command.stdout(log).stderr(err);+ }+ // Whatever the exit (a crash, a host that can't start yet), try again shortly.+ let _ = command.status();+ std::thread::sleep(Duration::from_secs(3));+ }+}++#[cfg(not(windows))]+fn main() {+ eprintln!("codync-hostw only runs the host on Windows; use codync-host here.");+ std::process::exit(2);+}diff --git a/host/src/main.rs b/host/src/main.rsindex 0db7ebed..c933bc8a 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -11,6 +11,7 @@ mod remote;mod routines;mod screen;mod service;+mod shell;mod store;mod tui;mod update;@@ -363,7 +364,11 @@ async fn main() -> Result<()> {}Sub::Install { port } => {open_store()?;- if let Some(home) = dirs::home_dir() {+ // Windows: the shell Claude Code runs status lines in varies (Git Bash, PowerShell), so+ // the line stays the user's; usage still comes from `claude -p /usage` and ACP.+ if cfg!(unix)+ && let Some(home) = dirs::home_dir()+ {match service::ensure_statusline(&home.join(".claude/settings.json")) {Ok(true) => println!("Claude Code's status line now also reports usage limits to Codync (your own status line still shows)."@@ -700,9 +705,7 @@ async fn statusline(port: u16, wrapped: String) {if !wrapped.trim().is_empty() {// The user's own status line gets the same JSON on stdin.use std::io::Write;- if let Ok(mut child) =- std::process::Command::new("/bin/sh").arg("-c").arg(&wrapped).stdin(std::process::Stdio::piped()).spawn()- {+ if let Ok(mut child) = shell::line(&wrapped).std().stdin(std::process::Stdio::piped()).spawn() {if let Some(mut stdin) = child.stdin.take() {let _ = stdin.write_all(input.as_bytes());}diff --git a/host/src/market/vault.rs b/host/src/market/vault.rsindex 11981879..b0bf2f01 100644--- a/host/src/market/vault.rs+++ b/host/src/market/vault.rs@@ -50,7 +50,7 @@ pub async fn unlock(hub: Arc<crate::hub::Hub>) -> Result<()> {fn unavailable() -> anyhow::Error {anyhow!(- "Secure credential storage is locked or unavailable. Unlock Keychain on macOS, or start and unlock a Secret Service keyring in this Linux user's D-Bus session. Credentials are never saved as plain text."+ "Secure credential storage is locked or unavailable. Unlock Keychain on macOS, or start and unlock a Secret Service keyring in this Linux user's D-Bus session (Windows keeps it in Credential Manager). Credentials are never saved as plain text.")}diff --git a/host/src/mcp.rs b/host/src/mcp.rsindex c677cc5c..7c1e3fbd 100644--- a/host/src/mcp.rs+++ b/host/src/mcp.rs@@ -500,7 +500,7 @@ pub async fn serve_local(connector: String, port: u16) -> Result<()> {}let v: Value = res.json().await?;let command = v["command"].as_str().ok_or_else(|| anyhow::anyhow!("Not a local connector"))?;- let mut child = tokio::process::Command::new(command);+ let mut child = tokio::process::Command::new(crate::shell::program(command));child.args(v["args"].as_array().into_iter().flatten().filter_map(Value::as_str));for (k, v) in v["env"].as_object().into_iter().flatten() {if let Some(v) = v.as_str() {diff --git a/host/src/screen/helper.rs b/host/src/screen/helper.rsindex 06504660..7e343e0d 100644--- a/host/src/screen/helper.rs+++ b/host/src/screen/helper.rs@@ -1,5 +1,7 @@//! The screen helper's socket: accepting helpers, JSON-RPC requests to them, and the Linux helper process.+//! Windows has no screen helper yet, so nothing listens there.+#[cfg(unix)]use super::protocol::HelperStatus;use super::{HELPER_TIMEOUT, Screen};use crate::LockExt;@@ -8,8 +10,11 @@ use serde_json::{Value, json};use std::collections::HashMap;use std::sync::atomic::{AtomicI64, Ordering};use std::sync::{Arc, Mutex};+#[cfg(unix)]use std::time::Duration;+#[cfg(unix)]use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};+#[cfg(unix)]use tokio::net::{UnixListener, UnixStream};use tokio::sync::{mpsc, oneshot};@@ -17,6 +22,7 @@ pub(super) type Pending = Mutex<HashMap<i64, oneshot::Sender<Result<Value, Strin/// One connected screen helper.pub(super) struct Link {+ #[cfg_attr(windows, expect(dead_code, reason = "Windows has no screen helper yet"))]pub(super) id: u64,pub(super) tx: mpsc::UnboundedSender<String>,pub(super) pending: Pending,@@ -45,7 +51,11 @@ impl Link {}}+#[cfg(windows)]+pub async fn serve_helpers(_screen: Arc<Screen>) {}+/// Accepts screen helpers on `~/.codync/screen.sock`. The newest connection wins.+#[cfg(unix)]pub async fn serve_helpers(screen: Arc<Screen>) {let path = crate::service::data_dir().join("screen.sock");let _ = std::fs::remove_file(&path);@@ -80,8 +90,13 @@ pub(super) fn graphical_session() -> bool {true}+#[cfg(windows)]+pub(super) fn graphical_session() -> bool {+ false+}+/// A Wayland socket in this user's runtime dir, or a running X server.-#[cfg(not(target_os = "macos"))]+#[cfg(target_os = "linux")]pub(super) fn graphical_session() -> bool {let has = |dir: &std::path::Path, prefix: &str| {std::fs::read_dir(dir)@@ -122,6 +137,7 @@ pub async fn supervise_linux_helper(screen: Arc<Screen>) {}}+#[cfg(unix)]async fn run_link(screen: Arc<Screen>, stream: UnixStream) {let (rd, mut wr) = stream.into_split();let (tx, mut rx) = mpsc::unbounded_channel::<String>();@@ -194,7 +210,7 @@ async fn run_link(screen: Arc<Screen>, stream: UnixStream) {tracing::info!("screen helper disconnected");}-#[cfg(test)]+#[cfg(all(test, unix))]mod tests {use super::*;use crate::screen::tests::retina;diff --git a/host/src/screen/mod.rs b/host/src/screen/mod.rsindex 210d79ca..b32defc8 100644--- a/host/src/screen/mod.rs+++ b/host/src/screen/mod.rs@@ -88,6 +88,7 @@ pub struct Screen {status: Mutex<HelperStatus>,control: Mutex<Control>,sessions: Mutex<HashMap<String, Viewer>>,+ #[cfg_attr(windows, expect(dead_code, reason = "Windows has no screen helper yet"))]next_link: AtomicU64,}diff --git a/host/src/screen/viewer.rs b/host/src/screen/viewer.rsindex e816d7bd..2ffbf83b 100644--- a/host/src/screen/viewer.rs+++ b/host/src/screen/viewer.rs@@ -147,6 +147,9 @@ impl Screen {/// Only callable from this computer (see `api/devices.rs`).pub async fn set_enabled(&self, store: &crate::store::Store, on: bool) -> Result<()> {+ if on && cfg!(windows) {+ anyhow::bail!("Remote screen isn't available on Windows yet.");+ }store.kv_set(KV_ENABLED, if on { "1" } else { "0" })?;*self.enabled.locked() = Some(on);if !on {diff --git a/host/src/service/mod.rs b/host/src/service/mod.rsindex b5740839..398d26f4 100644--- a/host/src/service/mod.rs+++ b/host/src/service/mod.rs@@ -1,4 +1,5 @@-//! Platform glue: data dir, background service install (launchd / systemd),+//! Platform glue: data dir, background service install (launchd / systemd /+//! the Windows Run key, in `unix.rs` and `windows.rs`),//! keeping the machine awake during turns, pairing addresses, and the Claude//! Code status line we route through the host.//!@@ -6,6 +7,7 @@//! through `spawn_blocking`.use anyhow::{Context, Result, bail};+use base64::{Engine as _, engine::general_purpose::STANDARD as B64};use serde_json::{Value, json};use sha2::{Digest, Sha256};use std::fmt::Write as _;@@ -14,12 +16,21 @@ use std::process::{Child, Command, Stdio};use std::sync::OnceLock;use std::time::{Duration, Instant};+#[cfg(unix)]+mod unix;+#[cfg(unix)]+pub use unix::{install, installed, require_executable, start, stop, uninstall};+#[cfg(windows)]+mod windows;+#[cfg(windows)]+pub use windows::{install, installed, require_executable, start, stop, uninstall};+static BINARY_IDENTITY: OnceLock<(String, String)> = OnceLock::new();/// Snapshot before serving: reading the path again after an update would identify/// the replacement on disk rather than this running process.pub fn capture_binary_identity() -> Result<()> {- let exe = std::env::current_exe()?.canonicalize()?;+ let exe = current_exe()?;let mut hash = String::with_capacity(64);for byte in Sha256::digest(std::fs::read(&exe)?) {write!(hash, "{byte:02x}")?;@@ -28,6 +39,16 @@ pub fn capture_binary_identity() -> Result<()> {Ok(())}+/// This binary's resolved path, in the form other programs print it: Windows'+/// `canonicalize` adds a `\\?\` prefix that the apps' paths and shells don't have.+pub fn current_exe() -> std::io::Result<PathBuf> {+ let exe = std::env::current_exe()?.canonicalize()?;+ Ok(match exe.to_str().and_then(|p| p.strip_prefix(r"\\?\")) {+ Some(plain) if cfg!(windows) => PathBuf::from(plain),+ _ => exe,+ })+}+pub fn binary_identity() -> Option<&'static (String, String)> {BINARY_IDENTITY.get()}@@ -49,59 +70,12 @@ fn wait_for_host_exit() -> Result<()> {}}-/// Stops the installed job, preserving its configuration for a later start.-/// A manually started daemon is never mistaken for the service we own.-pub fn stop() -> Result<()> {- if cfg!(target_os = "macos") {- let _ = Command::new("launchctl")- .args(["bootout", &format!("gui/{}/{LABEL}", current_uid())])- .stderr(Stdio::null())- .status()?;- } else if installed() {- run("systemctl", &["--user", "stop", "codync-host.service"])?;- }- wait_for_host_exit()-}--pub fn start() -> Result<()> {- if cfg!(target_os = "macos") {- run("launchctl", &["bootstrap", &format!("gui/{}", current_uid()), &launchd_plist().to_string_lossy()])- } else {- run("systemctl", &["--user", "start", "codync-host.service"])- }-}--/// Refuse to replace one installation while restarting a service owned by another.-pub fn require_executable(expected: &Path) -> Result<()> {- let configured = if cfg!(target_os = "macos") {- let output = Command::new("/usr/bin/plutil")- .args(["-extract", "ProgramArguments.0", "raw", "-o", "-"])- .arg(launchd_plist())- .output()?;- if !output.status.success() {- bail!("cannot read the installed host service");- }- PathBuf::from(String::from_utf8(output.stdout)?.trim())- } else {- let unit = std::fs::read_to_string(systemd_unit())?;- let command =- unit.lines().find_map(|line| line.strip_prefix("ExecStart=")).context("service has no ExecStart")?;- let args = shlex::split(command).context("invalid service ExecStart")?;- PathBuf::from(args.first().context("service has no executable")?)- };- if configured.canonicalize()? != expected.canonicalize()? {- bail!("the installed service runs another host binary; run that binary's update command");- }- Ok(())-}-pub const DEFAULT_PORT: u16 = 19222;-const LABEL: &str = "com.pokai.codync.host";/// Marker between our command and a wrapped user status line.const STATUSLINE_MARK: &str = " statusline --";/// The user's home. Codync can't do anything useful without one, so its absence is fatal.-fn home() -> PathBuf {+pub(crate) fn home() -> PathBuf {dirs::home_dir().expect("HOME must be set: Codync keeps its data and agent settings there")}@@ -109,18 +83,6 @@ pub fn data_dir() -> PathBuf {std::env::var_os("CODYNC_HOME").map_or_else(|| home().join(".codync"), PathBuf::from)}-fn launchd_plist() -> PathBuf {- home().join(format!("Library/LaunchAgents/{LABEL}.plist"))-}--fn systemd_unit() -> PathBuf {- dirs::config_dir().unwrap_or_else(|| home().join(".config")).join("systemd/user/codync-host.service")-}--fn xml_escape(s: &str) -> String {- s.replace('&', "&").replace('<', "<").replace('>', ">")-}-fn create_parent(file: &Path) -> Result<()> {if let Some(parent) = file.parent() {std::fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;@@ -139,79 +101,6 @@ pub fn lock_host() -> Result<std::fs::File> {Ok(file)}-/// Installs and starts the host as a per-user background service. The current-/// PATH is captured so the service finds `npx`, `claude`, `codex`, …-pub fn install(port: u16) -> Result<()> {- let exe = std::env::current_exe()?.canonicalize().context("locating the codync-host binary")?;- let exe = exe.to_string_lossy();- let path = std::env::var("PATH").unwrap_or_default();- let log = data_dir().join("host.log");- std::fs::create_dir_all(data_dir()).context("creating the data directory")?;- if cfg!(target_os = "macos") {- let plist = format!(- r#"<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>Label</key><string>{LABEL}</string>- <key>ProgramArguments</key><array><string>{exe}</string><string>serve</string><string>--port</string><string>{port}</string></array>- <key>EnvironmentVariables</key><dict><key>PATH</key><string>{path}</string></dict>- <key>RunAtLoad</key><true/>- <key>KeepAlive</key><true/>- <key>ProcessType</key><string>Interactive</string>- <key>StandardOutPath</key><string>{log}</string>- <key>StandardErrorPath</key><string>{log}</string>-</dict>-</plist>-"#,- exe = xml_escape(&exe),- path = xml_escape(&path),- log = xml_escape(&log.to_string_lossy()),- );- let file = launchd_plist();- create_parent(&file)?;- let uid = current_uid();- // Not loaded yet is the normal case here.- let _ =- Command::new("launchctl").args(["bootout", &format!("gui/{uid}/{LABEL}")]).stderr(Stdio::null()).status();- wait_for_host_exit()?;- std::fs::write(&file, plist).with_context(|| format!("writing {}", file.display()))?;- run("launchctl", &["bootstrap", &format!("gui/{uid}"), &file.to_string_lossy()])?;- } else {- let unit = format!(- "[Unit]\nDescription=Codync host\nAfter=network-online.target\n\n[Service]\nExecStart={exe} serve --port {port}\nEnvironment=PATH={path}\nRestart=always\nRestartSec=3\n\n[Install]\nWantedBy=default.target\n"- );- let file = systemd_unit();- create_parent(&file)?;- std::fs::write(&file, unit).with_context(|| format!("writing {}", file.display()))?;- run("systemctl", &["--user", "daemon-reload"])?;- run("systemctl", &["--user", "stop", "codync-host.service"])?;- wait_for_host_exit()?;- run("systemctl", &["--user", "enable", "--now", "codync-host.service"])?;- println!("Tip: `loginctl enable-linger $USER` keeps the host running while you're logged out.");- }- Ok(())-}--/// Best effort: every step tolerates "already gone".-pub fn uninstall() {- if cfg!(target_os = "macos") {- let _ = Command::new("launchctl")- .args(["bootout", &format!("gui/{}/{LABEL}", current_uid())])- .stderr(Stdio::null())- .status();- let _ = std::fs::remove_file(launchd_plist());- } else {- let _ = run("systemctl", &["--user", "disable", "--now", "codync-host.service"]);- let _ = std::fs::remove_file(systemd_unit());- let _ = run("systemctl", &["--user", "daemon-reload"]);- }-}--pub fn installed() -> bool {- if cfg!(target_os = "macos") { launchd_plist().exists() } else { systemd_unit().exists() }-}-fn run(cmd: &str, args: &[&str]) -> Result<()> {let ok = Command::new(cmd).args(args).status().with_context(|| format!("running {cmd}"))?.success();if !ok {@@ -220,15 +109,6 @@ fn run(cmd: &str, args: &[&str]) -> Result<()> {Ok(())}-fn current_uid() -> String {- Command::new("id")- .arg("-u")- .output()- .ok()- .and_then(|o| String::from_utf8(o.stdout).ok())- .map_or_else(|| "501".into(), |s| s.trim().to_owned())-}-/// Holds a sleep inhibitor while any bot is working.#[derive(Default)]pub struct KeepAwake(Option<Child>);@@ -240,6 +120,17 @@ impl KeepAwake {let pid = std::process::id().to_string();let child = if cfg!(target_os = "macos") {Command::new("caffeinate").args(["-i", "-w", &pid]).stdout(Stdio::null()).spawn()+ } else if cfg!(windows) {+ // The request lasts as long as the PowerShell holding it.+ let script = format!(+ "$k = Add-Type -Name P -Namespace W -PassThru -MemberDefinition '[DllImport(\"kernel32.dll\")] public static extern uint SetThreadExecutionState(uint f);'; $null = $k::SetThreadExecutionState(0x80000001); Wait-Process -Id {pid}"+ );+ let utf16: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();+ Command::new("powershell")+ .args(["-NoProfile", "-NonInteractive", "-EncodedCommand", &B64.encode(utf16)])+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()} else {Command::new("systemd-inhibit").args([@@ -306,7 +197,8 @@ pub fn host_name() -> String {n.trim_end_matches(".local").to_owned()}-/// What the computer is, so phones can draw the right icon (Linux gets its penguin).+/// What the computer is, so phones can draw the right icon (Linux gets its penguin;+/// Windows counts as a desktop).#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]#[serde(rename_all = "lowercase")]pub enum Device {@@ -323,6 +215,9 @@ pub enum Device {pub fn device() -> Device {static DEVICE: OnceLock<Device> = OnceLock::new();*DEVICE.get_or_init(|| {+ if cfg!(windows) {+ return Device::Desktop;+ }if !cfg!(target_os = "macos") {return Device::Linux;}@@ -409,7 +304,7 @@ pub fn ensure_statusline(settings: &Path) -> Result<bool> {if v.get("statusLine").is_some() && current.is_none() {return Ok(false); // not a command status line; leave it alone}- let exe = std::env::current_exe()?.canonicalize()?;+ let exe = current_exe()?;let ours = format!("'{}' statusline", exe.to_string_lossy());if let Some(cmd) = current.as_deref() {if cmd.starts_with(&ours) {diff --git a/host/src/service/unix.rs b/host/src/service/unix.rsnew file mode 100644index 00000000..93c4bdfc--- /dev/null+++ b/host/src/service/unix.rs@@ -0,0 +1,148 @@+//! The background service on macOS (a launchd agent) and Linux (a systemd user unit).++use super::{create_parent, current_exe, data_dir, home, run, wait_for_host_exit};+use anyhow::{Context, Result, bail};+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++const LABEL: &str = "com.pokai.codync.host";++/// Stops the installed job, preserving its configuration for a later start.+/// A manually started daemon is never mistaken for the service we own.+pub fn stop() -> Result<()> {+ if cfg!(target_os = "macos") {+ let _ = Command::new("launchctl")+ .args(["bootout", &format!("gui/{}/{LABEL}", current_uid())])+ .stderr(Stdio::null())+ .status()?;+ } else if installed() {+ run("systemctl", &["--user", "stop", "codync-host.service"])?;+ }+ wait_for_host_exit()+}++pub fn start() -> Result<()> {+ if cfg!(target_os = "macos") {+ run("launchctl", &["bootstrap", &format!("gui/{}", current_uid()), &launchd_plist().to_string_lossy()])+ } else {+ run("systemctl", &["--user", "start", "codync-host.service"])+ }+}++/// Refuse to replace one installation while restarting a service owned by another.+pub fn require_executable(expected: &Path) -> Result<()> {+ let configured = if cfg!(target_os = "macos") {+ let output = Command::new("/usr/bin/plutil")+ .args(["-extract", "ProgramArguments.0", "raw", "-o", "-"])+ .arg(launchd_plist())+ .output()?;+ if !output.status.success() {+ bail!("cannot read the installed host service");+ }+ PathBuf::from(String::from_utf8(output.stdout)?.trim())+ } else {+ let unit = std::fs::read_to_string(systemd_unit())?;+ let command =+ unit.lines().find_map(|line| line.strip_prefix("ExecStart=")).context("service has no ExecStart")?;+ let args = shlex::split(command).context("invalid service ExecStart")?;+ PathBuf::from(args.first().context("service has no executable")?)+ };+ if configured.canonicalize()? != expected.canonicalize()? {+ bail!("the installed service runs another host binary; run that binary's update command");+ }+ Ok(())+}++fn launchd_plist() -> PathBuf {+ home().join(format!("Library/LaunchAgents/{LABEL}.plist"))+}++fn systemd_unit() -> PathBuf {+ dirs::config_dir().unwrap_or_else(|| home().join(".config")).join("systemd/user/codync-host.service")+}++fn xml_escape(s: &str) -> String {+ s.replace('&', "&").replace('<', "<").replace('>', ">")+}++/// Installs and starts the host as a per-user background service. The current+/// PATH is captured so the service finds `npx`, `claude`, `codex`, …+pub fn install(port: u16) -> Result<()> {+ let exe = current_exe().context("locating the codync-host binary")?;+ let exe = exe.to_string_lossy();+ let path = std::env::var("PATH").unwrap_or_default();+ let log = data_dir().join("host.log");+ std::fs::create_dir_all(data_dir()).context("creating the data directory")?;+ if cfg!(target_os = "macos") {+ let plist = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key><string>{LABEL}</string>+ <key>ProgramArguments</key><array><string>{exe}</string><string>serve</string><string>--port</string><string>{port}</string></array>+ <key>EnvironmentVariables</key><dict><key>PATH</key><string>{path}</string></dict>+ <key>RunAtLoad</key><true/>+ <key>KeepAlive</key><true/>+ <key>ProcessType</key><string>Interactive</string>+ <key>StandardOutPath</key><string>{log}</string>+ <key>StandardErrorPath</key><string>{log}</string>+</dict>+</plist>+"#,+ exe = xml_escape(&exe),+ path = xml_escape(&path),+ log = xml_escape(&log.to_string_lossy()),+ );+ let file = launchd_plist();+ create_parent(&file)?;+ let uid = current_uid();+ // Not loaded yet is the normal case here.+ let _ =+ Command::new("launchctl").args(["bootout", &format!("gui/{uid}/{LABEL}")]).stderr(Stdio::null()).status();+ wait_for_host_exit()?;+ std::fs::write(&file, plist).with_context(|| format!("writing {}", file.display()))?;+ run("launchctl", &["bootstrap", &format!("gui/{uid}"), &file.to_string_lossy()])?;+ } else {+ let unit = format!(+ "[Unit]\nDescription=Codync host\nAfter=network-online.target\n\n[Service]\nExecStart={exe} serve --port {port}\nEnvironment=PATH={path}\nRestart=always\nRestartSec=3\n\n[Install]\nWantedBy=default.target\n"+ );+ let file = systemd_unit();+ create_parent(&file)?;+ std::fs::write(&file, unit).with_context(|| format!("writing {}", file.display()))?;+ run("systemctl", &["--user", "daemon-reload"])?;+ run("systemctl", &["--user", "stop", "codync-host.service"])?;+ wait_for_host_exit()?;+ run("systemctl", &["--user", "enable", "--now", "codync-host.service"])?;+ println!("Tip: `loginctl enable-linger $USER` keeps the host running while you're logged out.");+ }+ Ok(())+}++/// Best effort: every step tolerates "already gone".+pub fn uninstall() {+ if cfg!(target_os = "macos") {+ let _ = Command::new("launchctl")+ .args(["bootout", &format!("gui/{}/{LABEL}", current_uid())])+ .stderr(Stdio::null())+ .status();+ let _ = std::fs::remove_file(launchd_plist());+ } else {+ let _ = run("systemctl", &["--user", "disable", "--now", "codync-host.service"]);+ let _ = std::fs::remove_file(systemd_unit());+ let _ = run("systemctl", &["--user", "daemon-reload"]);+ }+}++pub fn installed() -> bool {+ if cfg!(target_os = "macos") { launchd_plist().exists() } else { systemd_unit().exists() }+}++fn current_uid() -> String {+ Command::new("id")+ .arg("-u")+ .output()+ .ok()+ .and_then(|o| String::from_utf8(o.stdout).ok())+ .map_or_else(|| "501".into(), |s| s.trim().to_owned())+}diff --git a/host/src/service/windows.rs b/host/src/service/windows.rsnew file mode 100644index 00000000..f54ef71e--- /dev/null+++ b/host/src/service/windows.rs@@ -0,0 +1,99 @@+//! The background service on Windows: the per-user Run key starts the host at+//! sign-in through `codync-hostw.exe`, which keeps it running without a console+//! window (`src/bin/codync-hostw.rs`).++use super::{current_exe, data_dir, run, wait_for_host_exit};+use anyhow::{Context, Result, bail, ensure};+use std::os::windows::process::CommandExt as _;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";+const VALUE: &str = "CodyncHost";+const SUPERVISOR: &str = "codync-hostw.exe";+const HOST: &str = "codync-host.exe";++const DETACHED_PROCESS: u32 = 0x0000_0008;+const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;+/// Out of the job of whoever ran `install` (Node puts its children in a job that+/// dies with it, and the service must outlive the app that installed it).+const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;++/// Stops the running service. Its configuration stays for a later start; a+/// manually started `codync-host serve` is left alone.+pub fn stop() -> Result<()> {+ // Not running is fine; `/T` takes the host and its agents with the supervisor.+ let _ = Command::new("taskkill")+ .args(["/F", "/T", "/IM", SUPERVISOR])+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status();+ wait_for_host_exit()+}++pub fn start() -> Result<()> {+ let (program, args) = configured()?;+ let spawn = |flags| Command::new(&program).args(&args).creation_flags(flags).spawn();+ let detached = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;+ spawn(detached | CREATE_BREAKAWAY_FROM_JOB)+ .or_else(|_| spawn(detached))+ .with_context(|| format!("starting {}", program.display()))?;+ Ok(())+}++/// Refuse to replace one installation while restarting a service owned by another.+pub fn require_executable(expected: &Path) -> Result<()> {+ let (supervisor, _) = configured()?;+ if supervisor.with_file_name(HOST).canonicalize()? != expected.canonicalize()? {+ bail!("the installed service runs another host binary; run that binary's update command");+ }+ Ok(())+}++/// Registers the host to start at sign-in and starts it now.+pub fn install(port: u16) -> Result<()> {+ let supervisor = current_exe().context("locating the codync-host binary")?.with_file_name(SUPERVISOR);+ ensure!(supervisor.is_file(), "{} is missing; reinstall Codync", supervisor.display());+ std::fs::create_dir_all(data_dir()).context("creating the data directory")?;+ stop()?;+ let command = format!("\"{}\" serve --port {port}", supervisor.display());+ run("reg", &["add", RUN_KEY, "/v", VALUE, "/t", "REG_SZ", "/d", &command, "/f"])?;+ start()+}++/// Best effort: every step tolerates "already gone".+pub fn uninstall() {+ let _ = Command::new("reg").args(["delete", RUN_KEY, "/v", VALUE, "/f"]).stderr(Stdio::null()).status();+ let _ = stop();+}++pub fn installed() -> bool {+ configured().is_ok()+}++/// The supervisor and arguments the Run key starts.+fn configured() -> Result<(PathBuf, Vec<String>)> {+ let output = Command::new("reg").args(["query", RUN_KEY, "/v", VALUE]).output().context("running reg")?;+ ensure!(output.status.success(), "the host service isn't installed");+ parse_run_value(&String::from_utf8_lossy(&output.stdout)).context("cannot read the installed host service")+}++/// ` CodyncHost REG_SZ "C:\…\codync-hostw.exe" serve --port 19222` → its parts.+fn parse_run_value(query: &str) -> Option<(PathBuf, Vec<String>)> {+ let value = query.lines().find_map(|line| Some(line.split_once("REG_SZ")?.1.trim()))?;+ let (program, args) = value.strip_prefix('"')?.split_once('"')?;+ Some((program.into(), args.split_whitespace().map(str::to_owned).collect()))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_the_run_value() {+ let query = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\r\n CodyncHost REG_SZ \"C:\\Program Files\\Codync\\codync-hostw.exe\" serve --port 19222\r\n\r\n";+ let (program, args) = parse_run_value(query).unwrap();+ assert_eq!(program, PathBuf::from("C:\\Program Files\\Codync\\codync-hostw.exe"));+ assert_eq!(args, ["serve", "--port", "19222"]);+ }+}diff --git a/host/src/shell.rs b/host/src/shell.rsnew file mode 100644index 00000000..bd7d8f3b--- /dev/null+++ b/host/src/shell.rs@@ -0,0 +1,148 @@+//! Command lines: the one place Unix and Windows differ in how agents, setup+//! terminals and wrapped status lines start. Unix runs a line with `sh -c`,+//! Windows with `cmd /c`.+//!+//! Windows hands the line to `cmd` through an environment variable: `cmd`+//! expands `%VAR%` before it parses, so the line's own quotes survive whatever+//! argument quoting the spawner (std, tokio, the PTY) applies to `cmd`'s arguments.++use std::fmt::Write as _;+use std::path::PathBuf;++/// A program, its arguments and extra environment that run one command line.+pub struct Shell {+ pub program: &'static str,+ pub args: Vec<String>,+ pub env: Vec<(String, String)>,+}++impl Shell {+ pub fn std(&self) -> std::process::Command {+ let mut command = std::process::Command::new(self.program);+ command.args(&self.args).envs(self.env.iter().map(|(k, v)| (k, v)));+ command+ }++ pub fn tokio(&self) -> tokio::process::Command {+ let mut command = tokio::process::Command::new(self.program);+ command.args(&self.args).envs(self.env.iter().map(|(k, v)| (k, v)));+ command+ }+}++#[cfg(unix)]+pub fn line(line: &str) -> Shell {+ Shell { program: "/bin/sh", args: vec!["-c".into(), line.into()], env: vec![] }+}++#[cfg(windows)]+const LINE_VAR: &str = "CODYNC_COMMAND_LINE";++/// `cmd` has no `KEY=value cmd` syntax, so leading assignments become the environment.+#[cfg(windows)]+pub fn line(line: &str) -> Shell {+ let (mut env, rest) = split_env(line);+ env.push((LINE_VAR.into(), rest.into()));+ Shell { program: "cmd.exe", args: vec!["/d".into(), "/c".into(), format!("%{LINE_VAR}%")], env }+}++/// Runs `command` in place of the shell where the shell can do that (`exec`), so+/// signals and exit codes reach the program itself.+pub fn exec(command: &str) -> Shell {+ if cfg!(windows) { line(command) } else { line(&format!("exec {command}")) }+}++/// Quotes one word for [`line`].+pub fn quote(s: &str) -> String {+ let plain = |c: char| c.is_ascii_alphanumeric() || "-_./=@:+,".contains(c) || (cfg!(windows) && c == '\\');+ if !s.is_empty() && s.chars().all(plain) {+ s.to_owned()+ } else if cfg!(windows) {+ // `cmd` has no escape for a quote inside quotes; Windows paths can't hold one.+ format!("\"{}\"", s.replace('"', ""))+ } else {+ format!("'{}'", s.replace('\'', "'\\''"))+ }+}++/// `KEY=value ` assignments before a command. Unix goes through `env` so the result+/// still works after `exec`; Windows' [`line`] lifts them into the environment.+pub fn env_prefix<'a>(pairs: impl IntoIterator<Item = (&'a str, &'a str)>) -> String {+ let mut out = String::new();+ for (k, v) in pairs {+ if !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {+ let _ = write!(out, "{k}={} ", quote(v));+ }+ }+ let pairs = out;+ if pairs.is_empty() || cfg!(windows) { pairs } else { format!("env {pairs}") }+}++/// `program` as spawnable: its full path when it's on the search path. Windows+/// needs this for npm's `.cmd` shims, which `CreateProcess` won't find by name.+pub fn program(name: &str) -> PathBuf {+ crate::agent::backends::which(name).unwrap_or_else(|| name.into())+}++/// Leading `KEY=value` words (an optional `env` first), and the command after them.+#[cfg(any(windows, test))]+fn split_env(line: &str) -> (Vec<(String, String)>, &str) {+ let mut env = vec![];+ let mut rest = line.trim_start();+ rest = rest.strip_prefix("env ").map_or(rest, str::trim_start);+ while let Some((key, after)) = rest.split_once('=') {+ if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {+ break;+ }+ let (value, after) = match after.strip_prefix(['"', '\'']) {+ Some(quoted) => {+ let close = after.chars().next().unwrap_or('"');+ let Some(end) = quoted.find(close) else { break };+ ("ed[..end], "ed[end + 1..])+ }+ None => after.split_once(' ').unwrap_or((after, "")),+ };+ env.push((key.to_owned(), value.to_owned()));+ rest = after.trim_start();+ }+ (env, rest)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn splits_leading_assignments() {+ let (env, rest) = split_env("env K=v Q=\"a b\" npx -y x --flag=1");+ assert_eq!(env, [("K".to_owned(), "v".to_owned()), ("Q".to_owned(), "a b".to_owned())]);+ assert_eq!(rest, "npx -y x --flag=1");+ let (env, rest) = split_env("NO_BROWSER=true \"C:\\a b\\gemini.cmd\"");+ assert_eq!(env, [("NO_BROWSER".to_owned(), "true".to_owned())]);+ assert_eq!(rest, "\"C:\\a b\\gemini.cmd\"");+ assert_eq!(split_env("claude --x=1").1, "claude --x=1");+ }++ #[cfg(unix)]+ #[test]+ fn quotes_for_sh() {+ assert_eq!(quote("/usr/bin/x"), "/usr/bin/x");+ assert_eq!(quote("a b'c"), "'a b'\\''c'");+ assert_eq!(env_prefix([("K", "v"), ("BAD;rm", "x")]), "env K=v ");+ }++ #[cfg(windows)]+ #[test]+ fn quotes_for_cmd() {+ assert_eq!(quote("C:\\x\\y.exe"), "C:\\x\\y.exe");+ assert_eq!(quote("C:\\Program Files\\y.exe"), "\"C:\\Program Files\\y.exe\"");+ assert_eq!(env_prefix([("K", "a b")]), "K=\"a b\" ");+ }++ #[tokio::test]+ async fn runs_a_line_with_its_environment() {+ let out = line(&format!("{}FOO=1 echo hi", env_prefix([("BAR", "two words")]))).tokio().output().await.unwrap();+ assert!(out.status.success());+ assert!(String::from_utf8_lossy(&out.stdout).contains("hi"));+ }+}diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rsindex 2328079e..77051901 100644--- a/host/src/tui/manage/mod.rs+++ b/host/src/tui/manage/mod.rs@@ -252,11 +252,12 @@ pub(super) fn open_browser(url: &str, host: &str) -> bool {if !local || url.is_empty() {return false;}- let cmd = if cfg!(target_os = "macos") { "open" } else { "xdg-open" };- std::process::Command::new(cmd)- .arg(url)- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .spawn()- .is_ok()+ let mut command = if cfg!(windows) {+ let mut c = std::process::Command::new("rundll32");+ c.arg("url.dll,FileProtocolHandler");+ c+ } else {+ std::process::Command::new(if cfg!(target_os = "macos") { "open" } else { "xdg-open" })+ };+ command.arg(url).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn().is_ok()}diff --git a/host/src/tui/view/time.rs b/host/src/tui/view/time.rsindex d61a4ee4..11f7e1f5 100644--- a/host/src/tui/view/time.rs+++ b/host/src/tui/view/time.rs@@ -6,19 +6,9 @@ pub(super) fn now_ms() -> i64 {crate::store::now_ms()}-/// Local UTC offset in seconds, read once from `date +%z` (no tz database needed).+/// Local UTC offset in seconds, read once.fn utc_offset() -> i64 {- static OFF: LazyLock<i64> = LazyLock::new(|| {- let out = std::process::Command::new("date").arg("+%z").output().ok();- let s = out.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()).unwrap_or_default();- if s.len() != 5 {- return 0;- }- let sign = if s.starts_with('-') { -1 } else { 1 };- let h: i64 = s[1..3].parse().unwrap_or(0);- let m: i64 = s[3..5].parse().unwrap_or(0);- sign * (h * 3600 + m * 60)- });+ static OFF: LazyLock<i64> = LazyLock::new(|| i64::from(chrono::Local::now().offset().local_minus_utc()));*OFF}diff --git a/host/src/update/install.rs b/host/src/update/install.rsindex 8cad40e3..a91a51cb 100644--- a/host/src/update/install.rs+++ b/host/src/update/install.rs@@ -14,7 +14,8 @@ pub enum Method {pub fn method(executable: &Path) -> Method {let path = executable.to_string_lossy();- if path.contains(".app/Contents/") {+ // The Mac app's bundle, or the Windows app's `resources` folder.+ if path.contains(".app/Contents/") || (cfg!(windows) && path.contains("\\resources\\")) {Method::AppBundle} else if path.contains("/Cellar/") || path.contains("/linuxbrew/") {Method::Homebrew@@ -28,7 +29,7 @@ pub fn method(executable: &Path) -> Method {pub fn require_standalone(executable: &Path) -> Result<()> {match method(executable) {Method::Standalone => Ok(()),- Method::AppBundle => bail!("this host belongs to Codync.app; update the Mac app from Settings > Updates"),+ Method::AppBundle => bail!("this host belongs to the Codync app; update the app from Settings > Updates"),Method::Homebrew => bail!("this host belongs to Homebrew; run `brew upgrade leepokai/codync/codync-host`, then `codync-host install`"),diff --git a/host/src/update/mod.rs b/host/src/update/mod.rsindex 3982382c..90a8a20e 100644--- a/host/src/update/mod.rs+++ b/host/src/update/mod.rs@@ -59,7 +59,7 @@ fn lock() -> Result<std::fs::File> {}pub fn status() -> Result<Value> {- let executable = std::env::current_exe()?.canonicalize()?;+ let executable = service::current_exe()?;status_at(&executable)}@@ -73,7 +73,7 @@ fn status_at(executable: &Path) -> Result<Value> {}pub fn set_automatic(enabled: bool) -> Result<Value> {- let executable = std::env::current_exe()?.canonicalize()?;+ let executable = service::current_exe()?;if enabled {install::require_standalone(&executable)?;ensure!(service::installed(), "install the background host service before enabling automatic updates");@@ -125,7 +125,7 @@ pub async fn apply(port: u16, force: bool, skip_app_check: bool, worker: bool) -Err(error) => return Err(error),}};- let target = std::env::current_exe()?.canonicalize()?;+ let target = service::current_exe()?;install::require_standalone(&target)?;let mut state = State { phase: "checking".into(), checked_at: Some(crate::store::now_ms()), ..State::default() };write("update-state.json", &state)?;@@ -171,7 +171,7 @@ pub fn spawn_worker(port: u16, force: bool, skip_app_check: bool) -> Result<()>let _lock = lock()?;let previous: State = read("update-state.json")?;ensure!(!awaiting_worker(&previous), "a host update is already starting");- let executable = std::env::current_exe()?.canonicalize()?;+ let executable = service::current_exe()?;install::require_standalone(&executable)?;ensure!(service::installed(),diff --git a/host/src/update/release.rs b/host/src/update/release.rsindex b8d22a95..08b25971 100644--- a/host/src/update/release.rs+++ b/host/src/update/release.rs@@ -149,7 +149,6 @@ pub fn extract(bytes: &[u8], platform: &str, destination: &Path) -> Result<()> {/// Extracts one executable shipped beside the host (`codync-screen` on Linux), with the same/// rules as [`extract`]. `false` when the archive doesn't carry it.pub fn extract_file(bytes: &[u8], platform: &str, name: &str, destination: &Path) -> Result<bool> {- use std::os::unix::fs::PermissionsExt as _;let decoder = flate2::read::GzDecoder::new(bytes).take(MAX_UNPACKED);let mut archive = tar::Archive::new(decoder);let expected = format!("codync-host-{platform}/{name}");@@ -163,7 +162,11 @@ pub fn extract_file(bytes: &[u8], platform: &str, name: &str, destination: &Pathensure!(entry.size() > 0 && entry.size() < MAX_UNPACKED, "invalid update executable size");let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(destination)?;std::io::copy(&mut entry, &mut file)?;- file.set_permissions(std::fs::Permissions::from_mode(0o755))?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ file.set_permissions(std::fs::Permissions::from_mode(0o755))?;+ }file.sync_all()?;found = true;}