Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.
Rust agent-to-agentai-agentsclaude-codecodexcoding-agentscursorgrokirohmcpmcp-servermulti-agentpeer-to-peerreason
tincan on Windows
Lars Talianf640d58fbe41
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 31000ee..2d6994e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -10,7 +10,7 @@ jobs:strategy:fail-fast: falsematrix:- os: [ubuntu-24.04, macos-14]+ os: [ubuntu-24.04, macos-14, windows-latest]runs-on: ${{ matrix.os }}steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.ymlindex e822994..554c3bc 100644--- a/.github/workflows/pages.yml+++ b/.github/workflows/pages.yml@@ -1,11 +1,11 @@name: pages-# Publishes site/ plus install.sh to GitHub Pages. To serve it from your domain, set the custom domain in+# Publishes site/ plus install.sh and install.ps1 to GitHub Pages. To serve it from your domain, set the custom domain in# Settings > Pages (or add site/CNAME), then set the repo variable TINCAN_SITE_URL=https://<domain>.on:push:branches: [main]- paths: ["site/**", "install.sh", ".github/workflows/pages.yml"]+ paths: ["site/**", "install.sh", "install.ps1", ".github/workflows/pages.yml"]workflow_dispatch:permissions:@@ -25,7 +25,7 @@ jobs:url: ${{ steps.deploy.outputs.page_url }}steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4- - run: cp install.sh site/install.sh+ - run: cp install.sh install.ps1 site/- uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5- uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3with:diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 39678e2..c39d921 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -1,6 +1,6 @@name: release-# Push a tag like v0.1.0 to build binaries for macOS and Linux and publish a GitHub release.+# Push a tag like v0.1.0 to build binaries for macOS, Linux and Windows and publish a GitHub release.on:push:tags: ["v*"]@@ -19,10 +19,14 @@ jobs:- { target: x86_64-apple-darwin, os: macos-14 }- { target: x86_64-unknown-linux-musl, os: ubuntu-24.04 }- { target: aarch64-unknown-linux-musl, os: ubuntu-24.04-arm }+ - { target: x86_64-pc-windows-msvc, os: windows-latest }+ - { target: aarch64-pc-windows-msvc, os: windows-11-arm }runs-on: ${{ matrix.os }}env:# The site team links and the installer point at; set the repo variable once the domain is live.TINCAN_SITE_URL: ${{ vars.TINCAN_SITE_URL }}+ # Windows builds carry their C runtime, so they run without the Visual C++ redistributable.+ RUSTFLAGS: ${{ contains(matrix.target, 'windows') && '-C target-feature=+crt-static' || '' }}steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable@@ -33,10 +37,18 @@ jobs:run: sudo apt-get update && sudo apt-get install -y musl-tools- run: cargo build --release --locked --target ${{ matrix.target }}- name: Package+ if: runner.os != 'Windows'run: |mkdir -p disttar -czf dist/tincan-${{ matrix.target }}.tar.gz -C target/${{ matrix.target }}/release tincancd dist && shasum -a 256 tincan-${{ matrix.target }}.tar.gz > tincan-${{ matrix.target }}.tar.gz.sha256+ - name: Package (Windows)+ if: runner.os == 'Windows'+ run: |+ $name = "tincan-${{ matrix.target }}.zip"+ New-Item -ItemType Directory dist | Out-Null+ Compress-Archive target/${{ matrix.target }}/release/tincan.exe dist/$name+ "$((Get-FileHash dist/$name -Algorithm SHA256).Hash.ToLower()) $name" | Out-File -Encoding ascii dist/$name.sha256- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4with:name: tincan-${{ matrix.target }}@@ -51,7 +63,7 @@ jobs:with:path: distmerge-multiple: true- - run: cp install.sh dist/+ - run: cp install.sh install.ps1 dist/- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2with:files: dist/*diff --git a/Cargo.lock b/Cargo.lockindex d9e3649..b61664c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3608,12 +3608,13 @@ dependencies = [[[package]]name = "tincan"-version = "0.8.0"+version = "0.9.0"dependencies = ["anyhow","blake3","clap","cliclack",+ "console","data-encoding","getrandom 0.3.4","iroh",@@ -3632,6 +3633,7 @@ dependencies = ["toml_edit","tray-icon","ulid",+ "windows-sys 0.61.2",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex adf8dee..9c57f9b 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[package]name = "tincan"-version = "0.8.0"+version = "0.9.0"edition = "2024"description = "Team directory and message bus for coding agents across machines"license = "MIT OR Apache-2.0"@@ -20,7 +20,6 @@ data-encoding = "2"getrandom = "0.3"iroh = "1.3"iroh-mdns-address-lookup = "0.6"-libc = "0.2"rmcp = { version = "3.5", features = ["server", "macros", "transport-io"] }rusqlite = { version = "0.37", features = ["bundled"] }schemars = "1"@@ -31,6 +30,13 @@ toml = "0.9"toml_edit = "0.25"ulid = "1"+[target.'cfg(unix)'.dependencies]+libc = "0.2"++[target.'cfg(windows)'.dependencies]+console = "0.16"+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Pipes", "Win32_System_Threading"] }+[target.'cfg(target_os = "macos")'.dependencies]tray-icon = { version = "0.26", default-features = false }objc2 = "0.6"diff --git a/DESIGN.md b/DESIGN.mdindex 11dc4df..74e3cd4 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -66,7 +66,8 @@ unread mail**, so "tell the api agent X" survives restarts (idea from agentbus).One static Rust binary, `tincan`, with subcommands:- `tincan daemon`: per machine. Owns the iroh endpoint, roster, directory, mailboxes (SQLite). Started on- demand by any other subcommand, or installed as a launchd/systemd user service.+ demand by any other subcommand, or installed as a launchd/systemd user service (on Windows, started at logon+ from the user's Run key; there the local socket is a named pipe).- `tincan mcp`: stdio MCP server spawned by the agent. Thin client of the daemon. **Must handle manysessions per process**: Codex, opencode and Cursor share one MCP process across threads/tabs.- `tincan hook <agent>`: hook handler (status, context injection, stop-continuation, wake).@@ -278,6 +279,8 @@ edits): Claude Code plugin or `claude mcp add --scope user` + hooks, `~/.codex/ctheir side). Messages wait in your outbox and go out when they're back.- **macOS asks to let tincan find devices on your local network:** allow it for direct LAN connections. If youdon't, tincan still works over the internet.+- **Windows asks to let tincan through the firewall:** allow it for direct and LAN connections. If you don't,+ tincan still works, through a relay.- **Codex sessions don't show up until they use a tincan tool:** Codex hasn't been told to trust the hooks yet;run `/hooks` in Codex.- Logs: `~/.tincan/daemon.log`.diff --git a/README.md b/README.mdindex ea60db7..9a22eea 100644--- a/README.md+++ b/README.md@@ -16,6 +16,12 @@ One person runs this and picks a team name:curl -fsSL https://larstalian.github.io/tincan/install.sh | sh```+On Windows, in PowerShell:++```powershell+irm https://larstalian.github.io/tincan/install.ps1 | iex+```+You get a team link (it's on your clipboard). Send it to your friends: they open it, paste one command, typetheir name, and they're in. Or they just tell their agent "join my tincan team: <link>".@@ -58,10 +64,16 @@ name teammates should see, then run this with the whole link, exactly as given.curl -fsSL https://larstalian.github.io/tincan/install.sh | sh -s -- '<the whole link>' --as <name>```-To start a team instead: `curl -fsSL https://larstalian.github.io/tincan/install.sh | sh -s -- init '<team>' --as-<name>`, then `tincan link` prints the link for teammates. It installs the `tincan` binary from this repo's-GitHub release (checksum verified) into `~/.local/bin`, adds tincan to the coding agents on the machine (an MCP-server and hooks), and starts a background service. `tincan who` shows the team.+On Windows (from any shell):++```sh+powershell -c "& ([scriptblock]::Create((irm https://larstalian.github.io/tincan/install.ps1))) '<the whole link>' --as <name>"+```++To start a team instead, give it `init '<team>' --as <name>` in place of the link, then `tincan link` prints the+link for teammates. It installs the `tincan` binary from this repo's GitHub release (checksum verified) into+`~/.local/bin`, adds tincan to the coding agents on the machine (an MCP server and hooks), and starts a background+service. `tincan who` shows the team.## Uninstall@@ -69,6 +81,8 @@ server and hooks), and starts a background service. `tincan who` shows the team.tincan setup --remove && tincan leave && rm -rf ~/.tincan ~/.local/bin/tincan```+On Windows, in PowerShell: `tincan setup --remove; tincan leave; Remove-Item -Recurse -Force ~\.tincan, ~\.local\bin\tincan*`+## Development```shdiff --git a/install.ps1 b/install.ps1new file mode 100644index 0000000..c8608c2--- /dev/null+++ b/install.ps1@@ -0,0 +1,73 @@+# Installs tincan for Windows. In PowerShell:+#+# irm <this url> | iex install, then set up (start or join a team)+# & ([scriptblock]::Create((irm <this url>))) <team link> install, then join that team+# & ([scriptblock]::Create((irm <this url>))) <team link> --as <name> the same, without questions (for agents)+# & ([scriptblock]::Create((irm <this url>))) init <team> --as <name> install and start a team, without questions+#+# From cmd or another shell, wrap it: powershell -c "<the line>".+# Environment: TINCAN_BIN_DIR (default ~\.local\bin), TINCAN_VERSION (default latest), TINCAN_REPO,+# TINCAN_DOWNLOAD_BASE (a mirror serving the release files), TINCAN_NO_PROMPT (never ask anything: updates).+& {+ $ErrorActionPreference = 'Stop'+ $ProgressPreference = 'SilentlyContinue'+ function die($msg) { throw "tincan install: $msg" }++ $repo = if ($env:TINCAN_REPO) { $env:TINCAN_REPO } else { 'larstalian/tincan' }+ $bin = if ($env:TINCAN_BIN_DIR) { $env:TINCAN_BIN_DIR } else { Join-Path $HOME '.local\bin' }+ $version = if ($env:TINCAN_VERSION) { $env:TINCAN_VERSION } else { 'latest' }++ $cpu = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }+ $arch = switch ($cpu) { 'AMD64' { 'x86_64' } 'ARM64' { 'aarch64' } default { die "unsupported CPU: $cpu" } }+ $target = "$arch-pc-windows-msvc"++ if ($env:TINCAN_DOWNLOAD_BASE) { $base = $env:TINCAN_DOWNLOAD_BASE }+ elseif ($version -eq 'latest') { $base = "https://github.com/$repo/releases/latest/download" }+ else { $base = "https://github.com/$repo/releases/download/$version" }++ $tmp = Join-Path ([IO.Path]::GetTempPath()) "tincan-$([guid]::NewGuid().ToString('n'))"+ New-Item -ItemType Directory $tmp | Out-Null+ try {+ Write-Host "Downloading tincan for $target..."+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+ $zip = Join-Path $tmp 'tincan.zip'+ try { Invoke-WebRequest -UseBasicParsing "$base/tincan-$target.zip" -OutFile $zip } catch { die "download failed ($base/tincan-$target.zip)" }+ try { Invoke-WebRequest -UseBasicParsing "$base/tincan-$target.zip.sha256" -OutFile "$zip.sha256" } catch { die 'checksum download failed; not installing' }+ $want = ([IO.File]::ReadAllText("$zip.sha256") -split '\s+')[0].ToLower()+ $file = [IO.File]::OpenRead($zip)+ try { $got = -join ([Security.Cryptography.SHA256]::Create().ComputeHash($file) | ForEach-Object { $_.ToString('x2') }) } finally { $file.Dispose() }+ if (-not $want -or $want -ne $got) { die 'checksum mismatch; not installing' }+ Add-Type -AssemblyName System.IO.Compression.FileSystem+ [IO.Compression.ZipFile]::ExtractToDirectory($zip, $tmp)++ New-Item -ItemType Directory -Force $bin | Out-Null+ $exe = Join-Path $bin 'tincan.exe'+ # Windows can't replace a program that is running, but it can rename it: move the old one aside, and delete+ # the ones set aside before once nothing runs them.+ Get-ChildItem $bin -Filter 'tincan.*.old' | Remove-Item -Force -ErrorAction SilentlyContinue+ $old = $null+ if (Test-Path $exe) { $old = Join-Path $bin "tincan.$(Get-Random).old"; Move-Item $exe $old }+ try { Move-Item (Join-Path $tmp 'tincan.exe') $exe } catch { if ($old) { Move-Item $old $exe }; throw }+ } finally {+ Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue+ }+ Write-Host "Installed $exe ($(& $exe --version))"++ $path = [Environment]::GetEnvironmentVariable('Path', 'User')+ if (($path -split ';') -notcontains $bin) {+ [Environment]::SetEnvironmentVariable('Path', (@($path -split ';' | Where-Object { $_ }) + $bin) -join ';', 'User')+ $env:Path = "$env:Path;$bin"+ Write-Host "Added $bin to your PATH (open a new terminal to use it there)."+ }++ # Hand over to tincan: it asks a few questions (name, invite code, which agents) when there's someone to ask.+ if ($args.Count -eq 0) {+ if ($env:TINCAN_NO_PROMPT -or [Console]::IsInputRedirected) { Write-Host ''; Write-Host 'Next, in a terminal: tincan'; return }+ & $exe+ } elseif ($args[0] -match '^(-.*|init|join|setup)$') {+ & $exe @args+ } else {+ & $exe join @args+ }+ if ($LASTEXITCODE) { throw "tincan exited with code $LASTEXITCODE" }+} @argsdiff --git a/site/index.html b/site/index.htmlindex 53a878d..453514f 100644--- a/site/index.html+++ b/site/index.html@@ -47,6 +47,8 @@<h2>Start a team</h2><pre><code>curl -fsSL https://larstalian.github.io/tincan/install.sh | sh</code></pre>+ <p>On Windows, in PowerShell:</p>+<pre><code>irm https://larstalian.github.io/tincan/install.ps1 | iex</code></pre><p>It asks your name and a team name, sets up your coding agents, and gives you a team link. Send it to your friends: it opens a page with one command, they paste it, type their name, and they're in. The same link works for everyone, for good.</p><h2>What it does</h2>@@ -71,7 +73,9 @@<p>Your user gave you a team link (<code>…/tincan/join/#tincan1…</code>)? Ask them what name teammates should see, thenrun this with the whole link, exactly as given (it asks no questions):</p><pre><code>curl -fsSL https://larstalian.github.io/tincan/install.sh | sh -s -- '<the whole link>' --as <name></code></pre>- <p>To start a team instead: <code>curl -fsSL https://larstalian.github.io/tincan/install.sh | sh -s -- init '<team name>' --as <name></code>,+ <p>On Windows (from any shell):</p>+ <pre><code>powershell -c "& ([scriptblock]::Create((irm https://larstalian.github.io/tincan/install.ps1))) '<the whole link>' --as <name>"</code></pre>+ <p>To start a team instead, give it <code>init '<team name>' --as <name></code> in place of the link,then <code>tincan link</code> prints the link for teammates. It installs the binary from the<a href="https://github.com/larstalian/tincan">GitHub release</a> (checksum verified), adds tincan to the codingagents on the machine, and starts a small background service; <code>tincan setup --remove</code> undoes it.</p>diff --git a/site/join/index.html b/site/join/index.htmlindex 9677ae2..8208a5c 100644--- a/site/join/index.html+++ b/site/join/index.html@@ -44,8 +44,9 @@<img class="hero" src="../tincan.svg" alt="Two little AI agent robots talking through tin cans on a string" width="1200" height="500"><div id="ok"><h1>Join <span id="team">a team</span> on tincan</h1>- <p class="lede">Paste this in a terminal (macOS or Linux), then type your name:</p>+ <p class="lede">Paste this in a terminal, then type your name:</p><div class="cmd"><pre id="cmd">curl -fsSL https://larstalian.github.io/tincan/install.sh | sh -s -- '<the whole link to this page>'</pre><button id="copy" type="button">Copy</button></div>+ <p class="muted" style="margin:8px 0 0"><a href="#" id="other-os" hidden>On Windows?</a></p><p class="muted" style="margin:18px 0 6px">Or tell your coding agent:</p><div class="cmd"><pre id="agent">Join my tincan team: <the whole link to this page></pre><button id="copy-agent" type="button">Copy</button></div><p class="muted" style="margin-top:28px">Teammates see your name and what your agent sessions are working on.@@ -60,6 +61,8 @@exactly as your user gave it to you.</p><p>Ask your user what name their teammates should see (a first name, like <code>alex</code>), then run:</p><pre>curl -fsSL https://larstalian.github.io/tincan/install.sh | sh -s -- '<the whole link>' --as <name></pre>+ <p>On Windows:</p>+ <pre>powershell -c "& ([scriptblock]::Create((irm https://larstalian.github.io/tincan/install.ps1))) '<the whole link>' --as <name>"</pre><p>It asks no questions. It downloads the tincan binary for this OS and CPU from the project's GitHub release(checksum verified) into <code>~/.local/bin</code>, joins the team, adds tincan to the coding agents installedhere (an MCP server and hooks for Claude Code, Codex, Cursor, Gemini CLI, Copilot CLI, opencode, pi; Reason if@@ -90,31 +93,45 @@}const name = teamName(ticket);if (name) {- const installer = new URL("../install.sh", location.href).href;- const cmd = `curl -fsSL ${installer} | sh -s -- ${ticket}`;+ const script = (file) => new URL(`../${file}`, location.href).href;+ const unix = `curl -fsSL ${script("install.sh")} | sh -s -- ${ticket}`;+ const windows = `powershell -c "& ([scriptblock]::Create((irm ${script("install.ps1")}))) ${ticket}"`;const agent = `Join my tincan team: ${location.href}`;document.getElementById("team").textContent = name;document.title = `Join ${name} on tincan`;- document.getElementById("cmd").textContent = cmd;document.getElementById("agent").textContent = agent;- const copyButton = (id, pre, text) => {+ // The command for this computer, and a link to the other one.+ let win = /Windows/.test(navigator.userAgent);+ const other = document.getElementById("other-os");+ const show = () => {+ document.getElementById("cmd").textContent = win ? windows : unix;+ other.textContent = win ? "On macOS or Linux?" : "On Windows?";+ };+ other.hidden = false;+ other.addEventListener("click", (e) => {+ e.preventDefault();+ win = !win;+ show();+ });+ show();+ const copyButton = (id, pre) => {const btn = document.getElementById(id);btn.addEventListener("click", async () => {try {- await navigator.clipboard.writeText(text);+ await navigator.clipboard.writeText(document.getElementById(pre).textContent);btn.textContent = "Copied";} catch (e) {const range = document.createRange();range.selectNodeContents(document.getElementById(pre));getSelection().removeAllRanges();getSelection().addRange(range);- btn.textContent = "Press ⌘C";+ btn.textContent = /Mac/.test(navigator.userAgent) ? "Press ⌘C" : "Press Ctrl+C";}setTimeout(() => (btn.textContent = "Copy"), 2000);});};- copyButton("copy", "cmd", cmd);- copyButton("copy-agent", "agent", agent);+ copyButton("copy", "cmd");+ copyButton("copy-agent", "agent");// People have the steps above; the agent notes are for agents reading the page's text.document.getElementById("for-agents").hidden = true;} else {diff --git a/site/skill/SKILL.md b/site/skill/SKILL.mdindex 548ce99..68ff393 100644--- a/site/skill/SKILL.md+++ b/site/skill/SKILL.md@@ -17,6 +17,12 @@ your user's own cloud agent, their own name), then run, with the whole link exaccurl -fsSL https://larstalian.github.io/tincan/install.sh | sh -s -- '<the whole link>' --as <name>```+On Windows:++```sh+powershell -c "& ([scriptblock]::Create((irm https://larstalian.github.io/tincan/install.ps1))) '<the whole link>' --as <name>"+```+## Commands- `tincan who`: every person, machine and session, with what each is working on. Check it before messaging, sodiff --git a/src/agent.rs b/src/agent.rsindex 876e5d0..f9199e2 100644--- a/src/agent.rs+++ b/src/agent.rs@@ -2,7 +2,10 @@use crate::{git::GitInfo, paths, util};use serde_json::{Value, json};-use std::{io::Write, os::unix::net::UnixStream, path::PathBuf, time::Duration};+use std::{+ io::Write,+ path::{Path, PathBuf},+};pub const CLAUDE_CODE: &str = "claude-code";@@ -95,13 +98,15 @@ pub fn meta_session_id(meta: &serde_json::Map<String, Value>) -> Option<String>.map(str::to_string)}-/// Finds an executable on `PATH` or in the usual install places (a launchd/systemd daemon has a bare `PATH`).+/// Finds an executable on `PATH` or in the usual install places (a launchd/systemd daemon has a bare `PATH`). On+/// Windows that is `<name>.exe`, or the `<name>.cmd` npm installs.pub fn find_bin(name: &str) -> Option<PathBuf> {if let Some(p) = std::env::var_os(format!("TINCAN_{}_BIN", name.to_uppercase())) {let p = PathBuf::from(p);return p.is_file().then_some(p);}let home = paths::user_home();+ #[cfg(unix)]let extra = [home.join(".local/bin"),home.join(".bun/bin"),@@ -112,25 +117,33 @@ pub fn find_bin(name: &str) -> Option<PathBuf> {PathBuf::from("/usr/local/bin"),PathBuf::from("/usr/bin"),];+ #[cfg(windows)]+ let extra = [home.join(r".local\bin"), home.join(r"AppData\Roaming\npm"), home.join(r".bun\bin")];+ let exts: &[&str] = if cfg!(windows) { &[".exe", ".cmd"] } else { &[""] };let path = std::env::var_os("PATH").unwrap_or_default();- std::env::split_paths(&path).chain(extra).map(|d| d.join(name)).find(|p| {- use std::os::unix::fs::PermissionsExt;- p.metadata().is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)- })+ std::env::split_paths(&path).chain(extra).flat_map(|d| exts.iter().map(move |ext| d.join(format!("{name}{ext}")))).find(|p| executable(p))+}++#[cfg(unix)]+fn executable(p: &Path) -> bool {+ use std::os::unix::fs::PermissionsExt;+ p.metadata().is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)+}++#[cfg(windows)]+fn executable(p: &Path) -> bool {+ p.is_file()}/// The agent process behind a hook: our parent, skipping the shell some agents run hooks through.pub fn hook_agent_pid() -> Option<u32> {let mut pid = util::parent_pid();for _ in 0..3 {- let out = std::process::Command::new("ps").args(["-o", "ppid=,comm=", "-p", &pid.to_string()]).output().ok()?;- let line = String::from_utf8_lossy(&out.stdout).trim().to_string();- let (ppid, comm) = line.split_once(' ')?;- let comm = comm.trim().rsplit('/').next().unwrap_or_default().trim_start_matches('-');- if !matches!(comm, "sh" | "bash" | "zsh" | "fish" | "dash" | "ksh") {+ let (ppid, name) = util::process(pid)?;+ if !matches!(name.as_str(), "sh" | "bash" | "zsh" | "fish" | "dash" | "ksh" | "cmd" | "powershell" | "pwsh") {return Some(pid);}- pid = ppid.trim().parse().ok()?;+ pid = ppid;}Some(pid)}@@ -155,7 +168,7 @@ pub fn label(agent: &str) -> &str {/// `<repo-or-dir>-<agent>`, e.g. `api-claude`.pub fn default_name(agent: &str, cwd: &str, git: &GitInfo) -> String {let dir = git.root.as_deref().unwrap_or(cwd);- let base = util::slug(dir.rsplit('/').find(|s| !s.is_empty()).unwrap_or("home"));+ let base = util::slug(Path::new(dir).file_name().and_then(|n| n.to_str()).unwrap_or("home"));let base = if base.is_empty() { "home".into() } else { base };format!("{base}-{}", short(agent))}@@ -187,15 +200,15 @@ pub fn claude_socket() -> Option<ClaudeSocket> {return Some(ClaudeSocket { path: path.into(), token });}// Not exported to this process: fall back to the session's registry entry.- let file = paths::claude_sessions().join(format!("{}.json", agent_pid()));+ let pid = agent_pid();+ let file = paths::claude_sessions().join(format!("{pid}.json"));let s: Value = serde_json::from_str(&std::fs::read_to_string(file).ok()?).ok()?;let path = s["messagingSocketPath"].as_str()?;- Some(ClaudeSocket { path: path.into(), token })+ Some(ClaudeSocket { path: path.into(), token: token.or_else(|| crate::claude::peer_token(pid)) })}pub fn post_to_claude(sock: &ClaudeSocket, text: &str) -> std::io::Result<()> {- let mut c = UnixStream::connect(&sock.path)?;- c.set_write_timeout(Some(Duration::from_secs(5)))?;+ let mut c = open_inbox(&sock.path)?;if let Some(t) = &sock.token {writeln!(c, "{}", json!({ "type": "auth", "token": t }))?;}@@ -203,6 +216,19 @@ pub fn post_to_claude(sock: &ClaudeSocket, text: &str) -> std::io::Result<()> {c.flush()}+#[cfg(unix)]+fn open_inbox(path: &Path) -> std::io::Result<std::os::unix::net::UnixStream> {+ let c = std::os::unix::net::UnixStream::connect(path)?;+ c.set_write_timeout(Some(std::time::Duration::from_secs(5)))?;+ Ok(c)+}++/// On Windows the session's inbox is a named pipe, which opens like a file.+#[cfg(windows)]+fn open_inbox(path: &Path) -> std::io::Result<std::fs::File> {+ std::fs::OpenOptions::new().read(true).write(true).open(path)+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/claude.rs b/src/claude.rsindex e92f410..dda3a9b 100644--- a/src/claude.rs+++ b/src/claude.rs@@ -1,7 +1,7 @@//! Claude Code keeps one `~/.claude/sessions/<pid>.json` per live session (name, cwd, busy/idle). Reading them//! lists every Claude session on this machine, including ones that don't have tincan loaded.-use crate::{paths, util};+use crate::{agent::ClaudeSocket, paths, util};use serde::Deserialize;#[derive(Debug, Clone, Deserialize)]@@ -69,10 +69,26 @@ pub fn wired() -> bool {}/// The messaging socket of a live session, by its id or process.-pub fn socket_for(session_id: Option<&str>, pid: Option<u32>) -> Option<std::path::PathBuf> {- scan()+pub fn socket_for(session_id: Option<&str>, pid: Option<u32>) -> Option<ClaudeSocket> {+ let c = scan().into_iter()- .find(|c| (session_id.is_some() && c.session_id.as_deref() == session_id) || (pid.is_some() && Some(c.pid) == pid))?- .messaging_socket_path- .map(Into::into)+ .find(|c| (session_id.is_some() && c.session_id.as_deref() == session_id) || (pid.is_some() && Some(c.pid) == pid))?;+ Some(ClaudeSocket { path: c.messaging_socket_path?.into(), token: peer_token(c.pid) })+}++/// The token a session's messaging socket wants from its peers, which Claude Code asks for on Windows only. It+/// leaves it for them in `~/.claude/sessions/<pid>.<hash>.key`.+pub fn peer_token(pid: u32) -> Option<String> {+ if !cfg!(windows) {+ return None;+ }+ let prefix = format!("{pid}.");+ std::fs::read_dir(paths::claude_sessions()).ok()?.flatten().find_map(|e| {+ let name = e.file_name().into_string().ok()?;+ if !name.starts_with(&prefix) || !name.ends_with(".key") {+ return None;+ }+ let v: serde_json::Value = serde_json::from_slice(&std::fs::read(e.path()).ok()?).ok()?;+ v["peerToken"].as_str().map(str::to_string)+ })}diff --git a/src/client.rs b/src/client.rsindex ce07572..47cb704 100644--- a/src/client.rs+++ b/src/client.rs@@ -1,13 +1,12 @@//! Connection to the local daemon, starting it if needed. Long-lived clients (`tincan mcp`) reconnect on their//! own and re-register their sessions, so a daemon restart is invisible to the agent.-use crate::{paths, proto::*};+use crate::{ipc, paths, proto::*};use anyhow::{Result, anyhow, bail};use serde::de::DeserializeOwned;use serde_json::Value;use std::{collections::HashMap,- os::unix::process::CommandExt,process::{Command, Stdio},sync::{Arc, Mutex, Weak,@@ -17,7 +16,6 @@ use std::{};use tokio::{io::{AsyncBufReadExt, AsyncWriteExt, BufReader},- net::UnixStream,sync::{mpsc, oneshot},};@@ -100,8 +98,8 @@ impl Link {Ok(c)}- fn spawn_io(self: &Arc<Self>, stream: UnixStream) -> Conn {- let (rd, mut wr) = stream.into_split();+ fn spawn_io(self: &Arc<Self>, stream: ipc::Stream) -> Conn {+ let (rd, mut wr) = tokio::io::split(stream);let (tx, mut rx) = mpsc::unbounded_channel::<String>();let conn = Conn { tx, pending: Pending::default(), alive: Arc::new(AtomicBool::new(true)) };tokio::spawn(async move {@@ -159,17 +157,14 @@ pub fn running_daemon() -> Option<u32> {/// Who holds the lock at `path`. Asked of the lock, not the pid: a daemon that exited holds none, even when a/// parent that never reaps (a container's `sleep` as PID 1) leaves it a zombie whose pid still "exists".fn holder(path: &std::path::Path) -> Option<u32> {- use std::os::unix::io::AsRawFd;- let f = std::fs::File::open(path).ok()?;- if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) } == 0 {+ if !crate::util::locked(path) {return None;}std::fs::read_to_string(path).ok()?.trim().parse().ok()}-async fn connect_or_start(start: bool) -> Result<UnixStream> {- let sock = paths::socket();- if let Ok(s) = UnixStream::connect(&sock).await {+async fn connect_or_start(start: bool) -> Result<ipc::Stream> {+ if let Ok(s) = ipc::connect().await {return Ok(s);}if !start {@@ -183,14 +178,14 @@ async fn connect_or_start(start: bool) -> Result<UnixStream> {&& std::env::var_os("TINCAN_NO_SERVICE").is_none()&& crate::setup::start_service();if !by_service {- child = Some(start_daemon()?);+ child = Some(start_daemon(false)?);}}let failed = || anyhow!("could not start the tincan daemon; see {}", paths::log().display());let mut connected = None;for _ in 0..100 {tokio::time::sleep(Duration::from_millis(50)).await;- if let Ok(s) = UnixStream::connect(&sock).await {+ if let Ok(s) = ipc::connect().await {connected = Some(s);break;}@@ -211,17 +206,37 @@ async fn connect_or_start(start: bool) -> Result<UnixStream> {connected.ok_or_else(failed)}-/// Starts `tincan daemon` detached from this process group, logging to `~/.tincan/daemon.log`.-fn start_daemon() -> Result<std::process::Child> {+/// Starts `tincan daemon` (`--service` with `service`) detached from this process group, logging to+/// `~/.tincan/daemon.log`.+pub fn start_daemon(service: bool) -> Result<std::process::Child> {paths::ensure_home()?;let log = std::fs::OpenOptions::new().create(true).append(true).open(paths::log())?;- Ok(Command::new(crate::util::current_exe()?)- .arg("daemon")- .stdin(Stdio::null())- .stdout(log.try_clone()?)- .stderr(log)- .process_group(0)- .spawn()?)+ let mut cmd = Command::new(crate::util::current_exe()?);+ cmd.arg("daemon").args(service.then_some("--service")).stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);+ #[cfg(unix)]+ let child = std::os::unix::process::CommandExt::process_group(&mut cmd, 0).spawn()?;+ #[cfg(windows)]+ let child = detach(&mut cmd)?;+ Ok(child)+}++/// On Windows: no window, out of reach of this console's Ctrl-C, and without our own standard handles, which+/// Windows would hand it otherwise (an agent reading a hook's output to the end would wait for the daemon too).+/// Nor any other handle we inherited: Windows PowerShell capturing our output hands us its own standard handles+/// as well. Also out of the starter's job when the job allows it: an SSH session's job ends everything at logout.+#[cfg(windows)]+fn detach(cmd: &mut Command) -> std::io::Result<std::process::Child> {+ use std::os::windows::{io::AsRawHandle, process::CommandExt};+ use windows_sys::Win32::{Foundation::*, System::Threading::*};+ let ours = [std::io::stdin().as_raw_handle(), std::io::stdout().as_raw_handle(), std::io::stderr().as_raw_handle()];+ // Handles are multiples of 4; what we inherited sits where it sat in our parent. (`cmd`'s own are made+ // inheritable again when it spawns.)+ for h in ours.into_iter().chain((4..1usize << 16).step_by(4).map(|h| h as HANDLE)) {+ // SAFETY: only clears inherit flags; a value that isn't an open handle just fails.+ unsafe { SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0) };+ }+ let flags = CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP;+ cmd.creation_flags(flags | CREATE_BREAKAWAY_FROM_JOB).spawn().or_else(|_| cmd.creation_flags(flags).spawn())}#[cfg(test)]diff --git a/src/config.rs b/src/config.rsindex 23e0e9a..0d4e70d 100644--- a/src/config.rs+++ b/src/config.rs@@ -79,7 +79,7 @@ impl Config {pub fn person(&self) -> String {self.person.clone()- .or_else(|| std::env::var("USER").ok())+ .or_else(|| std::env::var(if cfg!(windows) { "USERNAME" } else { "USER" }).ok()).map(|s| util::slug(&s)).filter(|s| !s.is_empty()).unwrap_or_else(|| "me".into())diff --git a/src/daemon/directory.rs b/src/daemon/directory.rsindex 6440b45..9ed8bf1 100644--- a/src/daemon/directory.rs+++ b/src/daemon/directory.rs@@ -192,7 +192,7 @@ impl Daemon {let mut sessions = self.local_rows(None, self.cfg.share_unmanaged).await.unwrap_or_default();if !self.cfg.share_paths {for s in &mut sessions {- s.cwd = s.cwd.rsplit('/').find(|p| !p.is_empty()).unwrap_or("~").to_string();+ s.cwd = std::path::Path::new(&s.cwd).file_name().map_or("~".into(), |n| n.to_string_lossy().into_owned());}}let g = self.inner.lock().unwrap();diff --git a/src/daemon/mail.rs b/src/daemon/mail.rsindex 5245f71..6fca62e 100644--- a/src/daemon/mail.rs+++ b/src/daemon/mail.rs@@ -31,7 +31,7 @@ enum Channel {/// The agent's own CLI: `codex queue --thread <id> --message`, `reason session send <id> --message`.Command(&'static str, Vec<String>),/// Straight into a Claude Code session's messaging socket (one without tincan's tools: it replies with the CLI).- ClaudeDirect(std::path::PathBuf),+ ClaudeDirect(agent::ClaudeSocket),/// Hooks inject it at the next tool call or turn end.Hook,/// Only `check_inbox`.@@ -191,7 +191,7 @@ impl Daemon {}(Tier::Push, None, id) if l.reg.agent == agent::CLAUDE_CODE && !l.push_failed => {match claude::socket_for(id.as_deref(), l.reg.pid) {- Some(path) => Channel::ClaudeDirect(path),+ Some(sock) => Channel::ClaudeDirect(sock),None => Channel::Pull,}}@@ -227,11 +227,11 @@ impl Daemon {self.send_with(bin, args, key.to_string(), ids, text);("pushed".into(), format!("queued into the {} session: it runs after the current turn, or now if idle", agent::label(bin)))}- Channel::ClaudeDirect(path) => {+ Channel::ClaudeDirect(sock) => {for id in &ids {g.in_flight.insert(id.clone(), Instant::now());}- self.post_direct(key.to_string(), path, ids, text);+ self.post_direct(key.to_string(), sock, ids, text);("pushed".into(), "delivered into the session: it reads it between tool calls, or wakes up if idle".into())}Channel::Hook => ("queued".into(), hook_note.into()),@@ -240,11 +240,10 @@ impl Daemon {}/// Posts into a Claude Code session's messaging socket; read once it took it.- fn post_direct(self: &Arc<Self>, key: String, path: std::path::PathBuf, ids: Vec<String>, text: String) {+ fn post_direct(self: &Arc<Self>, key: String, sock: agent::ClaudeSocket, ids: Vec<String>, text: String) {let this = self.clone();tokio::spawn(async move {- let sock = agent::ClaudeSocket { path, token: None };- let res = tokio::task::spawn_blocking(move || agent::post_to_claude(&sock, &text)).await;+ let res =tokio::task::spawn_blocking(move || agent::post_to_claude(&sock, &text)).await;let mut g = this.inner.lock().unwrap();for id in &ids {g.in_flight.remove(id);diff --git a/src/daemon/mod.rs b/src/daemon/mod.rsindex 282cbf9..9820f1a 100644--- a/src/daemon/mod.rs+++ b/src/daemon/mod.rs@@ -12,6 +12,7 @@ mod update;use crate::{config::Config,git::{self, GitInfo},+ ipc,net::Net,paths,proto::*,@@ -19,7 +20,7 @@ use crate::{team::TeamState,util,};-use anyhow::{Context, Result, anyhow};+use anyhow::{Result, anyhow};use iroh::SecretKey;use serde_json::{Value, json};use std::{@@ -29,7 +30,6 @@ use std::{};use tokio::{io::{AsyncBufReadExt, AsyncWriteExt, BufReader},- net::{UnixListener, UnixStream},sync::{Notify, mpsc},};@@ -38,26 +38,28 @@ const MAX_WAIT: u64 = 600;/// Runs the daemon. Only one runs per `TINCAN_HOME`: a second one exits, or with `service` waits its turn.pub async fn run(service: bool) -> Result<()> {+ // Windows runs what starts at logon in a console window of its own: carry on in a hidden process instead.+ #[cfg(windows)]+ if service && std::io::IsTerminal::is_terminal(&std::io::stderr()) {+ crate::client::start_daemon(true)?;+ return Ok(());+ }paths::ensure_home()?;let lock = tokio::task::spawn_blocking(move || util::lock(&paths::lock(), service)).await??;let Some(_lock) = lock else {log("another daemon is already running");return Ok(());};- let sock = paths::socket();- paths::ensure_socket_dir()?;- let _ = std::fs::remove_file(&sock);- let listener = UnixListener::bind(&sock).with_context(|| format!("binding {}", sock.display()))?;- util::chmod(&sock, 0o600)?;+ let mut listener = ipc::Listener::bind()?;let daemon = Arc::new(Daemon::open()?);- log(&format!("listening on {} as {}@{}", sock.display(), daemon.person, daemon.machine));+ log(&format!("listening on {} as {}@{}", paths::socket().display(), daemon.person, daemon.machine));if daemon.team_state().is_some()&& let Err(e) = daemon.start_net().await{log(&format!("network not started: {e:#}"));}// Normally the service's daemon; a daemon started some other way stands in for it while it runs.- if (service || crate::setup::service_installed()) && daemon.cfg.tray() {+ if daemon.cfg.tray() && (service || crate::setup::service_installed()) {tokio::spawn(tray());}if daemon.cfg.reason {@@ -67,7 +69,7 @@ pub async fn run(service: bool) -> Result<()> {tokio::spawn(daemon.clone().update_loop());}loop {- let (stream, _) = listener.accept().await?;+ let stream = listener.accept().await?;tokio::spawn(daemon.clone().serve(stream));}}@@ -147,6 +149,7 @@ fn load_key() -> Result<SecretKey> {}let key = SecretKey::generate();std::fs::write(&path, key.to_bytes())?;+ #[cfg(unix)]util::chmod(&path, 0o600)?;Ok(key)}@@ -196,8 +199,8 @@ impl Daemon {}}- async fn serve(self: Arc<Self>, stream: UnixStream) {- let (rd, mut wr) = stream.into_split();+ async fn serve(self: Arc<Self>, stream: ipc::Accepted) {+ let (rd, mut wr) = tokio::io::split(stream);let (tx, mut rx) = mpsc::unbounded_channel::<String>();let conn = {let mut g = self.inner.lock().unwrap();@@ -298,7 +301,13 @@ impl Daemon {if let Some(net) = this.net() {net.shutdown().await;}+ #[cfg(unix)]let _ = std::fs::remove_file(paths::socket());+ // Windows has no service manager to bring us back: start the one that takes over once we're gone.+ #[cfg(windows)]+ if crate::setup::service_installed() {+ let _ = crate::client::start_daemon(true);+ }std::process::exit(0);});}diff --git a/src/daemon/update.rs b/src/daemon/update.rsindex 73c0108..7a192ab 100644--- a/src/daemon/update.rs+++ b/src/daemon/update.rs@@ -1,6 +1,6 @@//! Keeps tincan up to date: every few hours the daemon looks for a newer release and, if there is one, installs it-//! over its own binary (with install.sh, checksum verified) and restarts on it. Off with `auto_update = false`;-//! never for builds run from a source tree.+//! over its own binary (with install.sh, or install.ps1 on Windows, checksum verified) and restarts on it. Off with+//! `auto_update = false`; never for builds run from a source tree.use super::{Daemon, log};use anyhow::{Result, bail};@@ -39,22 +39,19 @@ async fn update() -> Result<Option<String>> {return Ok(None);}let dir = crate::util::current_exe()?.parent().map(|d| d.to_path_buf()).unwrap_or_default();- // In its own process group, so a timeout kills the whole pipeline (curl and the inner sh too).- let child = tokio::process::Command::new("sh")- .arg("-c")- .arg(format!("curl -fsSL {} | sh", crate::install_url()))- .env("TINCAN_BIN_DIR", &dir)- .env("TINCAN_NO_PROMPT", "1")- .stdin(std::process::Stdio::null())- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped())- .process_group(0)- .kill_on_drop(true)- .spawn()?;+ let mut cmd = tokio::process::Command::from(crate::installer(&dir));+ cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).kill_on_drop(true);+ // In its own process group, so a timeout kills the whole pipeline (curl and the inner sh too). (On Windows the+ // installer is one PowerShell, which `kill_on_drop` ends.)+ #[cfg(unix)]+ cmd.process_group(0);+ let child = cmd.spawn()?;+ #[cfg(unix)]let group = child.id();let out = match tokio::time::timeout(Duration::from_secs(300), child.wait_with_output()).await {Ok(out) => out?,Err(_) => {+ #[cfg(unix)]if let Some(pgid) = group {// SAFETY: signals the process group we just created.unsafe { libc::killpg(pgid as libc::pid_t, libc::SIGKILL) };@@ -66,7 +63,8 @@ async fn update() -> Result<Option<String>> {bail!("install failed: {}", String::from_utf8_lossy(&out.stderr).trim());}// Restart only on a binary that really is newer (a release tagged without bumping its version must not loop).- let installed = tokio::process::Command::new(dir.join("tincan")).arg("--version").kill_on_drop(true).output();+ let installed = dir.join(format!("tincan{}", std::env::consts::EXE_SUFFIX));+ let installed = tokio::process::Command::new(installed).arg("--version").kill_on_drop(true).output();let installed = tokio::time::timeout(Duration::from_secs(30), installed).await??;let installed = String::from_utf8_lossy(&installed.stdout).trim().rsplit(' ').next().unwrap_or_default().to_string();if !newer(&installed, env!("CARGO_PKG_VERSION")) {@@ -78,8 +76,9 @@ async fn update() -> Result<Option<String>> {/// The newest release's version, from where GitHub's "latest release" link redirects.async fn latest_version() -> Result<String> {let repo = std::env::var("TINCAN_REPO").unwrap_or_else(|_| "larstalian/tincan".into());+ let null = if cfg!(windows) { "NUL" } else { "/dev/null" };let out = tokio::process::Command::new("curl")- .args(["-fsSLI", "--max-time", "50", "-o", "/dev/null", "-w", "%{url_effective}", &format!("https://github.com/{repo}/releases/latest")])+ .args(["-fsSLI", "--max-time", "50", "-o", null, "-w", "%{url_effective}", &format!("https://github.com/{repo}/releases/latest")]).stdin(std::process::Stdio::null()).kill_on_drop(true).output();diff --git a/src/doing.rs b/src/doing.rsindex d5c705b..9f3c6e9 100644--- a/src/doing.rs+++ b/src/doing.rs@@ -110,7 +110,8 @@ fn scan(path: &Path) -> Seen {let (len, modified) = (meta.len(), meta.modified().ok());let mut tails = TAILS.get_or_init(Default::default).lock().unwrap();let t = tails.entry(path.to_path_buf()).or_insert(Tail { modified: None, offset: 0, whole: false, seen: Seen::default() });- if t.modified == modified && t.offset <= len {+ // Nothing new to read (by its length too: Windows' file times are too coarse to tell appends apart).+ if t.modified == modified && t.offset == len {return t.seen.clone();}if t.whole || len < t.offset {diff --git a/src/hook.rs b/src/hook.rsindex 0ad44bc..0194ed4 100644--- a/src/hook.rs+++ b/src/hook.rs@@ -45,7 +45,8 @@ async fn handle(state: Option<String>,doing: Option<String>,) -> Option<(String, String, Vec<String>)> {- let v: Value = serde_json::from_str(input).unwrap_or(Value::Null);+ // Windows PowerShell pipes it in after a byte-order mark.+ let v: Value = serde_json::from_str(input.trim_start_matches('\u{feff}')).unwrap_or(Value::Null);let agent = agent::from_client_name(agent_name).unwrap_or(agent_name);let str_at = |k: &str| v.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string);@@ -97,7 +98,7 @@ async fn handle(fn format_for(agent: &str, event: &str, ev: &str, text: &str) -> String {let specific = |name: &str| json!({ "hookSpecificOutput": { "hookEventName": name, "additionalContext": text } });let block = || json!({ "decision": "block", "reason": text });- match (agent, ev) {+ let out = match (agent, ev) {("opencode", _) if event == "poll" => return text.to_string(),("codex", "start") => specific("SessionStart"),("codex", "prompt") => specific("UserPromptSubmit"),@@ -111,7 +112,13 @@ fn format_for(agent: &str, event: &str, ev: &str, text: &str) -> String {("copilot", _) => json!({ "additionalContext": text }),_ => return text.to_string(),}- .to_string()+ .to_string();+ // On Windows agents run hooks through PowerShell, which can re-encode what passes through it: JSON in ASCII is+ // safe from that.+ if !cfg!(windows) {+ return out;+ }+ out.chars().map(|c| if c.is_ascii() { c.to_string() } else { c.encode_utf16(&mut [0; 2]).iter().map(|u| format!("\\u{u:04x}")).collect() }).collect()}#[cfg(test)]diff --git a/src/ipc.rs b/src/ipc.rsnew file mode 100644index 0000000..4b9f2f2--- /dev/null+++ b/src/ipc.rs@@ -0,0 +1,88 @@+//! The daemon's local socket: a Unix socket, or a named pipe on Windows.++use crate::paths;+use anyhow::{Context, Result};+use std::io;++#[cfg(unix)]+pub use tokio::net::UnixStream as Stream;+#[cfg(windows)]+pub use tokio::net::windows::named_pipe::NamedPipeClient as Stream;++/// The daemon's end of a client's connection.+#[cfg(unix)]+pub use tokio::net::UnixStream as Accepted;+#[cfg(windows)]+pub use tokio::net::windows::named_pipe::NamedPipeServer as Accepted;++#[cfg(unix)]+pub async fn connect() -> io::Result<Stream> {+ Stream::connect(paths::socket()).await+}++#[cfg(windows)]+pub async fn connect() -> io::Result<Stream> {+ use std::os::windows::io::AsRawHandle;+ use tokio::net::windows::named_pipe::ClientOptions;+ let mut tries = 0;+ let pipe = loop {+ match ClientOptions::new().open(paths::socket()) {+ // Every instance is taken for a moment while the daemon opens the next one.+ Err(e) if e.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PIPE_BUSY as i32) && tries < 20 => tries += 1,+ r => break r?,+ }+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ };+ // Anyone on the machine can make a pipe by that name: talk only to the daemon that holds our lock.+ let mut server = 0;+ // SAFETY: asks about the pipe handle we hold.+ unsafe { windows_sys::Win32::System::Pipes::GetNamedPipeServerProcessId(pipe.as_raw_handle(), &mut server) };+ if crate::client::running_daemon() != Some(server) {+ return Err(io::Error::other(format!("{} is not this user's tincan daemon", paths::socket().display())));+ }+ Ok(pipe)+}++/// Where the daemon takes connections. Only the daemon holding the lock opens it.+pub struct Listener(#[cfg(unix)] tokio::net::UnixListener, #[cfg(windows)] Accepted);++impl Listener {+ #[cfg(unix)]+ pub fn bind() -> Result<Self> {+ let sock = paths::socket();+ paths::ensure_socket_dir()?;+ let _ = std::fs::remove_file(&sock);+ let listener = tokio::net::UnixListener::bind(&sock).with_context(|| format!("binding {}", sock.display()))?;+ crate::util::chmod(&sock, 0o600)?;+ Ok(Listener(listener))+ }++ /// The first instance of the pipe, so nobody else holds its name.+ #[cfg(windows)]+ pub fn bind() -> Result<Self> {+ Ok(Listener(pipe(true).with_context(|| format!("creating {}", paths::socket().display()))?))+ }++ #[cfg(unix)]+ pub async fn accept(&mut self) -> io::Result<Accepted> {+ Ok(self.0.accept().await?.0)+ }++ /// Each client gets an instance of its own: once one connects, the next waits for whoever comes after.+ #[cfg(windows)]+ pub async fn accept(&mut self) -> io::Result<Accepted> {+ loop {+ let connected = self.0.connect().await;+ let this = std::mem::replace(&mut self.0, pipe(false)?);+ // One that left before we got to it is dropped.+ if connected.is_ok() {+ return Ok(this);+ }+ }+ }+}++#[cfg(windows)]+fn pipe(first: bool) -> io::Result<Accepted> {+ tokio::net::windows::named_pipe::ServerOptions::new().first_pipe_instance(first).create(paths::socket())+}diff --git a/src/main.rs b/src/main.rsindex ef8df88..02a4742 100644--- a/src/main.rs+++ b/src/main.rs@@ -7,6 +7,7 @@ mod doing;mod git;mod hook;mod invite;+mod ipc;mod mcp;mod net;mod paths;@@ -32,8 +33,26 @@ pub const SITE_URL: &str = match option_env!("TINCAN_SITE_URL") {_ => "https://larstalian.github.io/tincan",};-pub fn install_url() -> String {- format!("{SITE_URL}/install.sh")+/// The one line that installs tincan and runs `tincan <args>`: for macOS and Linux, and for Windows.+pub fn install_lines(args: &str) -> [String; 2] {+ [+ format!("curl -fsSL {SITE_URL}/install.sh | sh -s -- {args}"),+ format!("powershell -c \"& ([scriptblock]::Create((irm {SITE_URL}/install.ps1))) {args}\""),+ ]+}++/// The install script, run without questions, installing into `dir`.+pub fn installer(dir: &std::path::Path) -> std::process::Command {+ let mut cmd;+ if cfg!(windows) {+ cmd = std::process::Command::new("powershell");+ cmd.args(["-NoProfile", "-NonInteractive", "-Command", &format!("irm {SITE_URL}/install.ps1 | iex")]);+ } else {+ cmd = std::process::Command::new("sh");+ cmd.arg("-c").arg(format!("curl -fsSL {SITE_URL}/install.sh | sh"));+ }+ cmd.env("TINCAN_BIN_DIR", dir).env("TINCAN_NO_PROMPT", "1");+ cmd}/// The team link: a page showing the one command that installs tincan and joins with `ticket`.@@ -180,7 +199,7 @@ enum Cmd {},/// Run the daemon in the foreground (normally started on demand or by the service)Daemon {- /// Wait for a running daemon to exit instead of quitting (for service managers)+ /// Wait for a running daemon to exit instead of quitting (for service managers, and Windows' logon entry)#[arg(long)]service: bool,},@@ -261,6 +280,7 @@ fn default_person(p: Option<String>) -> String {async fn cli(cmd: Cmd) -> Result<()> {// Like other command-line tools, stop quietly when whatever reads our output goes away. (`listen` marks// messages read only after printing them, so nothing is lost.)+ #[cfg(unix)]unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) };let link = Link::new(None);match cmd {@@ -363,8 +383,9 @@ async fn cli(cmd: Cmd) -> Result<()> {let i: InviteInfo = link.call(Request::Invite { me, hours: hours.clamp(1, 24 * 30) }).await?;let who = if me { "another machine of yours" } else { "a teammate" };println!("Invite code for {who}: {}\n", i.code);- println!("They run this, which installs tincan and joins the team:\n");- println!(" curl -fsSL {} | sh -s -- {}\n", install_url(), i.code);+ let [unix, windows] = install_lines(&i.code);+ println!("They run this, which installs tincan and joins the team (the second line on Windows):\n");+ println!(" {unix}\n {windows}\n");println!("(or `tincan join {}` if they have tincan). Works once, within {}h, while this machine is online.", i.code, i.hours);println!("If this machine will be offline, use the long form instead: tincan join {}", i.ticket);if me {@@ -430,13 +451,8 @@ async fn cli(cmd: Cmd) -> Result<()> {Cmd::Setup { dry_run, remove, no_service } => setup::run(dry_run, remove, no_service).await?,Cmd::Doctor => setup::doctor().await?,Cmd::Upgrade => {- let dir = util::current_exe()?.parent().map(|d| d.display().to_string()).unwrap_or_default();- let status = std::process::Command::new("sh")- .arg("-c")- .arg(format!("curl -fsSL {} | sh", install_url()))- .env("TINCAN_BIN_DIR", dir)- .env("TINCAN_NO_PROMPT", "1")- .status()?;+ let dir = util::current_exe()?.parent().map(|d| d.to_path_buf()).unwrap_or_default();+ let status = installer(&dir).status()?;if !status.success() {bail!("upgrade failed");}@@ -472,7 +488,7 @@ async fn wait_exit(pid: Option<u32>) {/// Asks a running daemon to exit and waits until it has. False if none was running.pub async fn stop_daemon() -> bool {- if tokio::net::UnixStream::connect(paths::socket()).await.is_err() {+ if ipc::connect().await.is_err() {return false;}let pid = daemon_pid();diff --git a/src/paths.rs b/src/paths.rsindex 31e9a5e..7ef61ca 100644--- a/src/paths.rs+++ b/src/paths.rs@@ -1,9 +1,10 @@//! Where tincan keeps its state. `TINCAN_HOME` overrides `~/.tincan` (handy for running two "machines" side by side).+//! On Windows, `~` is the profile folder.-use std::path::PathBuf;+use std::path::{Path, PathBuf};pub fn user_home() -> PathBuf {- std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"))+ std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"))}pub fn home() -> PathBuf {@@ -12,23 +13,33 @@ pub fn home() -> PathBuf {/// `~/.tincan/tincan.sock`, unless that is too long for a Unix socket address (104 bytes on macOS): then a short/// path in a private `/tmp/tincan-<uid>` directory, derived from the home directory so every client agrees on it.+#[cfg(unix)]pub fn socket() -> PathBuf {let path = home().join("tincan.sock");if path.as_os_str().len() < 100 {return path;}- // FNV-1a: stable across builds, unlike `DefaultHasher`.- let hash = path.as_os_str().as_encoded_bytes().iter().fold(0xcbf29ce484222325u64, |h, &b| {- (h ^ b as u64).wrapping_mul(0x100000001b3)- });- short_dir().join(format!("{hash:016x}.sock"))+ short_dir().join(format!("{:016x}.sock", hash(&path)))}+/// A named pipe, named for the home directory so every client agrees on it.+#[cfg(windows)]+pub fn socket() -> PathBuf {+ PathBuf::from(format!(r"\\.\pipe\tincan-{:016x}", hash(&home())))+}++/// FNV-1a: stable across builds, unlike `DefaultHasher`.+fn hash(path: &Path) -> u64 {+ path.as_os_str().as_encoded_bytes().iter().fold(0xcbf29ce484222325u64, |h, &b| (h ^ b as u64).wrapping_mul(0x100000001b3))+}++#[cfg(unix)]fn short_dir() -> PathBuf {PathBuf::from(format!("/tmp/tincan-{}", unsafe { libc::getuid() }))}/// Makes sure the socket's directory exists and that nobody else can get at it.+#[cfg(unix)]pub fn ensure_socket_dir() -> std::io::Result<()> {use std::os::unix::fs::{DirBuilderExt, MetadataExt};let dir = socket().parent().map(PathBuf::from).unwrap_or_else(home);@@ -69,7 +80,10 @@ pub fn claude_sessions() -> PathBuf {claude_dir().join("sessions")}+/// Only for you: mode 0700 (on Windows, the profile folder already is).pub fn ensure_home() -> std::io::Result<()> {- use std::os::unix::fs::DirBuilderExt;- std::fs::DirBuilder::new().recursive(true).mode(0o700).create(home())+ let mut dir = std::fs::DirBuilder::new();+ #[cfg(unix)]+ std::os::unix::fs::DirBuilderExt::mode(&mut dir, 0o700);+ dir.recursive(true).create(home())}diff --git a/src/render.rs b/src/render.rsindex d467942..420eb70 100644--- a/src/render.rs+++ b/src/render.rs@@ -10,11 +10,18 @@ pub struct Paint(bool);impl Paint {pub const PLAIN: Paint = Paint(false);+ #[cfg(unix)]pub fn terminal() -> Paint {use std::io::IsTerminal;Paint(std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none())}+ /// The same, after asking the console to take colour codes (Windows 10's doesn't until asked).+ #[cfg(windows)]+ pub fn terminal() -> Paint {+ Paint(console::colors_enabled())+ }+fn on(self, style: &str, text: &str) -> String {if self.0 && !text.trim().is_empty() { format!("\x1b[{style}m{text}\x1b[0m") } else { text.to_string() }}@@ -255,7 +262,8 @@ fn place(s: &SessionInfo) -> String {(Some(r), Some(b)) => format!("{r}@{b}"),(Some(r), None) => r.clone(),_ if s.cwd.chars().count() > 32 => {- let parts: Vec<&str> = s.cwd.rsplit('/').filter(|p| !p.is_empty()).take(2).collect();+ // Either separator: the session may be on Windows.+ let parts: Vec<&str> = s.cwd.rsplit(['/', '\\']).filter(|p| !p.is_empty()).take(2).collect();format!("…/{}", parts.into_iter().rev().collect::<Vec<_>>().join("/"))}_ => s.cwd.clone(),diff --git a/src/setup.rs b/src/setup.rsindex d6c58e2..b904c2e 100644--- a/src/setup.rs+++ b/src/setup.rs@@ -27,13 +27,27 @@ struct Report {}pub fn exe() -> Result<PathBuf> {- Ok(crate::util::current_exe()?.canonicalize()?)+ let exe = crate::util::current_exe()?;+ // Windows reports it in full already; its canonical form (`\\?\C:\…`) is not for other programs' configs.+ if cfg!(windows) {+ return Ok(exe);+ }+ Ok(exe.canonicalize()?)}-/// The command line agents run through a shell: `'/path/to/tincan' hook codex stop`.+/// The command line agents run through a shell: `'/path/to/tincan' hook codex stop`. On Windows that shell is+/// PowerShell (`& 'C:\Users\Alex Smith\…\tincan.exe' hook codex stop`), and a path that needs no quotes also runs in+/// cmd.exe.fn shell_cmd(exe: &Path, args: &str) -> String {let p = exe.display().to_string();- let quoted = if p.chars().all(|c| c.is_ascii_alphanumeric() || "/._-".contains(c)) { p } else { format!("'{}'", p.replace('\'', "'\\''")) };+ let plain = |extra: &str| p.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c));+ let quoted = if cfg!(windows) {+ if plain(r"\:._-") { p.clone() } else { format!("& '{}'", p.replace('\'', "''")) }+ } else if plain("/._-") {+ p.clone()+ } else {+ format!("'{}'", p.replace('\'', "'\\''"))+ };format!("{quoted} {args}")}@@ -50,11 +64,11 @@ fn gemini_home() -> PathBuf {}fn opencode_home() -> PathBuf {- home().join(".config/opencode")+ home().join(".config").join("opencode")}fn pi_home() -> PathBuf {- std::env::var_os("PI_CODING_AGENT_DIR").map(PathBuf::from).unwrap_or_else(|| home().join(".pi/agent"))+ std::env::var_os("PI_CODING_AGENT_DIR").map(PathBuf::from).unwrap_or_else(|| home().join(".pi").join("agent"))}fn read_json(path: &Path) -> Result<Value> {@@ -354,7 +368,7 @@ fn copilot(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {}r.lines.push(changed(&mcp_path, write_json(&mcp_path, &v, dry)?));- let hooks_path = dir.join("hooks/tincan.json");+ let hooks_path = dir.join("hooks").join("tincan.json");if remove {if hooks_path.exists() {if !dry {@@ -363,7 +377,8 @@ fn copilot(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {r.lines.push(format!("removed {}", crate::util::tilde(&hooks_path.display().to_string())));}} else {- let entry = |event: &str| json!([{ "type": "command", "bash": shell_cmd(exe, &format!("hook copilot {event}")), "timeoutSec": 10 }]);+ let shell = if cfg!(windows) { "powershell" } else { "bash" };+ let entry = |event: &str| json!([{ "type": "command", shell: shell_cmd(exe, &format!("hook copilot {event}")), "timeoutSec": 10 }]);let v = json!({ "version": 1, "hooks": {"sessionStart": entry("session-start"),"userPromptSubmitted": entry("user-prompt-submit"),@@ -403,7 +418,7 @@ fn opencode(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {}r.lines.push(changed(&path, write_json(&path, &v, dry)?));}- let plugin = dir.join("plugins/tincan.ts");+ let plugin = dir.join("plugins").join("tincan.ts");if remove {if plugin.exists() {if !dry {@@ -427,7 +442,7 @@ fn pi(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {return Ok(None);}let mut r = Report { agent: "pi", lines: Vec::new(), notes: Vec::new() };- let ext = pi_home().join("extensions/tincan.ts");+ let ext = pi_home().join("extensions").join("tincan.ts");if remove {if ext.exists() {if !dry {@@ -466,12 +481,14 @@ fn reason(_exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {// ---- background service ----+#[cfg(unix)]pub fn service_installed() -> bool {service_path().exists()}/// Asks the service manager to start the daemon now (rather than a stray one of our own, which would hold the/// lock and leave the service's daemon waiting, without its menu bar icon). True if it accepted.+#[cfg(unix)]pub fn start_service() -> bool {let out = if cfg!(target_os = "macos") {let uid = unsafe { libc::getuid() };@@ -482,6 +499,7 @@ pub fn start_service() -> bool {out.is_ok_and(|o| o.status.success())}+#[cfg(unix)]fn service_path() -> PathBuf {if cfg!(target_os = "macos") {home().join(format!("Library/LaunchAgents/{}.plist", service_name()))@@ -491,11 +509,13 @@ fn service_path() -> PathBuf {}/// A PATH for the daemon that includes where agents usually live (it runs `codex queue`).+#[cfg(unix)]fn service_path_env() -> String {let h = home().display().to_string();format!("{h}/.local/bin:{h}/.bun/bin:{h}/.npm-global/bin:{h}/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin")}+#[cfg(unix)]async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {let path = service_path();let uid = unsafe { libc::getuid() };@@ -587,10 +607,66 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {}}+#[cfg(unix)]fn xml(s: &str) -> String {s.replace('&', "&").replace('<', "<").replace('>', ">")}+// Without admin, Windows has no service for us: the daemon starts at logon from the user's Run key, and when it+// restarts it starts the next one itself (see `Daemon::restart_soon`).++#[cfg(windows)]+const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";++#[cfg(windows)]+pub fn service_installed() -> bool {+ run_entry().is_some()+}++/// There is no service manager to ask: the caller starts the daemon.+#[cfg(windows)]+pub fn start_service() -> bool {+ false+}++/// Our Run entry, as `reg query` shows it.+#[cfg(windows)]+fn run_entry() -> Option<String> {+ let out = Command::new("reg").args(["query", RUN_KEY, "/v", &service_name()]).stdin(std::process::Stdio::null()).output().ok()?;+ out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())+}++#[cfg(windows)]+async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {+ let reg = |args: &[&str]| Command::new("reg").args(args).stdin(std::process::Stdio::null()).output();+ if remove {+ if !dry {+ let _ = reg(&["delete", RUN_KEY, "/v", &service_name(), "/f"]);+ crate::stop_daemon().await;+ }+ return Ok("removed the login service".into());+ }+ // Windows starts it with its command line and nothing else.+ if std::env::var_os("TINCAN_HOME").is_some() {+ return Err(anyhow!("a logon entry can't set TINCAN_HOME"));+ }+ let command = format!("\"{}\" daemon --service", exe.display());+ let did = !run_entry().is_some_and(|v| v.contains(&command));+ if !dry {+ if did {+ let out = reg(&["add", RUN_KEY, "/v", &service_name(), "/d", &command, "/f"])?;+ if !out.status.success() {+ return Err(anyhow!("reg add: {}", String::from_utf8_lossy(&out.stderr).trim()));+ }+ }+ // Running now, as from logon: a daemon that is running starts it as it stops.+ if !crate::stop_daemon().await {+ crate::client::start_daemon(true)?;+ }+ }+ Ok(if did { "installed the login service (Run key)".into() } else { "login service already set".into() })+}+type AgentFn = fn(&Path, bool, bool) -> Result<Option<Report>>;struct Agent {@@ -607,8 +683,10 @@ fn has(path: PathBuf, needle: &str) -> bool {std::fs::read_to_string(path).is_ok_and(|s| s.contains(needle))}+/// Our path as a JSON config has it (with Windows' backslashes escaped).fn me(exe: &Path) -> String {- exe.display().to_string()+ let s = json!(exe.display().to_string()).to_string();+ s[1..s.len() - 1].to_string()}const AGENTS: [Agent; 8] = [@@ -628,7 +706,8 @@ const AGENTS: [Agent; 8] = [name: "Codex",hint: "instant; asks once to trust the hooks",installed: || agent::find_bin("codex").is_some() || codex_home().exists(),- wired: |exe| has(codex_home().join("config.toml"), &me(exe)) && has(codex_home().join("hooks.json"), "hook codex"),+ // TOML keeps a Windows path as it is ('C:\…').+ wired: |exe| has(codex_home().join("config.toml"), &exe.display().to_string()) && has(codex_home().join("hooks.json"), "hook codex"),apply: codex,},Agent {@@ -792,11 +871,11 @@ pub async fn doctor() -> Result<()> {}Err(e) => println!("✗ daemon: {e:#}"),}- let svc = service_path();+ let svc = service_installed();println!("{} login service: {}",- if svc.exists() { "✓" } else { "-" },- if svc.exists() { "installed" } else { "not installed (`tincan setup`)" }+ if svc { "✓" } else { "-" },+ if svc { "installed" } else { "not installed (`tincan setup`)" });for f in detect(&exe) {if f.wired {@@ -829,8 +908,17 @@ mod tests {}#[test]+ #[cfg(unix)]fn quoting() {assert_eq!(shell_cmd(Path::new("/usr/local/bin/tincan"), "mcp"), "/usr/local/bin/tincan mcp");assert_eq!(shell_cmd(Path::new("/Users/a b/tincan"), "mcp"), "'/Users/a b/tincan' mcp");}++ #[test]+ #[cfg(windows)]+ fn quoting() {+ assert_eq!(shell_cmd(Path::new(r"C:\Users\alex\.local\bin\tincan.exe"), "mcp"), r"C:\Users\alex\.local\bin\tincan.exe mcp");+ assert_eq!(shell_cmd(Path::new(r"C:\Users\Alex O'Neil\tincan.exe"), "mcp"), r"& 'C:\Users\Alex O''Neil\tincan.exe' mcp");+ assert_eq!(me(Path::new(r"C:\a\tincan.exe")), r"C:\\a\\tincan.exe");+ }}diff --git a/src/util.rs b/src/util.rsindex 9b6d968..c508a4a 100644--- a/src/util.rs+++ b/src/util.rs@@ -1,4 +1,4 @@-use std::{fs::File, os::fd::AsRawFd, path::Path};+use std::{fs::File, path::Path};pub fn now_ms() -> i64 {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64)@@ -9,28 +9,96 @@ pub fn hostname() -> String {if let Some(name) = std::env::var("TINCAN_MACHINE").ok().map(|n| slug(&n)).filter(|n| !n.is_empty()) {return name;}+ let raw = system_hostname();+ let short = raw.split('.').next().unwrap_or_default();+ let s = slug(short);+ if s.is_empty() { "machine".into() } else { s }+}++#[cfg(unix)]+fn system_hostname() -> String {let mut buf = [0u8; 256];let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) };- let raw = if rc == 0 {+ if rc == 0 {let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());String::from_utf8_lossy(&buf[..end]).into_owned()} else {String::new()- };- let short = raw.split('.').next().unwrap_or_default();- let s = slug(short);- if s.is_empty() { "machine".into() } else { s }+ }+}++#[cfg(windows)]+fn system_hostname() -> String {+ std::env::var("COMPUTERNAME").unwrap_or_default()}+#[cfg(unix)]pub fn pid_alive(pid: u32) -> bool {let rc = unsafe { libc::kill(pid as libc::pid_t, 0) };rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)}+#[cfg(windows)]+pub fn pid_alive(pid: u32) -> bool {+ use windows_sys::Win32::{Foundation::*, System::Threading::*};+ // SAFETY: a handle we open, look at without waiting, and close.+ unsafe {+ let h = OpenProcess(PROCESS_SYNCHRONIZE, 0, pid);+ if h.is_null() {+ return GetLastError() == ERROR_ACCESS_DENIED;+ }+ let alive = WaitForSingleObject(h, 0) == WAIT_TIMEOUT;+ CloseHandle(h);+ alive+ }+}++#[cfg(unix)]pub fn parent_pid() -> u32 {unsafe { libc::getppid() as u32 }}+#[cfg(windows)]+pub fn parent_pid() -> u32 {+ process(std::process::id()).map_or(0, |(ppid, _)| ppid)+}++/// A running process's parent and program name (`zsh`, `cmd`).+#[cfg(unix)]+pub fn process(pid: u32) -> Option<(u32, String)> {+ let out = std::process::Command::new("ps").args(["-o", "ppid=,comm=", "-p", &pid.to_string()]).output().ok()?;+ let line = String::from_utf8_lossy(&out.stdout).trim().to_string();+ let (ppid, comm) = line.split_once(' ')?;+ let name = comm.trim().rsplit('/').next().unwrap_or_default().trim_start_matches('-');+ Some((ppid.trim().parse().ok()?, name.to_string()))+}++#[cfg(windows)]+pub fn process(pid: u32) -> Option<(u32, String)> {+ use windows_sys::Win32::{Foundation::*, System::Diagnostics::ToolHelp::*};+ // SAFETY: walks a snapshot we take and close; the entry is sized as the API asks.+ unsafe {+ let snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);+ if snap == INVALID_HANDLE_VALUE {+ return None;+ }+ let mut e: PROCESSENTRY32W = std::mem::zeroed();+ e.dwSize = size_of::<PROCESSENTRY32W>() as u32;+ let mut found = None;+ let mut more = Process32FirstW(snap, &mut e) != 0;+ while more && found.is_none() {+ if e.th32ProcessID == pid {+ let exe = &e.szExeFile[..e.szExeFile.iter().position(|&c| c == 0).unwrap_or(e.szExeFile.len())];+ let name = String::from_utf16_lossy(exe).to_lowercase();+ found = Some((e.th32ParentProcessID, name.strip_suffix(".exe").unwrap_or(&name).to_string()));+ }+ more = Process32NextW(snap, &mut e) != 0;+ }+ CloseHandle(snap);+ found+ }+}+/// Lowercase letters, digits and single dashes: a name that is safe in an address.pub fn slug(s: &str) -> String {let mut out = String::new();@@ -59,7 +127,7 @@ pub fn tilde(path: &str) -> String {let home = crate::paths::user_home();match Path::new(path).strip_prefix(&home) {Ok(rest) if rest.as_os_str().is_empty() => "~".into(),- Ok(rest) => format!("~/{}", rest.display()),+ Ok(rest) => format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()),Err(_) => path.into(),}}@@ -68,7 +136,16 @@ pub fn tilde(path: &str) -> String {/// someone else holds it.pub fn lock(path: &Path, wait: bool) -> std::io::Result<Option<File>> {use std::io::Write;- let mut f = File::options().create(true).truncate(false).write(true).open(path)?;+ let Some(mut f) = acquire(path, wait)? else { return Ok(None) };+ f.set_len(0)?;+ write!(f, "{}", std::process::id())?;+ Ok(Some(f))+}++#[cfg(unix)]+fn acquire(path: &Path, wait: bool) -> std::io::Result<Option<File>> {+ use std::os::fd::AsRawFd;+ let f = File::options().create(true).truncate(false).write(true).open(path)?;let flags = if wait { libc::LOCK_EX } else { libc::LOCK_EX | libc::LOCK_NB };// A client checking whether a daemon runs holds the lock for an instant: try again before giving up.let mut tries = 0;@@ -79,11 +156,52 @@ pub fn lock(path: &Path, wait: bool) -> std::io::Result<Option<File>> {}std::thread::sleep(std::time::Duration::from_millis(20));}- f.set_len(0)?;- write!(f, "{}", std::process::id())?;Ok(Some(f))}+/// On Windows the lock is the open file itself, shared only for reading: until we exit, nobody else can open it to+/// write (another daemon, or `locked`), and anyone can read our pid. `wait` waits for the daemon that has it now,+/// then gives up if another got there first, so daemons waiting to take over can't pile up.+#[cfg(windows)]+fn acquire(path: &Path, wait: bool) -> std::io::Result<Option<File>> {+ use std::os::windows::fs::OpenOptionsExt;+ use windows_sys::Win32::{Foundation::ERROR_SHARING_VIOLATION, Storage::FileSystem::FILE_SHARE_READ};+ if wait && locked(path) {+ let pid = std::fs::read_to_string(path).ok().and_then(|s| s.trim().parse().ok());+ while pid.is_some_and(pid_alive) {+ std::thread::sleep(std::time::Duration::from_millis(100));+ }+ }+ // As above, a client's check holds it for an instant.+ let mut tries = 0;+ loop {+ match File::options().create(true).truncate(false).write(true).share_mode(FILE_SHARE_READ).open(path) {+ Err(e) if e.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32) => {}+ r => return r.map(Some),+ }+ tries += 1;+ if tries == 3 {+ return Ok(None);+ }+ std::thread::sleep(std::time::Duration::from_millis(20));+ }+}++/// Whether someone holds the lock at `path`.+#[cfg(unix)]+pub fn locked(path: &Path) -> bool {+ use std::os::fd::AsRawFd;+ let Ok(f) = File::open(path) else { return false };+ unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) != 0 }+}++#[cfg(windows)]+pub fn locked(path: &Path) -> bool {+ let held = windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION as i32;+ File::options().write(true).open(path).is_err_and(|e| e.raw_os_error() == Some(held))+}++#[cfg(unix)]pub fn chmod(path: &Path, mode: u32) -> std::io::Result<()> {use std::os::unix::fs::PermissionsExt;std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))@@ -102,7 +220,7 @@ pub fn printable(s: &str) -> String {}/// This program's path. After an update replaces the file, Linux reports the old one as `<path> (deleted)`; the-/// new binary is at `<path>`.+/// new binary is at `<path>`. (Windows, where the update moves the old one aside, reports `<path>` as it was.)pub fn current_exe() -> std::io::Result<std::path::PathBuf> {let exe = std::env::current_exe()?;Ok(exe.to_str().and_then(|s| s.strip_suffix(" (deleted)")).map(std::path::PathBuf::from).unwrap_or(exe))diff --git a/src/wizard.rs b/src/wizard.rsindex b0c1f76..e8bfb77 100644--- a/src/wizard.rs+++ b/src/wizard.rs@@ -4,7 +4,7 @@use crate::{client::Link,config::{Config, Policy},- install_url, invite,+ install_lines, invite,proto::*,render, setup, util,};@@ -225,14 +225,12 @@ pub async fn show_link(new: bool) -> Result<String> {pub async fn show_code(me: bool) -> Result<()> {let i: InviteInfo = Link::new(None).call(Request::Invite { me, hours: 24 }).await?;let who = if me { "your other machine" } else { "your teammate" };+ let [unix, windows] = install_lines(&i.code);note(format!("Invite code: {}", i.code),format!(- "On {who}: curl -fsSL {} | sh -s -- {}\n(or `tincan join {}` if tincan is there already)\nWorks once, within {}h, while this machine is online.",- install_url(),- i.code,- i.code,- i.hours+ "On {who}: {unix}\n(on Windows: {windows})\n(or `tincan join {}` if tincan is there already)\nWorks once, within {}h, while this machine is online.",+ i.code, i.hours),)?;Ok(())@@ -241,7 +239,8 @@ pub async fn show_code(me: bool) -> Result<()> {/// Puts text on the clipboard, if there's a clipboard tool. True if it worked.pub fn copy(text: &str) -> bool {use std::io::Write;- let tools: [(&str, &[&str]); 3] = [("pbcopy", &[]), ("wl-copy", &[]), ("xclip", &["-selection", "clipboard"])];+ let tools: &[(&str, &[&str])] =+ if cfg!(windows) { &[("clip", &[])] } else { &[("pbcopy", &[]), ("wl-copy", &[]), ("xclip", &["-selection", "clipboard"])] };tools.iter().any(|(bin, args)| {let Ok(mut child) = std::process::Command::new(bin).args(*args)