From d1e82f7f193939f0945cfe8fb5750660c58c3a26 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:04:56 +0000 Subject: [PATCH 1/5] Uninstall and reinstall without losing or leaving anything --- bin/ghost | 4 +- bin/ghost-login | 4 +- bin/ghost-uninstall | 35 ++++++-- bin/ghost-update | 3 +- bin/windows/ghost-uninstall.ps1 | 17 +++- install.ps1 | 47 +++++++--- install.sh | 119 ++++++++++++++++++------ privacy/bridge.py | 10 ++- privacy/doctor.py | 2 +- privacy/ghost_auth.py | 14 +++ privacy/ghost_login.py | 33 ++++--- privacy/launch.py | 29 +++++- scripts/fill.py | 22 +++++ scripts/fork-engine.ps1 | 3 +- scripts/fork-engine.sh | 29 ++++-- systemd/ghost-bridge.service | 4 +- tests/fake_dreamfort.py | 13 ++- tests/test_bridge.py | 8 +- tests/test_fork_engine.py | 33 +++++++ tests/test_install.py | 154 ++++++++++++++++++++++++++++---- tests/test_launch.py | 65 ++++++++++---- tests/test_login.py | 5 +- 22 files changed, 533 insertions(+), 120 deletions(-) create mode 100644 scripts/fill.py diff --git a/bin/ghost b/bin/ghost index f98ec7d..25429ec 100755 --- a/bin/ghost +++ b/bin/ghost @@ -1,9 +1,9 @@ #!/bin/sh # ghost -- the command. privacy/launch.py does the work; `update` and `uninstall` don't go through it # because they replace or remove the very Python it runs on. -export GHOST_HOME="__GHOST_HOME__" GHOST_ENGINE="__ENG__" +export GHOST_HOME=__GHOST_HOME__ GHOST_ENGINE=__ENG__ case "${1:-}" in update) shift; exec "$HOME/.local/bin/ghost-update" "$@" ;; uninstall) shift; exec "$HOME/.local/bin/ghost-uninstall" "$@" ;; esac -exec "__PYTHON__" -Es "$GHOST_HOME/privacy/launch.py" "$@" +exec __PYTHON__ -Es "$GHOST_HOME/privacy/launch.py" "$@" diff --git a/bin/ghost-login b/bin/ghost-login index bb94a24..fda11bc 100755 --- a/bin/ghost-login +++ b/bin/ghost-login @@ -1,4 +1,4 @@ #!/bin/sh # ghost-login -- connect ghost to DreamFort, with your account or an API key (ghost-login --help). -export GHOST_HOME="__GHOST_HOME__" GHOST_ENGINE="__ENG__" -exec "__PYTHON__" -Es "$GHOST_HOME/privacy/ghost_login.py" "$@" +export GHOST_HOME=__GHOST_HOME__ GHOST_ENGINE=__ENG__ +exec __PYTHON__ -Es "$GHOST_HOME/privacy/ghost_login.py" "$@" diff --git a/bin/ghost-uninstall b/bin/ghost-uninstall index 3692f07..5f5e0d0 100644 --- a/bin/ghost-uninstall +++ b/bin/ghost-uninstall @@ -6,8 +6,8 @@ # ghost uninstall --purge delete your data too set -uo pipefail -GHOST_HOME="__GHOST_HOME__" -ENG="__ENG__" +GHOST_HOME=__GHOST_HOME__ +ENG=__ENG__ BIN="$HOME/.local/bin" SRC="$(cat "$GHOST_HOME/.src" 2>/dev/null || true)" @@ -39,6 +39,13 @@ if ! ours_home "$GHOST_HOME"; then exit 0 fi +open="$( (ps axww -o pid=,command= 2>/dev/null || true) | awk -v e="$ENG" \ + '(index($0, e "/") || index($0, e "\047")) && !/gateway run|process_supervisor/ { print $1 }')" +if [ -n "$open" ] && [ -z "${GHOST_FORCE:-}" ]; then + echo "ghost is open (pid $(echo $open)). Close those windows and run this again." >&2 + exit 1 +fi + echo "This removes ghost: its engine ($ENG), background services and commands." if [ -z "$YES" ]; then ask "Remove ghost?" || { echo "Nothing was changed."; exit 0; } @@ -69,8 +76,12 @@ else systemctl --user daemon-reload >/dev/null 2>&1 fi # One `ghost` started itself, where there is no service manager. -pid="$(curl -s -D - -o /dev/null --max-time 2 http://127.0.0.1:8788/healthz | tr -d '\r' | sed -n 's/^X-Ghost-Pid: //p')" -[ -z "$pid" ] || kill "$pid" 2>/dev/null +pid="$(curl -s -D - -o /dev/null --max-time 2 http://127.0.0.1:8788/healthz | tr -d '\r' | sed -n 's/^X-Ghost-Pid: \([0-9]*\)$/\1/p')" +if [ -n "$pid" ]; then + case "$(ps -ww -o command= -p "$pid" 2>/dev/null || tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null)" in + *"$GHOST_HOME/privacy/"*) kill "$pid" 2>/dev/null ;; + esac +fi echo "Removing files" for dir in "$ENG" "$ENG.old" "$ENG.new"; do @@ -79,8 +90,15 @@ for dir in "$ENG" "$ENG.old" "$ENG.new"; do fi done for name in ghost ghost-login ghost-update; do - if grep -qsF "$GHOST_HOME" "$BIN/$name"; then rm -f "$BIN/$name"; fi + if grep -qs GHOST_HOME "$BIN/$name"; then rm -f "$BIN/$name"; fi +done +if [ -e "$BIN/ghost.other" ] && [ ! -e "$BIN/ghost" ]; then mv "$BIN/ghost.other" "$BIN/ghost"; fi # what had the name before +for rc in "${ZDOTDIR:-$HOME}/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.bash_login" "$HOME/.profile"; do + if grep -qs '\.local/bin.* # ghost$' "$rc"; then # the line the installer put there + rest="$(grep -v '\.local/bin.* # ghost$' "$rc")"; printf '%s\n' "$rest" > "$rc" + fi done +rm -f "${XDG_CONFIG_HOME:-$HOME/.config}/fish/conf.d/ghost.fish" if [ "$SRC" = "$HOME/.ghost-src" ] && [ -d "$SRC/.git" ]; then if [ -z "$(git -C "$SRC" status --porcelain 2>/dev/null)" ]; then rm -rf "$SRC"; else echo " left $SRC (it has changes of yours)"; fi fi @@ -89,8 +107,9 @@ if [ -n "$PURGE" ]; then rm -rf "$GHOST_HOME" echo "ghost and all of its data are gone." else - for dir in venv tools installs cache privacy; do rm -rf "${GHOST_HOME:?}/$dir"; done - rm -f "$GHOST_HOME/.src" "$GHOST_HOME/.install-env" "$GHOST_HOME/install.log" - echo "ghost is gone. Your chats, skills and settings are still in $GHOST_HOME (delete it to remove them too)." + for dir in venv tools installs cache python uv privacy/__pycache__; do rm -rf "${GHOST_HOME:?}/$dir"; done + rm -f "$GHOST_HOME/.src" "$GHOST_HOME/.install-env" "$GHOST_HOME/install.log" "$GHOST_HOME"/privacy/*.py \ + "$GHOST_HOME/privacy/uncensored_prefill.json" "$GHOST_HOME/privacy/bridge.key" "$GHOST_HOME"/privacy/bridge.log* + echo "ghost is gone. Your chats, skills, settings and login are still in $GHOST_HOME (delete it to remove them too)." fi rm -f "$BIN/ghost-uninstall" diff --git a/bin/ghost-update b/bin/ghost-update index c6c27f0..25cb6c3 100644 --- a/bin/ghost-update +++ b/bin/ghost-update @@ -4,8 +4,7 @@ # The Hermes release the engine is built on is pinned in the source (engine.pin), so a newer engine arrives # here too, once ghost's patches have been checked against it. set -e -GHOST_HOME="__GHOST_HOME__" -export GHOST_HOME GHOST_ENGINE="__ENG__" +export GHOST_HOME=__GHOST_HOME__ GHOST_ENGINE=__ENG__ # The source you installed from, or ghost's own copy. SRC="$(cat "$GHOST_HOME/.src" 2>/dev/null || true)" diff --git a/bin/windows/ghost-uninstall.ps1 b/bin/windows/ghost-uninstall.ps1 index 095b374..8dee2a7 100644 --- a/bin/windows/ghost-uninstall.ps1 +++ b/bin/windows/ghost-uninstall.ps1 @@ -21,6 +21,13 @@ function Test-OurEngine($dir) { } if (-not ((Test-Path "$GhostHome\.src") -and (Test-Path "$GhostHome\privacy"))) { Write-Host "ghost isn't installed here ($GhostHome)."; exit 0 } +$open = @(Get-CimInstance Win32_Process | Where-Object { + $_.ProcessId -ne $PID -and $_.CommandLine -and $_.Name -match '^(python|hermes)' -and $_.CommandLine -notmatch 'gateway run' -and + ($_.CommandLine.Contains("$Eng\") -or $_.CommandLine.Contains($Eng.Replace('\', '\\'))) }) +if ($open.Count -and -not $env:GHOST_FORCE) { + Write-Host "ghost is open (pid $($open.ProcessId -join ', ')). Close those windows and run this again."; exit 1 +} + Write-Host "This removes ghost: its engine ($Eng), background service and commands." if (-not ($y -or $Flags -contains "--yes")) { if ((Read-Host "Remove ghost? [y/N]") -notmatch '^[Yy]') { Write-Host "Nothing was changed."; exit 0 } @@ -59,10 +66,16 @@ if ($purge) { Remove-Item -Recurse -Force $GhostHome Write-Host "ghost and all of its data are gone." } else { - foreach ($name in "venv", "tools", "installs", "cache", "privacy", ".src", ".install-env") { Remove-Item -Recurse -Force "$GhostHome\$name" } - Write-Host "ghost is gone. Your chats, skills and settings are still in $GhostHome (delete it to remove them too)." + foreach ($name in "venv", "tools", "installs", "cache", "python", "uv", "privacy\__pycache__", "privacy\*.py", "privacy\uncensored_prefill.json", + "privacy\bridge.key", "privacy\bridge.log*", ".src", ".install-env", ".installing") { Remove-Item -Recurse -Force "$GhostHome\$name" } + Write-Host "ghost is gone. Your chats, skills, settings and login are still in $GhostHome (delete it to remove them too)." } foreach ($name in "ghost.cmd", "ghost-login.cmd", "ghost-update.cmd", "ghost-update.ps1", "ghost-uninstall.cmd", "ghost-uninstall.ps1") { Remove-Item -Force "$BinDir\$name" } +if (-not (Get-ChildItem -Force $BinDir)) { # nothing else of yours in there + Remove-Item -Force $BinDir + $path = [Environment]::GetEnvironmentVariable("Path", "User") + [Environment]::SetEnvironmentVariable("Path", (($path -split ";" | Where-Object { $_ -and $_ -ne $BinDir }) -join ";"), "User") +} exit 0 diff --git a/install.ps1 b/install.ps1 index 92613b5..1289cd1 100644 --- a/install.ps1 +++ b/install.ps1 @@ -26,6 +26,10 @@ function Have($c) { [bool](Get-Command $c -ErrorAction SilentlyContinue) } function Write-Text($path, $text) { [IO.File]::WriteAllText($path, $text) } # no byte-order mark, unlike Set-Content function Check($what) { if ($LASTEXITCODE -ne 0) { throw "$what failed (exit code $LASTEXITCODE)" } } +# (what the machine is, not this PowerShell) +$arch = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -ErrorAction SilentlyContinue).PROCESSOR_ARCHITECTURE +if ($arch -eq "ARM64") { throw "ghost doesn't run on Windows on ARM yet. It does in WSL2 there (https://learn.microsoft.com/windows/wsl/install): use the Linux command." } + # Run as `irm | iex` there is no checkout: get one, and carry on from there. $Repo = if ($PSScriptRoot) { $PSScriptRoot } else { "" } if (-not $Repo -or -not (Test-Path "$Repo\profile\config.yaml")) { @@ -56,11 +60,28 @@ if ($NoBrowser) { $env:GHOST_NO_BROWSER = "1" } else { Remove-Item Env:GHOST_NO_ # --- 1. this machine ------------------------------------------------------------------------- Say "Checking this machine" +New-Item -ItemType Directory -Force -Path $GhostHome | Out-Null +try { $lock = [IO.File]::Open("$GhostHome\.installing", "OpenOrCreate", "ReadWrite", "None") } +catch { throw "ghost is already being installed or updated. Wait for that to finish." } +trap { $lock.Dispose(); break } & "$Repo\scripts\fork-engine.ps1" -Eng $Eng -GhostHome $GhostHome -Check # nothing changes under an open ghost -if (-not (Have uv)) { Invoke-RestMethod https://astral.sh/uv/install.ps1 | Invoke-Expression; $env:Path = "$BinDir;$env:Path" } -if (-not (Have uv)) { throw "couldn't install uv. Install it from https://docs.astral.sh/uv/, then run this again." } +# What ghost brings stays in its own folder: uv, the Pythons it fetches, and their cache. uv is ours, because one you +# have may be too old; it trusts the certificates the system trusts, as a company network may have one of its own. +$env:UV_CACHE_DIR = "$GhostHome\cache\uv"; $env:UV_PYTHON_INSTALL_DIR = "$GhostHome\python" +$env:UV_SYSTEM_CERTS = "1"; $env:UV_NATIVE_TLS = "1" +foreach ($v in "PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV") { Remove-Item "Env:$v" -ErrorAction SilentlyContinue } +$UvVersion = "0.13.10"; $Uv = "$GhostHome\uv\uv.exe" +if (-not ((Test-Path $Uv) -and "$(& $Uv --version)".StartsWith("uv $UvVersion"))) { + $env:UV_UNMANAGED_INSTALL = "$GhostHome\uv" + try { Invoke-RestMethod "https://astral.sh/uv/$UvVersion/install.ps1" | Invoke-Expression } catch { Write-Host " $_" } + Remove-Item Env:UV_UNMANAGED_INSTALL + if (-not (Test-Path $Uv)) { + if (-not (Have uv)) { throw "couldn't download uv, which brings ghost's Python (from astral.sh and github.com). Check your connection, then run this again." } + $Uv = "uv" + } +} if ($Local -and -not (Have ollama)) { throw "-Local needs Ollama: install it from https://ollama.com, then run this again." } -New-Item -ItemType Directory -Force -Path $GhostHome, $Priv, $BinDir | Out-Null +New-Item -ItemType Directory -Force -Path $Priv, $BinDir | Out-Null Write-Text "$GhostHome\.src" $Repo $chosen = @(); if ($Local) { $chosen += "GHOST_LOCAL=1" }; if ($NoBrowser) { $chosen += "GHOST_NO_BROWSER=1" } Write-Text "$GhostHome\.install-env" (($chosen | ForEach-Object { "$_`n" }) -join "") @@ -77,11 +98,7 @@ foreach ($task in "ghost-scrubber", "ghost-veil") { Unregister-ScheduledTask -Ta $env:UV_PROJECT_ENVIRONMENT = $Venv Push-Location $Repo try { - & uv sync --quiet --python 3.11 --frozen - if ($LASTEXITCODE -ne 0) { # again with the system's certificates, for a network that has one of its own - $env:UV_SYSTEM_CERTS = "1"; $env:UV_NATIVE_TLS = "1" - & uv sync --quiet --python 3.11 --frozen; Check "uv sync" - } + & $Uv sync --quiet --managed-python --python 3.11 --frozen; Check "uv sync" } finally { Pop-Location } Remove-Item Env:UV_PROJECT_ENVIRONMENT if (Test-Path "$Priv\.scrub") { # someone relied on it: say so rather than let them find out @@ -94,7 +111,7 @@ Copy-Item "$Repo\profile\uncensored_prefill.json" $Priv -Force # --- 3. the engine --------------------------------------------------------------------------- Say "Setting up the engine (a few minutes the first time)" -& powershell -ExecutionPolicy Bypass -NoProfile -File "$Repo\scripts\fork-engine.ps1" -Eng $Eng -GhostHome $GhostHome +& powershell -ExecutionPolicy Bypass -NoProfile -File "$Repo\scripts\fork-engine.ps1" -Eng $Eng -GhostHome $GhostHome -Python $Py Check "building the engine" # --- 4. the local model (-Local) ------------------------------------------------------------- @@ -136,13 +153,18 @@ try { } Register-ScheduledTask @task -Force | Out-Null } catch { Write-Host " Task Scheduler refused it ($($_.Exception.Message.Trim())), so ghost starts it when needed." } -& $Py -Es -c "import sys; sys.path.insert(0, sys.argv[1]); import launch; sys.exit(not launch.ensure_bridge())" $Priv -if ($LASTEXITCODE -ne 0) { throw "the background service didn't start. Its log is $Priv\bridge.log" } +$why = & $Py -Es -c "import sys; sys.path.insert(0, sys.argv[1]); import launch; print('' if launch.ensure_bridge() else launch.bridge_problem())" $Priv +if ("$why".Trim() -or $LASTEXITCODE -ne 0) { throw "ghost's background service isn't running: $why" } # --- 7. the commands ------------------------------------------------------------------------- Say "Installing the ghost command" foreach ($name in "ghost.cmd", "ghost-login.cmd", "ghost-update.cmd", "ghost-update.ps1", "ghost-uninstall.cmd", "ghost-uninstall.ps1") { - $text = [IO.File]::ReadAllText("$Repo\bin\windows\$name").Replace("__PYTHON__", $Py).Replace("__GHOST_HOME__", $GhostHome).Replace("__ENG__", $Eng) + # Your folder by its variable: these files are read in a code page your name may not be in. + $you = if ($name.EndsWith(".cmd")) { "%USERPROFILE%" } else { '$env:USERPROFILE' } + $text = [IO.File]::ReadAllText("$Repo\bin\windows\$name") + foreach ($path in @(("__PYTHON__", $Py), ("__GHOST_HOME__", $GhostHome), ("__ENG__", $Eng))) { + $text = $text.Replace($path[0], $path[1].Replace($env:USERPROFILE, $you)) + } Write-Text "$BinDir\$name" ($text -replace "`r?`n", "`r`n") # cmd misreads labels in files with bare newlines } & "$Repo\scripts\fork-engine.ps1" -Eng $Eng -GhostHome $GhostHome -RefreshGateway @@ -152,4 +174,5 @@ if ("$userPath" -notlike "*$BinDir*") { [Environment]::SetEnvironmentVariable("P $who = & $Py -Es "$Priv\ghost_login.py" --status if ($LASTEXITCODE -eq 0) { Say "ghost is ready. $who." } else { Say "ghost is ready. It asks you to log in the first time." } Write-Host " Open a new terminal and run: ghost" +$lock.Dispose() exit 0 diff --git a/install.sh b/install.sh index 5188f62..2406bcc 100755 --- a/install.sh +++ b/install.sh @@ -20,12 +20,16 @@ main() { Darwin|Linux) ;; *) echo "ghost runs on macOS, Linux and WSL2 (and on Windows with install.ps1). This is: $OS." >&2; exit 1 ;; esac + if [ "$(id -u)" = 0 ] && [ -n "${SUDO_USER:-}" ]; then + echo "Run this without sudo: ghost installs for you alone, and needs no administrator. (For root's own use: SUDO_USER= bash install.sh)" >&2 + exit 1 + fi # Run as `curl ... | bash` there is no checkout: get one, and carry on from there. REPO="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || true)" if [ -z "$REPO" ] || [ ! -f "$REPO/profile/config.yaml" ]; then need_git - SRC="${GHOST_SRC_DIR:-$HOME/.ghost-src}" + SRC="$HOME/.ghost-src" if [ ! -d "$SRC/.git" ]; then rm -rf "$SRC"; git clone --quiet https://github.com/OpenGradient/ghost.git "$SRC" else # always the released branch, whatever was checked out before @@ -47,7 +51,13 @@ main() { LOG="$GHOST_HOME/install.log" HERMES_VERSION=""; . "$REPO/engine.pin" LOCAL_MODEL="" NOTES=() - mkdir -p "$GHOST_HOME"; : > "$LOG" + # What ghost brings stays in its own folder: uv, the Pythons it fetches, and their cache. uv trusts the + # certificates the system trusts, as curl and git do: a company network may have one of its own. + export UV_CACHE_DIR="$GHOST_HOME/cache/uv" UV_PYTHON_INSTALL_DIR="$GHOST_HOME/python" UV_SYSTEM_CERTS=1 UV_NATIVE_TLS=1 + unset PYTHONHOME PYTHONPATH VIRTUAL_ENV + mkdir -p "$GHOST_HOME"; chmod 700 "$GHOST_HOME" + one_at_a_time + : > "$LOG" options ui @@ -74,6 +84,18 @@ options() { [ -z "$GHOST_LOCAL_32B" ] || GHOST_LOCAL=1 } +one_at_a_time() { # (two would build the engine over each other) + LOCK="$GHOST_HOME/.installing" + local pid + if ! mkdir "$LOCK" 2>/dev/null; then + pid="$(cat "$LOCK/pid" 2>/dev/null || true)" + if [ -n "$pid" ] && [ "$pid" != $$ ] && kill -0 "$pid" 2>/dev/null; then + echo "ghost is already being installed or updated (pid $pid). Wait for that to finish." >&2; exit 1 + fi # (or whoever left it there is gone) + fi + echo $$ > "$LOCK/pid" +} + remember() { # what `ghost update` and `ghost uninstall` need to know local name echo "$REPO" > "$GHOST_HOME/.src" @@ -91,7 +113,7 @@ ui() { FANCY=1 BOLD=$'\033[1m' DIM=$'\033[2m' GOLD=$'\033[38;5;220m' GREEN=$'\033[32m' RED=$'\033[31m' OFF=$'\033[0m' fi trap on_exit EXIT - trap 'exit 130' INT TERM + trap 'exit 130' INT TERM HUP } step() { # step "what it does" command... @@ -114,7 +136,7 @@ took() { local s=$((SECONDS - STARTED)); [ "$s" -lt 5 ] || printf ' %s%ss%s' "$D spin() { [ -n "$FANCY" ] || return 0 - ( trap - EXIT INT TERM + ( trap - EXIT INT TERM HUP frames=(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏) i=0 while kill -0 $$ 2>/dev/null; do printf '\r\033[2K %s%s%s %s%s' "$GOLD" "${frames[i % 10]}" "$OFF" "$STEP" "$(took)" >&3 @@ -141,6 +163,7 @@ die() { # a failure we can explain: no need to show the log on_exit() { local code=$? unspin + rm -rf "$LOCK" [ "$code" -ne 0 ] && [ -n "$STEP" ] || return 0 printf ' %s✗%s %s\n\n' "$RED" "$OFF" "$STEP" >&3 [ "$code" -ne 130 ] || { printf ' Stopped. Run the installer again to carry on.\n\n' >&3; return 0; } @@ -164,16 +187,14 @@ need_git() { # (on a Mac without the command line tools, `git` exists but only check_machine() { need_git - have curl || die "ghost needs curl: install it with your package manager, then run this again." - local open + local tool open + for tool in curl tar find; do have "$tool" || die "ghost needs $tool: install it with your package manager, then run this again."; done + case "$(ldd --version 2>&1 || true)" in *musl*) die "ghost needs a Linux with glibc (Debian, Ubuntu, Fedora, Arch, ...). This one uses musl, as Alpine does." ;; esac if ! open="$(GHOST_ENGINE="$ENG" GHOST_HOME="$GHOST_HOME" bash "$REPO/scripts/fork-engine.sh" --check 2>&1)"; then case "$open" in "!! ghost is open"*) die "${open#!! }" ;; *) echo "$open"; return 1 ;; esac fi - if ! have uv; then # it brings the bridge's own Python, so the system's never matters - curl -LsSf https://astral.sh/uv/install.sh | sh - PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH" - fi - have uv || die "couldn't install uv (https://docs.astral.sh/uv/getting-started/installation/). Install it, then run this again." + space + get_uv if [ -n "$GHOST_LOCAL" ] && ! have ollama; then ! have brew || brew install --cask ollama || true have ollama || die "GHOST_LOCAL needs Ollama: install it from https://ollama.com (or drop GHOST_LOCAL), then run this again." @@ -181,10 +202,27 @@ check_machine() { remember } +space() { # (the first time: an update needs little) + local need=3500 free + [ -z "$GHOST_NO_BROWSER" ] || need=2000 + [ ! -d "$ENG" ] || return 0 + free="$(df -Pm "$GHOST_HOME" 2>/dev/null | awk 'NR == 2 { print $4 }')" + case "$free" in ""|*[!0-9]*) return 0 ;; esac + [ "$free" -ge "$need" ] || die "ghost needs about $((need / 1000)).$((need % 1000 / 100)) GB of disk, and there are $((free / 1000)).$((free % 1000 / 100)) GB free here." +} + +# uv brings the bridge's own Python, so the system's never matters. Ours, because one you have may be too old. +UV_VERSION=0.13.10 +get_uv() { + UV="$GHOST_HOME/uv/uv" + case "$("$UV" --version 2>/dev/null)" in "uv $UV_VERSION"*) return 0 ;; esac + curl -LsSf "https://astral.sh/uv/$UV_VERSION/install.sh" | UV_UNMANAGED_INSTALL="$GHOST_HOME/uv" sh || true + [ -x "$UV" ] || ! have uv || UV=uv + "$UV" --version || die "couldn't download uv, which brings ghost's Python (from astral.sh and github.com). Check your connection, then run this again." +} + install_bridge() { - # (Again with the system's certificates, for a network that has one of its own.) - ( cd "$REPO" && export UV_PROJECT_ENVIRONMENT="$GHOST_HOME/venv" \ - && { uv sync --python 3.11 --frozen || UV_SYSTEM_CERTS=1 UV_NATIVE_TLS=1 uv sync --python 3.11 --frozen; } ) + ( cd "$REPO" && UV_PROJECT_ENVIRONMENT="$GHOST_HOME/venv" "$UV" sync --managed-python --python 3.11 --frozen ) mkdir -p "$PRIV" if [ -e "$PRIV/.scrub" ]; then # someone relied on it: say so rather than let them find out NOTES+=("Redaction was removed. What you send is sealed to a TEE enclave, but no longer redacted first.") @@ -235,13 +273,16 @@ free_port() { # stopping a service finishes in its own time, and two bridges c done } -stop_bridge() { # whichever process holds the port, as it says itself (minimal systems have no `pkill`) +stop_bridge() { # whichever process holds the port, as it says itself, if it is ours (minimal systems have no `pkill`, nor `ps`) local pid - pid="$(curl -s -D - -o /dev/null --max-time 2 http://127.0.0.1:8788/healthz | tr -d '\r' | sed -n 's/^X-Ghost-Pid: //p' || true)" - [ -z "$pid" ] || kill "$pid" || true + pid="$(curl -s -D - -o /dev/null --max-time 2 http://127.0.0.1:8788/healthz | tr -d '\r' | sed -n 's/^X-Ghost-Pid: \([0-9]*\)$/\1/p' || true)" + [ -n "$pid" ] || return 0 + case "$(ps -ww -o command= -p "$pid" 2>/dev/null || tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null || true)" in + *"$PRIV/"*) kill "$pid" || true ;; + esac } -fill() { sed -e "s#__PYTHON__#$PYTHON#g" -e "s#__GHOST_HOME__#$GHOST_HOME#g" -e "s#__ENG__#$ENG#g" "$1"; } +fill() { "$PYTHON" -Es "$REPO/scripts/fill.py" "$1" "__PYTHON__=$PYTHON" "__GHOST_HOME__=$GHOST_HOME" "__ENG__=$ENG"; } # The bridge runs in the background and restarts by itself: launchd on macOS, systemd on Linux. Where neither # is available (some containers, WSL without systemd) `ghost` starts it when it's needed. @@ -280,35 +321,55 @@ start_service() { pkill -f "veil serve --foreground --skip-setup --port 11435" || true free_port fi - "$PYTHON" -Es -c 'import sys; sys.path.insert(0, sys.argv[1]); import launch; sys.exit(not launch.ensure_bridge())' "$PRIV" \ - || die "the background service didn't start. Its log is $PRIV/bridge.log" + local why + why="$(GHOST_HOME="$GHOST_HOME" "$PYTHON" -Es -c 'import sys; sys.path.insert(0, sys.argv[1]); import launch +print("" if launch.ensure_bridge() else launch.bridge_problem())' "$PRIV")" || why="its log is $PRIV/bridge.log" + [ -z "$why" ] || die "ghost's background service isn't running: $why." } install_commands() { local name mkdir -p "$BIN" + if [ -e "$BIN/ghost" ] && ! grep -qsi -e GHOST_HOME -e hermes "$BIN/ghost"; then + mv "$BIN/ghost" "$BIN/ghost.other" # (the Ghost blog's command has that name too) + NOTES+=("There was another program at $BIN/ghost. It is now $BIN/ghost.other.") + fi for name in ghost ghost-login ghost-update ghost-uninstall; do fill "$REPO/bin/$name" > "$BIN/.$name.new" chmod +x "$BIN/.$name.new" mv -f "$BIN/.$name.new" "$BIN/$name" # in one move: `ghost update` is running from one of these done + add_to_path GHOST_ENGINE="$ENG" GHOST_HOME="$GHOST_HOME" bash "$REPO/scripts/fork-engine.sh" --refresh-gateway } +add_to_path() { # a line in your shell's startup file, where it's needed; `ghost uninstall` takes it out again + case ":$PATH:" in *":$BIN:"*) return 0 ;; esac + local rc line='export PATH="$HOME/.local/bin:$PATH"' file + case "${SHELL:-}" in + */zsh) rc="${ZDOTDIR:-$HOME}/.zshrc" ;; + */fish) rc="${XDG_CONFIG_HOME:-$HOME/.config}/fish/conf.d/ghost.fish" line='fish_add_path -g "$HOME/.local/bin"' + mkdir -p "$(dirname "$rc")" ;; + */bash) rc="$HOME/.bashrc" + if [ "$OS" = Darwin ]; then # a login shell, which reads only the first of these there is + for file in .profile .bash_login .bash_profile; do [ ! -f "$HOME/$file" ] || rc="$HOME/$file"; done + [ "$rc" != "$HOME/.bashrc" ] || rc="$HOME/.bash_profile" + fi ;; + *) rc="$HOME/.profile" ;; + esac + grep -qs '\.local/bin' "$rc" || printf '\n%s # ghost\n' "$line" >> "$rc" +} + finish() { - local who note rc + local who note found printf '\n' >&3 for note in ${NOTES[@]+"${NOTES[@]}"}; do printf ' %s%s%s\n' "$DIM" "$note" "$OFF" >&3; done [ "${#NOTES[@]}" -eq 0 ] || printf '\n' >&3 case ":$PATH:" in - *":$BIN:"*) ;; - *) if (cd "$HOME" && grep -qs '\.local/bin' .zshrc .zprofile .zshenv .bashrc .bash_profile .profile); then - printf ' Open a new terminal first, so that it finds ~/.local/bin.\n\n' >&3 - else - case "${SHELL:-}" in */zsh) rc="~/.zshrc" ;; */bash) rc="~/.bashrc" ;; *) rc="~/.profile" ;; esac - printf ' First put ~/.local/bin on your PATH, then open a new terminal:\n\n' >&3 - printf ' echo '\''export PATH="$HOME/.local/bin:$PATH"'\'' >> %s\n\n' "$rc" >&3 - fi ;; + *":$BIN:"*) + found="$(command -v ghost || true)" + [ "$found" = "$BIN/ghost" ] || printf ' Another program called ghost comes first on your PATH (%s). This one is %s.\n\n' "$found" "$BIN/ghost" >&3 ;; + *) printf ' Open a new terminal first, so that it finds the command.\n\n' >&3 ;; esac if who="$("$BIN/ghost-login" --status 2>/dev/null)"; then printf ' %sghost is ready.%s %s.\n\n' "$BOLD" "$OFF" "$who" >&3 else printf ' %sghost is ready.%s It asks you to log in the first time.\n\n' "$BOLD" "$OFF" >&3; fi diff --git a/privacy/bridge.py b/privacy/bridge.py index 0d3095a..f6b0942 100755 --- a/privacy/bridge.py +++ b/privacy/bridge.py @@ -418,11 +418,14 @@ def _error(self, status, message): self._send_json(status, {"error": {"message": message}}) def do_GET(self): - if self.path == "/healthz": + path, _, nonce = self.path.partition("?") + if path == "/healthz": body = b"ok" self.send_response(200) self.send_header("Content-Type", "text/plain") self.send_header("X-Ghost-Pid", str(os.getpid())) # how the installer finds us to replace us + if nonce: + self.send_header("X-Ghost-Proof", ghost_auth.bridge_proof(nonce[:64])) self.send_header("Content-Length", str(len(body))) self.send_header("Connection", "close") self.end_headers() @@ -546,6 +549,11 @@ def _send_stream(self, reply): if __name__ == "__main__": + try: + if os.path.getsize(LOG) > 5_000_000: + os.replace(LOG, LOG + ".1") + except OSError: + pass spend.prune() log(f"bridge up on {LISTEN[0]}:{LISTEN[1]}") LocalServer(LISTEN, Handler).serve_forever() diff --git a/privacy/doctor.py b/privacy/doctor.py index ae8cbd5..e2cb3ae 100644 --- a/privacy/doctor.py +++ b/privacy/doctor.py @@ -30,7 +30,7 @@ def login(): def bridge(): if launch.ensure_bridge(): return True, f"running on 127.0.0.1:{launch.PORT}", None - return False, f"isn't running; its log is {launch.PRIV / 'bridge.log'}", "ghost update" + return False, f"isn't running: {launch.bridge_problem()}", None if launch.port_taken() else "ghost update" def relay(): diff --git a/privacy/ghost_auth.py b/privacy/ghost_auth.py index a3a3295..2182253 100644 --- a/privacy/ghost_auth.py +++ b/privacy/ghost_auth.py @@ -9,8 +9,10 @@ A login says who you are, never where your requests go or which enclaves to trust: those are fixed here and in opengradient-ohttp, so a login you were tricked into accepting can't point ghost at an impostor. """ +import hmac import json import os +import secrets import threading import time from pathlib import Path @@ -21,6 +23,7 @@ BUNDLE_TYPE = "opengradient-cli-auth" # what the website's /cli-auth page hands to a CLI KEY_FILE = Path(os.environ.get("GHOST_HOME") or Path.home() / ".ghost") / "privacy" / "dreamfort_api_key" +BRIDGE_KEY_FILE = KEY_FILE.with_name("bridge.key") SESSION_FILE = Path(os.environ.get("OG_VEIL_HOME") or Path.home() / ".opengradient" / "veil") / "session.json" CREDITS_URL = "https://www.dreamfort.ai/dashboard/credits" @@ -63,6 +66,17 @@ def _write_private(path, text): os.replace(tmp, path) +def bridge_proof(nonce): + """What only your own bridge can answer. Its port may be held by another program, or by the ghost of someone + else on this machine, and neither may have your prompts.""" + try: + key = BRIDGE_KEY_FILE.read_text(encoding="utf-8") + except OSError: + key = secrets.token_hex(32) + _write_private(BRIDGE_KEY_FILE, key) + return hmac.new(key.encode(), nonce.encode(), "sha256").hexdigest() + + # ── API key ─────────────────────────────────────────────────────────────────── def api_key(): key = _read(KEY_FILE, str.strip) diff --git a/privacy/ghost_login.py b/privacy/ghost_login.py index 9795c05..a8815e3 100644 --- a/privacy/ghost_login.py +++ b/privacy/ghost_login.py @@ -114,14 +114,20 @@ def read(self, timeout): return self._read_windows(timeout) if not select.select([self._fd], [], [], timeout)[0]: return "" - data = os.read(self._fd, 65536) + data = self._input() while select.select([self._fd], [], [], 0.02)[0]: - more = os.read(self._fd, 65536) - if not more: - break - data += more + data += self._input() return data.decode("utf-8", "replace") + def _input(self): + try: + data = os.read(self._fd, 65536) + except OSError: + data = b"" + if not data: # the terminal is gone + raise Cancelled + return data + @staticmethod def _read_windows(timeout): import msvcrt @@ -251,7 +257,11 @@ def device_code(): if resp.status_code in (404, 405, 501): return None resp.raise_for_status() - return resp.json() + try: + handshake = resp.json() + return handshake if {"deviceCode", "userCode", "verificationUri", "expiresIn", "interval"} <= set(handshake) else None + except (ValueError, TypeError): # some other page: a network that answers for everyone, say + return None def device_login(handshake): @@ -286,13 +296,14 @@ def device_login(handshake): json={"deviceCode": handshake["deviceCode"]}, timeout=TIMEOUT, verify=trust) except httpx.HTTPError: continue # a network blip; keep waiting + try: + answer = poll.json() + error = None if poll.status_code == 200 else answer.get("error") + except (ValueError, AttributeError): + answer, error = None, None if poll.status_code == 200: spin.clear() - return poll.json() - try: - error = poll.json().get("error") - except ValueError: - error = None + return answer # (save_account says if it isn't a login) if error in ("expired_token", "invalid_grant"): break if error == "slow_down" or poll.status_code == 429: diff --git a/privacy/launch.py b/privacy/launch.py index 7e5029e..05b75ea 100644 --- a/privacy/launch.py +++ b/privacy/launch.py @@ -5,13 +5,16 @@ seals every request to a TEE enclave; `ghost --local` never leaves this machine. Nothing is contacted before you log in. """ +import hmac import http.client import json import os import platform import re +import secrets import shutil import signal +import socket import subprocess import sys import time @@ -105,16 +108,28 @@ def walk(node): # ── the bridge ──────────────────────────────────────────────────────────────── def bridge_up(): + """Is the bridge answering, and is it yours?""" + nonce = secrets.token_hex(8) conn = http.client.HTTPConnection("127.0.0.1", PORT, timeout=2) try: - conn.request("GET", "/healthz") - return conn.getresponse().status == 200 + conn.request("GET", f"/healthz?{nonce}") + resp = conn.getresponse() + return resp.status == 200 and hmac.compare_digest(resp.headers.get("X-Ghost-Proof") or "", ghost_auth.bridge_proof(nonce)) except (OSError, http.client.HTTPException): return False finally: conn.close() +def port_taken(): + """Something answers on the bridge's port (and, when the bridge isn't up, it isn't the bridge).""" + try: + socket.create_connection(("127.0.0.1", PORT), timeout=2).close() + return True + except OSError: + return False + + def _quiet(*cmd): try: return subprocess.run(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, @@ -150,6 +165,8 @@ def ensure_bridge(): """It runs as a background service; start it if something stopped it.""" if bridge_up(): return True + if port_taken() and not bridge_up(): + return False if not _start_service(): # no service manager here, or none that has it try: _start_process() @@ -162,6 +179,11 @@ def ensure_bridge(): return False +def bridge_problem(): + return (f"another program is using port {PORT}, which ghost's bridge needs (or someone else on this machine is running ghost)" + if port_taken() else f"it didn't start; its log is {PRIV / 'bridge.log'}") + + # ── the engine ──────────────────────────────────────────────────────────────── def engine_binary(): bin_dir = ENGINE / ".hermes" / "bin" @@ -273,6 +295,9 @@ def main(argv): return stop pin_route() if not ensure_bridge(): + if port_taken(): # whoever it is, they'd be sent your prompts + say(f"{bridge_problem()}. Close it, then start ghost again.") + return 1 say("ghost's background service isn't running, so hosted models won't answer. Fix it with: ghost update") if sys.stderr.isatty(): say(status_line(config, args)) diff --git a/scripts/fill.py b/scripts/fill.py new file mode 100644 index 0000000..37ff48e --- /dev/null +++ b/scripts/fill.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +"""Put this install's paths into a template, quoted for what it is (a script, a launchd plist, a systemd unit). + + fill.py FILE __NAME__=VALUE... +""" +import shlex +import sys +from pathlib import Path +from xml.sax.saxutils import escape + +QUOTE = {".plist": escape, ".service": lambda value: value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%")} + + +def fill(path, values): + text = path.read_text(encoding="utf-8") + for name, value in values: + text = text.replace(name, QUOTE.get(path.suffix, shlex.quote)(value)) + return text + + +if __name__ == "__main__": + sys.stdout.buffer.write(fill(Path(sys.argv[1]), [arg.split("=", 1) for arg in sys.argv[2:]]).encode("utf-8")) diff --git a/scripts/fork-engine.ps1 b/scripts/fork-engine.ps1 index 8ab802a..68b61b9 100644 --- a/scripts/fork-engine.ps1 +++ b/scripts/fork-engine.ps1 @@ -11,6 +11,7 @@ param( [string]$Eng = $(if ($env:GHOST_ENGINE) { $env:GHOST_ENGINE } else { "$env:USERPROFILE\.ghost-engine" }), [string]$GhostHome = $(if ($env:GHOST_HOME) { $env:GHOST_HOME } else { "$env:USERPROFILE\.ghost" }), + [string]$Python = "python", # a Python 3.9+ to run debrand.py [switch]$Check, [switch]$RefreshGateway ) @@ -118,7 +119,7 @@ foreach ($d in ".git",".github","tests","tests-js","evals","website","contributo # ---------- 2. debrand + seal ---------- Write-Host "==> debranding" -& uv run --no-project --python 3.11 python "$here\debrand.py" $New +& $Python -Es "$here\debrand.py" $New if ($LASTEXITCODE -ne 0) { throw "debrand.py failed" } $stamp = [ordered]@{ schemaVersion = 2; commit = $Commit; commitDate = $null; branch = $null diff --git a/scripts/fork-engine.sh b/scripts/fork-engine.sh index 803e6c0..af2b5cb 100755 --- a/scripts/fork-engine.sh +++ b/scripts/fork-engine.sh @@ -51,16 +51,30 @@ HERMES_VERSION="" HERMES_COMMIT="" # Is ghost open on this engine? A process keeps importing from the engine's path for as long as it # runs, so swapping the tree underneath one would mix two releases in it. The background gateway # doesn't count: it is ours to stop and start again. -processes() { # minimal systems have no `ps` - if command -v ps >/dev/null 2>&1; then ps axww -o pid=,command=; return; fi - local dir - for dir in /proc/[0-9]*; do printf '%s %s\n' "${dir#/proc/}" "$(tr '\0' ' ' < "$dir/cmdline" 2>/dev/null)"; done +processes() { # each one's pid, parent and command (minimal systems have no `ps`) + if command -v ps >/dev/null 2>&1; then ps axww -o pid=,ppid=,command=; return; fi + local dir parent + for dir in /proc/[0-9]*; do + parent="$(sed -n 's/^PPid:[^0-9]*//p' "$dir/status" 2>/dev/null || true)" + printf '%s %s %s\n' "${dir#/proc/}" "${parent:-0}" "$(tr '\0' ' ' < "$dir/cmdline" 2>/dev/null)" + done } check_closed() { [ -d "$ENG" ] && [ -z "${GHOST_FORCE:-}" ] || return 0 - local pids # launched by path, or as `python -c "... '' ..."` - pids="$( (processes 2>/dev/null || true) | awk -v e="$ENG" \ - '(index($0, e "/") || index($0, e "\047")) && !/gateway run/ { print $1 }')" + # Launched by path, or as `python -c "... '' ..."`. What the gateway started isn't a window either, nor is + # the reaper that goes with every engine process. + local pids + pids="$( (processes 2>/dev/null || true) | awk -v e="$ENG" -v h="$GHOST_HOME" ' + { parent[$1] = $2; engine[$1] = index($0, e "/") || index($0, e "\047") + gateway[$1] = (engine[$1] || index($0, h "/tools/")) && /gateway run/; reaper[$1] = /process_supervisor[.]sh/ } + END { + for (p in engine) { + if (!engine[p] || reaper[p]) continue + q = p; hops = 0 + while ((q in parent) && !gateway[q] && hops++ < 64) q = parent[q] + if (!gateway[q]) print p + } + }')" [ -z "$pids" ] && return 0 echo "!! ghost is open (pid $(echo $pids)). Close those windows and re-run, or set GHOST_FORCE=1." >&2 return 1 @@ -91,6 +105,7 @@ if current; then echo "==> the engine is already this build: $ENG"; exit 0; fi check_closed # ---------- 1. fetch ---------- +trap 'exit 130' INT TERM HUP # so that the traps below run, whatever stops this trap 'rm -rf "$NEW"' EXIT # a build that stops here leaves the current engine untouched rm -rf "$NEW"; mkdir -p "$(dirname "$NEW")" "$GHOST_HOME" if [ -n "${HERMES_SRC:-}" ]; then diff --git a/systemd/ghost-bridge.service b/systemd/ghost-bridge.service index c42b501..7ac9f43 100644 --- a/systemd/ghost-bridge.service +++ b/systemd/ghost-bridge.service @@ -2,8 +2,8 @@ Description=ghost's local bridge to the TEE gateway (127.0.0.1:8788) [Service] -Environment=GHOST_HOME=__GHOST_HOME__ -ExecStart=__PYTHON__ -Es __GHOST_HOME__/privacy/bridge.py +Environment="GHOST_HOME=__GHOST_HOME__" +ExecStart="__PYTHON__" -Es "__GHOST_HOME__/privacy/bridge.py" Restart=always RestartSec=2 diff --git a/tests/fake_dreamfort.py b/tests/fake_dreamfort.py index 3cad774..e4aadd3 100644 --- a/tests/fake_dreamfort.py +++ b/tests/fake_dreamfort.py @@ -14,6 +14,7 @@ import json import os import re +import socketserver import struct import sys import time @@ -207,10 +208,16 @@ def relay(self, body): return Handler +class Server(ThreadingHTTPServer): + daemon_threads = True + + def server_bind(self): # without looking up its own name, which takes half a minute on some Macs + socketserver.TCPServer.server_bind(self) + self.server_name, self.server_port = self.server_address[:2] + + def serve(service, port=0): - server = ThreadingHTTPServer(("127.0.0.1", port), handler(service)) - server.daemon_threads = True - return server + return Server(("127.0.0.1", port), handler(service)) class Redirected(httpx.HTTPTransport): diff --git a/tests/test_bridge.py b/tests/test_bridge.py index 80e72a8..6ca99f7 100644 --- a/tests/test_bridge.py +++ b/tests/test_bridge.py @@ -324,7 +324,13 @@ def test_a_nonsense_limit_is_the_usual_one(enclave, bridge, asked): def test_the_bridge_says_which_process_it_is(bridge): with urllib.request.urlopen(bridge.url + "/healthz", timeout=5) as resp: - assert (resp.read(), resp.headers["X-Ghost-Pid"]) == (b"ok", str(os.getpid())) + assert (resp.read(), resp.headers["X-Ghost-Pid"], resp.headers["X-Ghost-Proof"]) == (b"ok", str(os.getpid()), None) + + +def test_the_bridge_proves_that_it_is_yours(monkeypatch, tmp_path, bridge): + monkeypatch.setattr(sp.ghost_auth, "BRIDGE_KEY_FILE", tmp_path / "bridge.key") + with urllib.request.urlopen(bridge.url + "/healthz?nonce", timeout=5) as resp: + assert resp.headers["X-Ghost-Proof"] == sp.ghost_auth.bridge_proof("nonce") != sp.ghost_auth.bridge_proof("other") def test_a_web_page_cannot_spend_your_credits(enclave, bridge): diff --git a/tests/test_fork_engine.py b/tests/test_fork_engine.py index 8732841..8ab8a75 100644 --- a/tests/test_fork_engine.py +++ b/tests/test_fork_engine.py @@ -3,6 +3,7 @@ import platform import re import shutil +import signal import subprocess import sys import time @@ -182,6 +183,38 @@ def test_gateway_does_not_count_as_open(box, shape): assert box.run("--check").returncode == 0 +def test_what_a_chat_leaves_running_does_not_count_either(box): + """Closed a minute ago, yet `ghost update` said it was open: the gateway idles on, with helpers of the engine's.""" + assert box.run(src=box.source("one")).returncode == 0 + box.procs.append(subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)", f"{box.engine}/hermes_cli/process_supervisor.sh", "123"])) + helper = f"import subprocess, sys, time; subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)', '{box.engine}/tools/kernel.py']).wait()" + box.procs.append(subprocess.Popen([sys.executable, "-c", helper, f"{box.state}/tools/python", "gateway run --idle-exit"], start_new_session=True)) + deadline = time.time() + 5 + while "tools/kernel.py" not in subprocess.run(["pgrep", "-fl", "tools/kernel.py"], capture_output=True, text=True).stdout and time.time() < deadline: + time.sleep(0.05) + try: + assert box.run("--check").returncode == 0 + finally: + os.killpg(box.procs[-1].pid, 9) + + +@pytest.mark.parametrize("stop", [signal.SIGINT, signal.SIGTERM, signal.SIGHUP]) +def test_a_build_that_is_stopped_restores_the_previous_engine(box, stop): + """Ctrl-C, a shutdown, or a closed terminal window.""" + assert box.run(src=box.source("one")).returncode == 0 + slow = box.source("two") + (slow / "scripts" / "install.sh").write_text("#!/bin/bash\ntouch \"$HOME/building\"\nsleep 30\n") + env = {"PATH": f"{box.bin}:{os.environ['PATH']}", "HOME": str(box.home), "GHOST_PYTHON": "true", "HERMES_SRC": str(slow)} + build = subprocess.Popen(["bash", str(BUILDER)], env=env, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + deadline = time.time() + 20 + while not (box.home / "building").exists(): + assert time.time() < deadline + time.sleep(0.05) + os.killpg(build.pid, stop) + assert build.wait(timeout=20) == 130 + assert (box.engine / "one").exists() and not (box.engine / "two").exists() and not box.old.exists() + + @pytest.fixture def released(box): """As users build it: fetched at the pinned commit (a stand-in `git` clones a local tree).""" diff --git a/tests/test_install.py b/tests/test_install.py index 3fdf814..7dcff26 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -2,8 +2,10 @@ The real engine and services are covered by CI's install jobs; this is everything around them. """ +import hmac import json import os +import re import shutil import subprocess import sys @@ -36,9 +38,20 @@ """ +# What astral.sh serves: an installer that puts uv where it's told. +UV = r"""#!/bin/sh +echo "uv $*" >> "$HOME/calls" +[ "$1" != --version ] || { echo "uv VERSION (stub)"; exit; } +mkdir -p "$UV_PROJECT_ENVIRONMENT/bin" +printf '#!/bin/sh\nexec "PYTHON" "$@"\n' > "$UV_PROJECT_ENVIRONMENT/bin/python" +chmod +x "$UV_PROJECT_ENVIRONMENT/bin/python" +""" +UV_VERSION = next(line.split("=")[1] for line in (REPO / "install.sh").read_text().splitlines() if line.startswith("UV_VERSION=")) + + class Machine: - def __init__(self, root, system, port): - self.home, self.bin, self.repo = root / "home", root / "stubs", root / "repo" + def __init__(self, root, system, port, home="home"): + self.home, self.bin, self.repo = root / home, root / "stubs", root / "repo" self.ghost, self.engine, self.commands = self.home / ".ghost", self.home / ".ghost-engine", self.home / ".local" / "bin" self.profile = self.ghost / "profiles" / "uncensored" for directory in (self.home, self.bin, self.repo): @@ -52,10 +65,12 @@ def __init__(self, root, system, port): launch.write_text(launch.read_text(encoding="utf-8").replace("PORT = 8788", f"PORT = {port}"), encoding="utf-8") log = 'echo "$(basename "$0") $*" >> "$HOME/calls"\n' self.stub("uname", f"echo {system}\n") - self.stub("uv", log + 'mkdir -p "$UV_PROJECT_ENVIRONMENT/bin"\n' - f'printf \'#!/bin/sh\\nexec "{sys.executable}" "$@"\\n\' > "$UV_PROJECT_ENVIRONMENT/bin/python"\n' - 'chmod +x "$UV_PROJECT_ENVIRONMENT/bin/python"\n') - self.stub("curl", log + "exit 7\n") # nobody is on the bridge's port + (root / "uv").write_text(UV.replace("VERSION", UV_VERSION).replace("PYTHON", sys.executable)) + (root / "get-uv").write_text(f'mkdir -p "$UV_UNMANAGED_INSTALL"; cp "{root}/uv" "$UV_UNMANAGED_INSTALL/uv"; chmod +x "$UV_UNMANAGED_INSTALL/uv"\n') + self.stub("curl", log + f'case "$*" in *astral.sh/uv/{UV_VERSION}/install.sh) [ ! -e "$HOME/offline" ] || exit 6; cat "{root}/get-uv" ;; ' + '*) exit 7 ;; esac\n') # nobody is on the bridge's port + self.stub("id", '[ "$1" = -u ] && [ -e "$HOME/root" ] && echo 0 || exec /usr/bin/id "$@"\n') + self.stub("ldd", '[ -e "$HOME/musl" ] && echo "musl libc (x86_64)" >&2 || echo "ldd (GNU libc) 2.36"\n') for name in ("launchctl", "loginctl", "pkill"): self.stub(name, log) self.stub("systemctl", log + '[ "$2" != show-environment ] || [ ! -e "$HOME/no-systemd" ]\n') @@ -82,15 +97,19 @@ def calls(self): @pytest.fixture def machine(tmp_path): class Health(BaseHTTPRequestHandler): - def do_GET(self): + def do_GET(self): # as ghost's own bridge + key = next(tmp_path.glob("*/.ghost/privacy")) / "bridge.key" + if not key.exists(): + key.write_text("k") self.send_response(200) + self.send_header("X-Ghost-Proof", hmac.new(key.read_bytes(), self.path.partition("?")[2].encode(), "sha256").hexdigest()) self.end_headers() def log_message(self, *args): pass server = ThreadingHTTPServer(("127.0.0.1", 0), Health) threading.Thread(target=server.serve_forever, daemon=True).start() - yield lambda system="Linux": Machine(tmp_path, system, server.server_port) + yield lambda system="Linux", **options: Machine(tmp_path, system, server.server_port, **options) server.shutdown() server.server_close() @@ -108,7 +127,7 @@ def test_fresh_install(machine, system): assert "previous" not in done.stdout and "Ghost" in (m.profile / "SOUL.md").read_text() assert "compiling the engine" in (m.ghost / "install.log").read_text() for name in ("ghost", "ghost-login", "ghost-update", "ghost-uninstall"): - assert os.access(m.commands / name, os.X_OK) and "__" not in (m.commands / name).read_text() + assert os.access(m.commands / name, os.X_OK) and not re.search("__[A-Z]", (m.commands / name).read_text()) assert (m.ghost / ".src").read_text() == f"{m.repo}\n" and (m.ghost / ".install-env").read_text() == "" config = (m.profile / "config.yaml").read_text() assert "ollama-local" not in config and "__" not in config and f"{m.ghost}/privacy/uncensored_prefill.json" in config @@ -123,7 +142,8 @@ def test_a_new_install_contacts_nobody_until_you_log_in(machine): assert (chat.returncode, chat.stdout) == (1, "") and "not logged in. Run: ghost login" in chat.stderr assert m.command("ghost", "--version").stdout == "Ghost v9\n" assert m.command("ghost-login", "--status").returncode == 1 - assert {c for c in m.calls() if c.startswith("curl")} <= {"curl -s -o /dev/null --max-time 1 http://127.0.0.1:8788/healthz"} + assert {c for c in m.calls() if c.startswith("curl")} <= {"curl -s -o /dev/null --max-time 1 http://127.0.0.1:8788/healthz", + f"curl -LsSf https://astral.sh/uv/{UV_VERSION}/install.sh"} def test_services_on_a_mac(machine): @@ -152,7 +172,7 @@ def test_services_on_linux(machine): (units / f"{unit}.service").write_text("old") assert m.install().returncode == 0 assert [p.name for p in units.iterdir()] == ["ghost-bridge.service"] - assert f"Environment=GHOST_HOME={m.ghost}\nExecStart={m.ghost}/venv/bin/python -Es {m.ghost}/privacy/" in (units / "ghost-bridge.service").read_text() + assert f'Environment="GHOST_HOME={m.ghost}"\nExecStart="{m.ghost}/venv/bin/python" -Es "{m.ghost}/privacy/' in (units / "ghost-bridge.service").read_text() calls = m.calls() for call in (*(f"systemctl --user disable --now {u}.service" for u in OLD_UNITS), "systemctl --user restart ghost-bridge.service"): assert call in calls @@ -246,12 +266,94 @@ def test_a_failed_check_is_not_taken_for_an_open_ghost(machine): assert done.returncode == 1 and "✗ Checking this machine" in done.stdout and "something else broke" in done.stdout -def test_path_hint(machine): +@pytest.mark.parametrize("system, shell, existing, expect", [ + ("Darwin", "/bin/zsh", [], ".zshrc"), ("Linux", "/usr/bin/zsh", [".zshrc"], ".zshrc"), ("Linux", "/bin/bash", [], ".bashrc"), + ("Darwin", "/bin/bash", [], ".bash_profile"), ("Darwin", "/bin/bash", [".profile"], ".profile"), # a new .bash_profile would hide it + ("Darwin", "/bin/bash", [".profile", ".bash_profile"], ".bash_profile"), ("Linux", "/bin/dash", [], ".profile"), + ("Linux", "/usr/bin/fish", [], ".config/fish/conf.d/ghost.fish"), +]) +def test_your_shell_finds_the_command(machine, system, shell, existing, expect): + m = machine(system) + for name in existing: + (m.home / name).write_text("# yours\n") + assert "Open a new terminal first" in m.install(SHELL=shell).stdout + startup = [p for p in (m.home / n for n in (".zshrc", ".bashrc", ".bash_profile", ".profile", ".config/fish/conf.d/ghost.fish")) if p.exists()] + with_line = [p for p in startup if ".local/bin" in p.read_text()] + assert with_line == [m.home / expect] and with_line[0].read_text().count(".local/bin") == 1 + m.install(SHELL=shell) + assert with_line[0].read_text().count(".local/bin") == 1 # once + assert m.command("ghost-uninstall", "--yes", SHELL=shell).returncode == 0 + assert not any(".local/bin" in p.read_text() for p in startup if p.exists()) + assert all((m.home / name).read_text().startswith("# yours\n") for name in existing) + + +def test_a_path_you_already_have_is_left_alone(machine): m = machine() - assert "echo 'export PATH=\"$HOME/.local/bin:$PATH\"' >> ~/.zshrc" in m.install().stdout (m.home / ".zshrc").write_text('export PATH="$HOME/.local/bin:$PATH"\n') - assert "Open a new terminal first" in m.install().stdout - assert "PATH" not in m.install(PATH=f"{m.commands}:{m.bin}:{os.environ['PATH']}").stdout + assert "Open a new terminal first" in m.install().stdout and (m.home / ".zshrc").read_text().count("local/bin") == 1 + (m.home / ".zshrc").unlink() + done = m.install(PATH=f"{m.commands}:{m.bin}:{os.environ['PATH']}") + assert "PATH" not in done.stdout and "terminal" not in done.stdout and not (m.home / ".zshrc").exists() + + +def test_another_program_called_ghost(machine): + """The Ghost blog's command has the name too: not overwritten, not run by mistake without a word, and put back.""" + m = machine() + m.commands.mkdir(parents=True) + (m.commands / "ghost").write_text("#!/usr/bin/env node\nrequire('ghost-cli')\n") + assert f"It is now {m.commands}/ghost.other" in m.install().stdout and "ghost-cli" in (m.commands / "ghost.other").read_text() + m.stub("ghost", "echo a blog\n") + assert f"Another program called ghost comes first on your PATH ({m.bin}/ghost)" in m.install(PATH=f"{m.bin}:{m.commands}:{os.environ['PATH']}").stdout + m.command("ghost-uninstall", "--yes") + assert "ghost-cli" in (m.commands / "ghost").read_text() and not (m.commands / "ghost.other").exists() + + +def test_a_home_nobody_would_choose(machine): + m = machine("Darwin", home="Zoé O'Neil & co #1 $x 50%") + done = m.install() + assert done.returncode == 0, done.stdout + done.stderr + assert m.command("ghost", "--version").stdout == "Ghost v9\n" and m.command("ghost-login", "--status").returncode == 1 + plist = (m.home / "Library/LaunchAgents/ai.dreamfort.ghost.plist").read_text() + assert "& co" in plist and "& co" not in plist.replace("& co", "") + assert m.command("ghost", "uninstall", "--yes", "--purge").returncode == 0 and not m.ghost.exists() and not m.engine.exists() + + +@pytest.mark.parametrize("what, words", [ + ("musl", "This one uses musl"), ("offline", "couldn't download uv"), ("root", "Run this without sudo"), +]) +def test_a_machine_it_cannot_install_on_is_told_why(machine, what, words): + m = machine() + (m.home / what).touch() + done = m.install(SUDO_USER="mara", PATH=f"{m.bin}:/usr/bin:/bin") + assert done.returncode == 1 and words in done.stdout + done.stderr and not m.engine.exists() + + +def test_two_installs_at_once(machine): + m = machine() + lock = m.ghost / ".installing" + lock.mkdir(parents=True) + (lock / "pid").write_text(str(os.getpid())) # someone who is still there + done = m.install() + assert done.returncode == 1 and "already being installed or updated" in done.stderr and not m.engine.exists() + (lock / "pid").write_text("999999") # and someone who isn't + assert m.install().returncode == 0 and not lock.exists() + + +def test_nobody_else_can_look_into_it(machine): + m = machine() + m.ghost.mkdir(mode=0o755) + m.install() + assert m.ghost.stat().st_mode & 0o777 == 0o700 + + +def test_it_keeps_to_its_own_folder(machine): + """uv, its Pythons and its cache; nothing in yours.""" + m = machine() + m.stub("uv", 'echo "yours $*" >> "$HOME/calls"; exit 9\n') # one you have is neither needed nor used + assert m.install().returncode == 0 and not any(c.startswith("yours") for c in m.calls()) + assert (m.ghost / "uv" / "uv").exists() and m.calls().count("uv --version") == 1 + m.install() + assert sum("astral.sh" in c for c in m.calls()) == 1 # it's there now def test_a_login_survives_an_update(machine): @@ -314,15 +416,33 @@ def installed(machine): def test_uninstall_keeps_your_data(installed): m, session = installed + kept = {"dreamfort_api_key": "df_sk_abcd\n", "budget": "20\n", "spend.jsonl": "{}\n", "pii_denylist.txt": "mine\n"} + for name, text in kept.items(): + (m.ghost / "privacy" / name).write_text(text) done = m.command("ghost", "uninstall", "--yes") assert done.returncode == 0 and "still in" in done.stdout assert not m.engine.exists() and not any((m.commands / c).exists() for c in ("ghost", "ghost-login", "ghost-update", "ghost-uninstall")) assert not (m.home / "Library/LaunchAgents/ai.dreamfort.ghost.plist").exists() assert not (m.home / ".config/systemd/user/ghost-bridge.service").exists() - assert not (m.ghost / "venv").exists() and not (m.ghost / "privacy").exists() + assert not any((m.ghost / name).exists() for name in ("venv", "uv", "python", "cache", ".src", ".installing")) + assert {p.name: p.read_text() for p in (m.ghost / "privacy").iterdir()} == kept assert (m.profile / "state.db").read_text() == "chats" and session.exists() and m.repo.exists() assert "engine -p uncensored gateway stop" in m.calls() - assert m.install().returncode == 0 and (m.profile / "state.db").read_text() == "chats" # and back again + back = m.install() # and back again, as you left it + assert back.returncode == 0 and "Logged in with your DreamFort API key (df_sk_…abcd)" in back.stdout + assert (m.profile / "state.db").read_text() == "chats" and (m.ghost / "privacy" / "budget").read_text() == "20\n" + + +def test_uninstall_waits_for_an_open_ghost(installed): + m, _ = installed + window = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)", f"{m.engine}/.hermes/bin/hermes"]) + try: + done = m.command("ghost", "uninstall", "--yes") + assert done.returncode == 1 and f"ghost is open (pid {window.pid})" in done.stderr and m.engine.exists() + finally: + window.kill() + window.wait() + assert m.command("ghost", "uninstall", "--yes").returncode == 0 def test_purge_removes_everything(installed): diff --git a/tests/test_launch.py b/tests/test_launch.py index 9099bd3..8255fa8 100644 --- a/tests/test_launch.py +++ b/tests/test_launch.py @@ -1,11 +1,13 @@ """The launcher: what runs the engine, what asks for a login first, and what must contact nobody.""" import os +import socket import subprocess import sys import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path +from types import SimpleNamespace import pytest @@ -125,10 +127,19 @@ def test_a_chat_starts_the_bridge_then_the_engine(box): def test_a_dead_bridge_is_reported_and_the_engine_still_runs(box, monkeypatch, capsys): box.log_in() monkeypatch.setattr(launch, "ensure_bridge", lambda: False) + monkeypatch.setattr(launch, "port_taken", lambda: False) assert launch.main([]) == 0 and box.ran == [[]] assert "background service isn't running" in capsys.readouterr().err +def test_another_program_on_the_bridges_port_never_gets_a_prompt(box, monkeypatch, capsys): + box.log_in() + monkeypatch.setattr(launch, "ensure_bridge", lambda: False) + monkeypatch.setattr(launch, "port_taken", lambda: True) + assert launch.main(["-z", "a secret"]) == 1 and box.ran == [] + assert "another program is using port 8788" in capsys.readouterr().err + + def test_status_line(box): box.log_in() launch.spend._entries.append((time.time(), 0.21)) @@ -182,41 +193,63 @@ def real(tmp_path, monkeypatch): """The real ensure_bridge, with the service manager and the process start replaced.""" class Health(BaseHTTPRequestHandler): def do_GET(self): - self.send_response(200 if self.path == "/healthz" else 404) + path, _, nonce = self.path.partition("?") + self.send_response(200 if path == "/healthz" else 404) + if proves: + self.send_header("X-Ghost-Proof", launch.ghost_auth.bridge_proof(nonce)) self.end_headers() def log_message(self, *args): pass - server = ThreadingHTTPServer(("127.0.0.1", 0), Health) - monkeypatch.setattr(launch, "PORT", server.server_port) + with socket.socket() as free: + free.bind(("127.0.0.1", 0)) + port = free.getsockname()[1] + monkeypatch.setattr(launch, "PORT", port) monkeypatch.setattr(launch, "PRIV", tmp_path) - calls = [] + monkeypatch.setattr(launch.ghost_auth, "BRIDGE_KEY_FILE", tmp_path / "bridge.key") + calls, servers, proves = [], [], [1] + + def listen(): + servers.append(ThreadingHTTPServer(("127.0.0.1", port), Health)) + threading.Thread(target=servers[0].serve_forever, daemon=True).start() def serve(name, ok=True): def start(): calls.append(name) if ok: - threading.Thread(target=server.serve_forever, daemon=True).start() + listen() return ok return start - server.socket.settimeout(0.1) - yield lambda **starts: [monkeypatch.setattr(launch, k, serve(k, v)) for k, v in starts.items()], calls - server.shutdown() if calls else None - server.server_close() + setup = SimpleNamespace(listen=listen, calls=calls, proves=proves, + start=lambda **starts: [monkeypatch.setattr(launch, k, serve(k, v)) for k, v in starts.items()]) + yield setup + for server in servers: + server.shutdown() + server.server_close() def test_bridge_is_started_by_the_service_manager(real): - setup, calls = real - setup(_start_service=True, _start_process=True) - assert launch.ensure_bridge() and calls == ["_start_service"] - assert launch.ensure_bridge() and calls == ["_start_service"] # it's up now: nothing to start + real.start(_start_service=True, _start_process=True) + assert launch.ensure_bridge() and real.calls == ["_start_service"] + assert launch.ensure_bridge() and real.calls == ["_start_service"] # it's up now: nothing to start def test_bridge_is_started_by_us_where_there_is_no_service_manager(real): - setup, calls = real - setup(_start_service=False, _start_process=True) - assert launch.ensure_bridge() and calls == ["_start_service", "_start_process"] + real.start(_start_service=False, _start_process=True) + assert launch.ensure_bridge() and real.calls == ["_start_service", "_start_process"] + + +def test_a_bridge_that_is_not_yours_is_not_the_bridge(real): + """Another program, or the ghost of someone else on this machine: /healthz says ok, and that proves nothing.""" + real.start(_start_service=True, _start_process=True) + real.proves.clear() + real.listen() + assert not launch.ensure_bridge() and real.calls == [] and "another program" in launch.bridge_problem() + real.proves.append(1) + assert launch.ensure_bridge() and real.calls == [] + key = launch.ghost_auth.BRIDGE_KEY_FILE + assert len(key.read_text()) == 64 and (os.name == "nt" or key.stat().st_mode & 0o77 == 0) def test_our_own_bridge_process(tmp_path, monkeypatch): diff --git a/tests/test_login.py b/tests/test_login.py index a160121..b63ed72 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -319,7 +319,10 @@ def test_doctor_contacts_nobody_before_you_log_in(dream, machine, capsys): (lambda d, m: setattr(d, "relay", 503), "✗ DreamFort isn't well (503)"), (lambda d, m: m.setattr(ghost_auth, "CHAT_API_URL", "http://127.0.0.1:9"), "✗ DreamFort can't be reached (ConnectError)"), (lambda d, m: setattr(d, "balance", 0), "✗ Credits none left -> add some at https://www.dreamfort.ai/dashboard/credits"), - (lambda d, m: m.setattr("launch.ensure_bridge", lambda: False), "✗ Bridge isn't running"), + (lambda d, m: (m.setattr("launch.ensure_bridge", lambda: False), m.setattr("launch.port_taken", lambda: False)), + "✗ Bridge isn't running: it didn't start"), + (lambda d, m: (m.setattr("launch.ensure_bridge", lambda: False), m.setattr("launch.port_taken", lambda: True)), + "✗ Bridge isn't running: another program is using port 8788"), (lambda d, m: m.setattr("launch.engine_binary", lambda: None), "✗ Engine not installed -> ghost update"), (lambda d, m: m.setattr("spend._entries", [(time.time(), 6.0)]), "✗ Spending $6.00 of $5.00 in the last hour -> ghost budget 10"), ]) From 260db0c1f8d0248994ae43f179031a6f247ab084 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:20:28 +0000 Subject: [PATCH 2/5] Windows: the one-liner, accents, proxies, interrupted updates --- .gitattributes | 3 + README.md | 2 +- bin/ghost-uninstall | 44 +++++++++---- bin/ghost-update | 1 + bin/windows/ghost-uninstall.ps1 | 37 +++++++---- bin/windows/ghost-update.ps1 | 17 +++++- install.ps1 | 105 ++++++++++++++++++++++---------- install.sh | 45 ++++++++------ privacy/bridge.py | 7 ++- privacy/doctor.py | 3 +- privacy/ghost_login.py | 23 ++++++- privacy/launch.py | 13 ++-- privacy/localhttp.py | 7 ++- scripts/fork-engine.ps1 | 76 ++++++++++++++--------- scripts/fork-engine.sh | 34 +++++++---- systemd/ghost-bridge.service | 2 +- tests/test_fork_engine.py | 4 +- tests/test_install.py | 5 +- tests/test_login.py | 18 ++++-- 19 files changed, 309 insertions(+), 137 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1a8b70c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# The scripts run where they're checked out, also by a git that would rather have CRLF. +* text=auto eol=lf +*.gif binary diff --git a/README.md b/README.md index 929e845..efba9f2 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ The first run asks how you want to log in. Nothing is contacted before that. | **DreamFort account** | Your plan and credits. ghost shows a code, you type it on [dreamfort.ai](https://www.dreamfort.ai), done. Works over SSH too. | | **DreamFort API key** | Billed by usage. Create one at [api.dreamfort.ai](https://api.dreamfort.ai/api-keys) and paste it. | -`ghost login` switches between them. In a script or a container: `ghost-login --with-api-key < keyfile`. +`ghost login` switches between them. In a script or a container: `cat keyfile | ghost-login --with-api-key`. ## Everyday commands diff --git a/bin/ghost-uninstall b/bin/ghost-uninstall index 5f5e0d0..b7f68ce 100644 --- a/bin/ghost-uninstall +++ b/bin/ghost-uninstall @@ -5,6 +5,7 @@ # ghost uninstall --yes don't ask (your data is kept) # ghost uninstall --purge delete your data too set -uo pipefail +unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_COMMON_DIR GIT_OBJECT_DIRECTORY GIT_NAMESPACE # some other repository's GHOST_HOME=__GHOST_HOME__ ENG=__ENG__ @@ -39,8 +40,9 @@ if ! ours_home "$GHOST_HOME"; then exit 0 fi -open="$( (ps axww -o pid=,command= 2>/dev/null || true) | awk -v e="$ENG" \ - '(index($0, e "/") || index($0, e "\047")) && !/gateway run|process_supervisor/ { print $1 }')" +REAL="$(cd "$ENG" 2>/dev/null && pwd -P || echo "$ENG")" +open="$( (ps axww -o pid=,command= 2>/dev/null || true) | awk -v e="$ENG" -v r="$REAL" \ + '(index($0, e "/") || index($0, e "\047") || index($0, r "/") || index($0, r "\047")) && !/gateway run|process_supervisor/ { print $1 }')" if [ -n "$open" ] && [ -z "${GHOST_FORCE:-}" ]; then echo "ghost is open (pid $(echo $open)). Close those windows and run this again." >&2 exit 1 @@ -53,13 +55,20 @@ if [ -z "$YES" ]; then fi echo "Stopping ghost" +UNIT="$HOME/Library/LaunchAgents/ai.hermes.gateway-uncensored.plist" +[ -f "$UNIT" ] || UNIT="$HOME/.config/systemd/user/hermes-gateway-uncensored.service" +GATEWAY=""; if [ -f "$UNIT" ] && grep -qF -e "$ENG/" -e "$GHOST_HOME/" "$UNIT"; then GATEWAY=1; fi if [ -x "$ENG/.hermes/bin/hermes" ]; then - HERMES_HOME="$GHOST_HOME" "$ENG/.hermes/bin/hermes" -p uncensored gateway stop /dev/null 2>&1 - UNIT="$HOME/Library/LaunchAgents/ai.hermes.gateway-uncensored.plist" - [ -f "$UNIT" ] || UNIT="$HOME/.config/systemd/user/hermes-gateway-uncensored.service" - if [ -f "$UNIT" ] && grep -qF -e "$ENG/" -e "$GHOST_HOME/" "$UNIT"; then - HERMES_HOME="$GHOST_HOME" "$ENG/.hermes/bin/hermes" -p uncensored gateway uninstall /dev/null 2>&1 - fi + engine() { HERMES_HOME="$GHOST_HOME" "$ENG/.hermes/bin/hermes" -p uncensored "$@" /dev/null 2>&1; } + engine gateway stop --yes || engine gateway stop + [ -z "$GATEWAY" ] || engine gateway uninstall +fi +if [ -n "$GATEWAY" ] && [ -f "$UNIT" ]; then # (the engine couldn't) + case "$UNIT" in + *.plist) launchctl bootout "gui/$(id -u)/ai.hermes.gateway-uncensored" >/dev/null 2>&1 ;; + *) systemctl --user disable --now hermes-gateway-uncensored.service >/dev/null 2>&1 ;; + esac + rm -f "$UNIT" fi if [ "$(uname -s)" = Darwin ]; then for label in ai.dreamfort.ghost com.advait.hermes-pii-scrubber com.advait.hermes-veil; do @@ -76,13 +85,19 @@ else systemctl --user daemon-reload >/dev/null 2>&1 fi # One `ghost` started itself, where there is no service manager. -pid="$(curl -s -D - -o /dev/null --max-time 2 http://127.0.0.1:8788/healthz | tr -d '\r' | sed -n 's/^X-Ghost-Pid: \([0-9]*\)$/\1/p')" +pid="$(curl --noproxy '*' -s -D - -o /dev/null --max-time 2 http://127.0.0.1:8788/healthz | tr -d '\r' | sed -n 's/^X-Ghost-Pid: \([0-9]*\)$/\1/p')" if [ -n "$pid" ]; then case "$(ps -ww -o command= -p "$pid" 2>/dev/null || tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null)" in *"$GHOST_HOME/privacy/"*) kill "$pid" 2>/dev/null ;; esac fi +if [ "$(uname -s)" = Darwin ]; then # the gateway a chat started leaves its entry behind + for label in $(launchctl list | awk '/com[.]nousresearch[.]hermes[.]runtime[.]/ { print $3 }'); do + case "$(launchctl print "gui/$(id -u)/$label" 2>/dev/null)" in *"path = $GHOST_HOME/"*) launchctl bootout "gui/$(id -u)/$label" >/dev/null 2>&1 ;; esac + done +fi + echo "Removing files" for dir in "$ENG" "$ENG.old" "$ENG.new"; do if [ -d "$dir" ]; then @@ -100,15 +115,20 @@ for rc in "${ZDOTDIR:-$HOME}/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOM done rm -f "${XDG_CONFIG_HOME:-$HOME/.config}/fish/conf.d/ghost.fish" if [ "$SRC" = "$HOME/.ghost-src" ] && [ -d "$SRC/.git" ]; then - if [ -z "$(git -C "$SRC" status --porcelain 2>/dev/null)" ]; then rm -rf "$SRC"; else echo " left $SRC (it has changes of yours)"; fi + yours() { git -C "$SRC" status --porcelain; git -C "$SRC" stash list; git -C "$SRC" log --oneline --branches --not --remotes; } + if [ -z "$(yours 2>/dev/null)" ]; then rm -rf "$SRC"; else echo " left $SRC (it has changes of yours)"; fi fi +[ ! -e "$GHOST_HOME/.linger" ] || loginctl disable-linger "$(id -un)" >/dev/null 2>&1 +! grep -qs GHOST_LOCAL "$GHOST_HOME/.install-env" || echo " left the offline model in Ollama (ollama rm ghost-tool uncensored-local)" if [ -n "$PURGE" ]; then rm -f "${OG_VEIL_HOME:-$HOME/.opengradient/veil}/session.json" - rm -rf "$GHOST_HOME" + find "$GHOST_HOME" -mindepth 1 -maxdepth 1 ! -name config -exec rm -rf {} + # (the Ghost blog's command keeps its own file there) + rmdir "$GHOST_HOME" 2>/dev/null + [ -d "$HOME/.hermes" ] || rm -rf "$HOME/.local/state/hermes/gateway-locks"; rmdir "$HOME/.local/state/hermes" 2>/dev/null echo "ghost and all of its data are gone." else for dir in venv tools installs cache python uv privacy/__pycache__; do rm -rf "${GHOST_HOME:?}/$dir"; done - rm -f "$GHOST_HOME/.src" "$GHOST_HOME/.install-env" "$GHOST_HOME/install.log" "$GHOST_HOME"/privacy/*.py \ + rm -f "$GHOST_HOME/.src" "$GHOST_HOME/.install-env" "$GHOST_HOME/.linger" "$GHOST_HOME/install.log" "$GHOST_HOME"/privacy/*.py \ "$GHOST_HOME/privacy/uncensored_prefill.json" "$GHOST_HOME/privacy/bridge.key" "$GHOST_HOME"/privacy/bridge.log* echo "ghost is gone. Your chats, skills, settings and login are still in $GHOST_HOME (delete it to remove them too)." fi diff --git a/bin/ghost-update b/bin/ghost-update index 25cb6c3..a64688c 100644 --- a/bin/ghost-update +++ b/bin/ghost-update @@ -4,6 +4,7 @@ # The Hermes release the engine is built on is pinned in the source (engine.pin), so a newer engine arrives # here too, once ghost's patches have been checked against it. set -e +unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_COMMON_DIR GIT_OBJECT_DIRECTORY GIT_NAMESPACE # some other repository's export GHOST_HOME=__GHOST_HOME__ GHOST_ENGINE=__ENG__ # The source you installed from, or ghost's own copy. diff --git a/bin/windows/ghost-uninstall.ps1 b/bin/windows/ghost-uninstall.ps1 index 8dee2a7..8cb9517 100644 --- a/bin/windows/ghost-uninstall.ps1 +++ b/bin/windows/ghost-uninstall.ps1 @@ -5,6 +5,8 @@ # ghost uninstall --purge delete your data too param([switch]$y, [Parameter(ValueFromRemainingArguments = $true)][string[]]$Flags) $ErrorActionPreference = "SilentlyContinue" +$env:PSModulePath = [Environment]::GetEnvironmentVariable("PSModulePath", "Machine") # PowerShell 7's, if that's where you are +Remove-Item Env:GIT_DIR, Env:GIT_WORK_TREE # some other repository's $GhostHome = "__GHOST_HOME__" $Eng = "__ENG__" $BinDir = Split-Path -Parent $MyInvocation.MyCommand.Path @@ -35,39 +37,45 @@ if (-not ($y -or $Flags -contains "--yes")) { } Write-Host "Stopping ghost" -$gateway = Get-ScheduledTask -TaskName "Hermes_Gateway_uncensored" +$startup = "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\Hermes_Gateway_uncensored.vbs" # (or it's a task) +$gateway = (Get-ScheduledTask -TaskName "Hermes_Gateway_uncensored") -or (Test-Path $startup) +$env:HERMES_NONINTERACTIVE = "1" $engine = @("$Eng\.hermes\bin\hermes.exe", "$Eng\.hermes\bin\hermes.cmd") | Where-Object { Test-Path $_ } | Select-Object -First 1 if ($engine) { $env:HERMES_HOME = $GhostHome - & $engine -p uncensored gateway stop 2>&1 | Out-Null + & $engine -p uncensored gateway stop --yes 2>&1 | Out-Null if ($gateway) { & $engine -p uncensored gateway uninstall 2>&1 | Out-Null } } +if ((Test-Path $startup) -and [IO.File]::ReadAllText($startup).Contains("\.ghost\")) { Remove-Item -Force $startup } # (the engine couldn't) foreach ($task in "ghost-bridge", "ghost-scrubber", "ghost-veil") { Stop-ScheduledTask -TaskName $task Unregister-ScheduledTask -TaskName $task -Confirm:$false } -Get-CimInstance Win32_Process | Where-Object { - $_.ProcessId -ne $PID -and $_.CommandLine -and $_.Name -match '^(python|hermes)' -and - ($_.CommandLine.Contains("$GhostHome\") -or $_.CommandLine.Contains("$Eng\") -or $_.CommandLine.Contains($Eng.Replace('\', '\\'))) +Get-CimInstance Win32_Process | Where-Object { # whatever runs from ghost's folders: Python, Node, its browser + $_.ProcessId -ne $PID -and ("$($_.ExecutablePath)".StartsWith("$GhostHome\") -or "$($_.ExecutablePath)".StartsWith("$Eng\") -or + ($_.Name -match '^(python|hermes)' -and $_.CommandLine -and + ($_.CommandLine.Contains("$GhostHome\") -or $_.CommandLine.Contains("$Eng\") -or $_.CommandLine.Contains($Eng.Replace('\', '\\'))))) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force } Start-Sleep -Seconds 1 +# Antivirus may hold a file for a moment. +function Remove-Hard($path) { for ($i = 0; $i -lt 5 -and (Test-Path $path); $i++) { if ($i) { Start-Sleep -Seconds 1 }; Remove-Item -Recurse -Force $path } } Write-Host "Removing files" foreach ($dir in $Eng, "$Eng.old", "$Eng.new") { if (-not (Test-Path $dir)) { continue } - if (Test-OurEngine $dir) { Remove-Item -Recurse -Force $dir } else { Write-Host " left $dir (not an engine ghost built)" } + if (Test-OurEngine $dir) { Remove-Hard $dir } else { Write-Host " left $dir (not an engine ghost built)" } } $src = [IO.File]::ReadAllText("$GhostHome\.src").Trim() if ($src -eq "$env:USERPROFILE\.ghost-src" -and (Test-Path "$src\.git")) { - if (git -C $src status --porcelain) { Write-Host " left $src (it has changes of yours)" } else { Remove-Item -Recurse -Force $src } + if ((git -C $src status --porcelain) -or (git -C $src stash list) -or (git -C $src log --oneline --branches --not --remotes)) { Write-Host " left $src (it has changes of yours)" } else { Remove-Item -Recurse -Force $src } } if ($purge) { Remove-Item "$env:USERPROFILE\.opengradient\veil\session.json" - Remove-Item -Recurse -Force $GhostHome - Write-Host "ghost and all of its data are gone." + Get-ChildItem -Force $GhostHome | Where-Object { $_.Name -ne "config" } | ForEach-Object { Remove-Hard $_.FullName } # (the Ghost blog's command keeps its own file there) + if (-not (Get-ChildItem -Force $GhostHome)) { Remove-Item -Force $GhostHome } } else { foreach ($name in "venv", "tools", "installs", "cache", "python", "uv", "privacy\__pycache__", "privacy\*.py", "privacy\uncensored_prefill.json", - "privacy\bridge.key", "privacy\bridge.log*", ".src", ".install-env", ".installing") { Remove-Item -Recurse -Force "$GhostHome\$name" } + "privacy\bridge.key", "privacy\bridge.log*", ".src", ".install-env", ".installing") { Remove-Hard "$GhostHome\$name" } Write-Host "ghost is gone. Your chats, skills, settings and login are still in $GhostHome (delete it to remove them too)." } foreach ($name in "ghost.cmd", "ghost-login.cmd", "ghost-update.cmd", "ghost-update.ps1", "ghost-uninstall.cmd", "ghost-uninstall.ps1") { @@ -75,7 +83,12 @@ foreach ($name in "ghost.cmd", "ghost-login.cmd", "ghost-update.cmd", "ghost-upd } if (-not (Get-ChildItem -Force $BinDir)) { # nothing else of yours in there Remove-Item -Force $BinDir - $path = [Environment]::GetEnvironmentVariable("Path", "User") - [Environment]::SetEnvironmentVariable("Path", (($path -split ";" | Where-Object { $_ -and $_ -ne $BinDir }) -join ";"), "User") + if (-not (Get-ChildItem -Force (Split-Path $BinDir))) { Remove-Item -Force (Split-Path $BinDir) } + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Environment", $true) + $path = $key.GetValue("Path", "", "DoNotExpandEnvironmentNames") + $key.SetValue("Path", (($path -split ";" | Where-Object { $_ -and $_ -ne $BinDir }) -join ";"), "ExpandString"); $key.Close() } +$left = @($Eng, "$env:USERPROFILE\.ghost-src", $(if ($purge) { $GhostHome }), "$GhostHome\venv", "$GhostHome\tools") | Where-Object { $_ -and (Test-Path $_) -and -not ($_ -eq $GhostHome -and (Test-Path "$GhostHome\config")) } +if ($left) { Write-Host "Something is still using these, so delete them yourself once it's closed: $($left -join ', ')"; exit 1 } +if ($purge) { Write-Host "ghost and all of its data are gone." } exit 0 diff --git a/bin/windows/ghost-update.ps1 b/bin/windows/ghost-update.ps1 index dd74523..321b225 100644 --- a/bin/windows/ghost-update.ps1 +++ b/bin/windows/ghost-update.ps1 @@ -1,5 +1,16 @@ # ghost-update -- get the latest ghost and install it, with the options you chose the first time (`ghost update`). $ErrorActionPreference = "Stop" +$env:PSModulePath = [Environment]::GetEnvironmentVariable("PSModulePath", "Machine") # PowerShell 7's, if that's where you are +Remove-Item Env:GIT_DIR, Env:GIT_WORK_TREE -ErrorAction SilentlyContinue # some other repository's +# git and the engine's installer read only the environment; this also follows a company's PAC script. +if (-not $env:HTTPS_PROXY) { + try { + $to = [Uri]"https://github.com/"; $by = [Net.WebRequest]::GetSystemWebProxy().GetProxy($to) + if ($by -and $by.AbsoluteUri -ne $to.AbsoluteUri) { $env:HTTPS_PROXY = $env:HTTP_PROXY = $by.AbsoluteUri.TrimEnd("/"); $env:NO_PROXY = "127.0.0.1,localhost" } + } catch {} +} +# A network that inspects TLS has a certificate only Windows knows, and git may be using a list of its own. +function Git-Net { & git @args; if ($LASTEXITCODE) { & git -c http.sslBackend=schannel -c http.schannelCheckRevoke=false @args } } function Check($what) { if ($LASTEXITCODE -ne 0) { throw "$what failed (exit code $LASTEXITCODE)" } } # The source you installed from, or ghost's own copy. @@ -9,13 +20,13 @@ if (-not (Test-Path "$src\.git")) { $src = $managed } if (-not (Test-Path "$src\.git")) { if (Test-Path $src) { Remove-Item -Recurse -Force $src } - git clone --quiet https://github.com/OpenGradient/ghost.git $src; Check "git clone" + Git-Net clone --quiet https://github.com/OpenGradient/ghost.git $src; Check "git clone" } elseif ($src -eq $managed) { # always the released branch, whatever was checked out before - git -C $src fetch --quiet origin main; Check "git fetch" + Git-Net -C $src fetch --quiet origin main; Check "git fetch" git -C $src checkout --quiet main; Check "git checkout (does $src have changes of yours in it?)" git -C $src merge --quiet --ff-only origin/main; Check "git merge (does $src have changes of yours in it?)" } else { - git -C $src pull --quiet --ff-only; Check "git pull" + Git-Net -C $src pull --quiet --ff-only; Check "git pull" } & powershell -ExecutionPolicy Bypass -NoProfile -File "$src\install.ps1" exit $LASTEXITCODE diff --git a/install.ps1 b/install.ps1 index 1289cd1..af33829 100644 --- a/install.ps1 +++ b/install.ps1 @@ -11,8 +11,47 @@ # Options: -Local (an offline model too; needs Ollama), -NoBrowser (skip Chromium and the computer-use driver). # `ghost update` remembers them. param([switch]$Local, [switch]$NoBrowser) + +# Run as `irm | iex` there is no checkout: get one, and carry on from there. That is your own session, so nothing is +# set in it, and nothing exits. +if (-not $PSScriptRoot -or -not (Test-Path "$PSScriptRoot\profile\config.yaml")) { + & { + param($Options) + $ErrorActionPreference = "Stop" + if (-not (Get-Command git -ErrorAction SilentlyContinue)) { throw "ghost needs git: install Git for Windows (https://git-scm.com/download/win), then run this again." } + $saved = @{}; foreach ($v in "HTTPS_PROXY", "HTTP_PROXY", "NO_PROXY", "GIT_DIR", "GIT_WORK_TREE") { $saved[$v] = [Environment]::GetEnvironmentVariable($v) } + try { + Remove-Item Env:GIT_DIR, Env:GIT_WORK_TREE -ErrorAction SilentlyContinue # some other repository's + # git and the engine's installer read only the environment; this also follows a company's PAC script. + if (-not $env:HTTPS_PROXY) { + try { + $to = [Uri]"https://github.com/"; $by = [Net.WebRequest]::GetSystemWebProxy().GetProxy($to) + if ($by -and $by.AbsoluteUri -ne $to.AbsoluteUri) { $env:HTTPS_PROXY = $env:HTTP_PROXY = $by.AbsoluteUri.TrimEnd("/"); $env:NO_PROXY = "127.0.0.1,localhost" } + } catch {} + } + # A network that inspects TLS has a certificate only Windows knows, and git may be using a list of its own. + function Git-Net { & git @args; if ($LASTEXITCODE) { & git -c http.sslBackend=schannel -c http.schannelCheckRevoke=false @args } } + $src = "$env:USERPROFILE\.ghost-src" + if (Test-Path "$src\.git") { # always the released branch, whatever was checked out before + Git-Net -C $src fetch --quiet origin main + if ($LASTEXITCODE) { throw "couldn't get the latest ghost from github.com. Check your connection, then run this again." } + git -C $src checkout --quiet main; if (-not $LASTEXITCODE) { git -C $src merge --quiet --ff-only origin/main } + if ($LASTEXITCODE) { throw "Your copy of ghost in $src has changes of yours in it. Set them aside (git -C $src stash) and run this again." } + } else { + if (Test-Path $src) { Remove-Item -Recurse -Force $src } + Git-Net clone --quiet https://github.com/OpenGradient/ghost.git $src + if ($LASTEXITCODE) { throw "couldn't get ghost from github.com. Check your connection, then run this again." } + } + & powershell -ExecutionPolicy Bypass -NoProfile -File "$src\install.ps1" @Options + if ($LASTEXITCODE) { throw "ghost was not installed; the reason is above." } + } finally { foreach ($v in $saved.Keys) { [Environment]::SetEnvironmentVariable($v, $saved[$v]) } } + } (@(if ($Local) { "-Local" }; if ($NoBrowser) { "-NoBrowser" })) + return +} +$Repo = $PSScriptRoot $ErrorActionPreference = "Stop" $ProgressPreference = "SilentlyContinue" +foreach ($v in "GIT_DIR", "GIT_WORK_TREE", "PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV") { Remove-Item "Env:$v" -ErrorAction SilentlyContinue } $GhostHome = "$env:USERPROFILE\.ghost" $Eng = "$env:USERPROFILE\.ghost-engine" @@ -29,22 +68,9 @@ function Check($what) { if ($LASTEXITCODE -ne 0) { throw "$what failed (exit cod # (what the machine is, not this PowerShell) $arch = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -ErrorAction SilentlyContinue).PROCESSOR_ARCHITECTURE if ($arch -eq "ARM64") { throw "ghost doesn't run on Windows on ARM yet. It does in WSL2 there (https://learn.microsoft.com/windows/wsl/install): use the Linux command." } - -# Run as `irm | iex` there is no checkout: get one, and carry on from there. -$Repo = if ($PSScriptRoot) { $PSScriptRoot } else { "" } -if (-not $Repo -or -not (Test-Path "$Repo\profile\config.yaml")) { - if (-not (Have git)) { throw "ghost needs git: install Git for Windows (https://git-scm.com/download/win), then run this again." } - $Src = "$env:USERPROFILE\.ghost-src" - if (Test-Path "$Src\.git") { # always the released branch, whatever was checked out before - git -C $Src fetch --quiet origin main; Check "git fetch" - git -C $Src checkout --quiet main; Check "git checkout (does $Src have changes of yours in it?)" - git -C $Src merge --quiet --ff-only origin/main; Check "git merge (does $Src have changes of yours in it?)" - } else { - if (Test-Path $Src) { Remove-Item -Recurse -Force $Src } - git clone --quiet https://github.com/OpenGradient/ghost.git $Src; Check "git clone" - } - & powershell -ExecutionPolicy Bypass -NoProfile -File "$Src\install.ps1" @PSBoundParameters - exit $LASTEXITCODE +if (-not (Have git)) { throw "ghost needs git: install Git for Windows (https://git-scm.com/download/win), then run this again." } +if (-not $env:CI -and ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + Write-Host " This is an administrator window. ghost needs none: use it from an ordinary one, where its background process is yours." -ForegroundColor Yellow } # --- options: what was asked for now, or last time ------------------------------------------- @@ -63,13 +89,19 @@ Say "Checking this machine" New-Item -ItemType Directory -Force -Path $GhostHome | Out-Null try { $lock = [IO.File]::Open("$GhostHome\.installing", "OpenOrCreate", "ReadWrite", "None") } catch { throw "ghost is already being installed or updated. Wait for that to finish." } -trap { $lock.Dispose(); break } +trap { if ($lock) { $lock.Dispose() }; break } & "$Repo\scripts\fork-engine.ps1" -Eng $Eng -GhostHome $GhostHome -Check # nothing changes under an open ghost # What ghost brings stays in its own folder: uv, the Pythons it fetches, and their cache. uv is ours, because one you # have may be too old; it trusts the certificates the system trusts, as a company network may have one of its own. $env:UV_CACHE_DIR = "$GhostHome\cache\uv"; $env:UV_PYTHON_INSTALL_DIR = "$GhostHome\python" $env:UV_SYSTEM_CERTS = "1"; $env:UV_NATIVE_TLS = "1" -foreach ($v in "PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV") { Remove-Item "Env:$v" -ErrorAction SilentlyContinue } +# git and the engine's installer read only the environment; this also follows a company's PAC script. +if (-not $env:HTTPS_PROXY) { + try { + $to = [Uri]"https://github.com/"; $by = [Net.WebRequest]::GetSystemWebProxy().GetProxy($to) + if ($by -and $by.AbsoluteUri -ne $to.AbsoluteUri) { $env:HTTPS_PROXY = $env:HTTP_PROXY = $by.AbsoluteUri.TrimEnd("/"); $env:NO_PROXY = "127.0.0.1,localhost" } + } catch {} +} $UvVersion = "0.13.10"; $Uv = "$GhostHome\uv\uv.exe" if (-not ((Test-Path $Uv) -and "$(& $Uv --version)".StartsWith("uv $UvVersion"))) { $env:UV_UNMANAGED_INSTALL = "$GhostHome\uv" @@ -93,7 +125,6 @@ foreach ($task in "ghost-bridge", "ghost-scrubber", "ghost-veil") { Stop-Schedul Get-CimInstance Win32_Process -Filter "Name LIKE 'python%'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and ($_.CommandLine.Contains("$Priv\bridge.py") -or $_.CommandLine.Contains("$Priv\scrubbing_proxy.py") -or $_.CommandLine.Contains("-m veil serve --foreground --skip-setup --port 11435")) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } -foreach ($task in "ghost-scrubber", "ghost-veil") { Unregister-ScheduledTask -TaskName $task -Confirm:$false -ErrorAction SilentlyContinue } # older releases' $env:UV_PROJECT_ENVIRONMENT = $Venv Push-Location $Repo @@ -104,10 +135,18 @@ Remove-Item Env:UV_PROJECT_ENVIRONMENT if (Test-Path "$Priv\.scrub") { # someone relied on it: say so rather than let them find out Write-Host " Redaction was removed. What you send is sealed to a TEE enclave, but no longer redacted first." } -foreach ($old in "scrubbing_proxy.py", "presidio_scrub.py", "scrub_patterns.py", "ensure_scrubber_route.py", ".scrub", ".no_scrub", - ".full_redaction", ".presidio", ".presidio_failed", ".pass_paths", ".proxy") { Remove-Item "$Priv\$old" -ErrorAction SilentlyContinue } Copy-Item "$Repo\privacy\*.py" $Priv -Force Copy-Item "$Repo\profile\uncensored_prefill.json" $Priv -Force +function Install-Command($name) { + # Your folder by its variable: these files are read in a code page your name may not be in. + $you = if ($name.EndsWith(".cmd")) { "%USERPROFILE%" } else { '$env:USERPROFILE' } + $text = [IO.File]::ReadAllText("$Repo\bin\windows\$name") + foreach ($path in @(("__PYTHON__", $Py), ("__GHOST_HOME__", $GhostHome), ("__ENG__", $Eng))) { + $text = $text.Replace($path[0], $path[1].Replace($env:USERPROFILE, $you)) + } + Write-Text "$BinDir\$name" ($text -replace "`r?`n", "`r`n") # cmd misreads labels in files with bare newlines +} +"ghost-uninstall.cmd", "ghost-uninstall.ps1" | ForEach-Object { Install-Command $_ } # the way out, should a later step fail # --- 3. the engine --------------------------------------------------------------------------- Say "Setting up the engine (a few minutes the first time)" @@ -155,21 +194,23 @@ try { } catch { Write-Host " Task Scheduler refused it ($($_.Exception.Message.Trim())), so ghost starts it when needed." } $why = & $Py -Es -c "import sys; sys.path.insert(0, sys.argv[1]); import launch; print('' if launch.ensure_bridge() else launch.bridge_problem())" $Priv if ("$why".Trim() -or $LASTEXITCODE -ne 0) { throw "ghost's background service isn't running: $why" } +foreach ($task in "ghost-scrubber", "ghost-veil") { Unregister-ScheduledTask -TaskName $task -Confirm:$false -ErrorAction SilentlyContinue } # older releases' +foreach ($old in "scrubbing_proxy.py", "presidio_scrub.py", "scrub_patterns.py", "ensure_scrubber_route.py", ".scrub", ".no_scrub", + ".full_redaction", ".presidio", ".presidio_failed", ".pass_paths", ".proxy") { Remove-Item "$Priv\$old" -ErrorAction SilentlyContinue } # --- 7. the commands ------------------------------------------------------------------------- Say "Installing the ghost command" -foreach ($name in "ghost.cmd", "ghost-login.cmd", "ghost-update.cmd", "ghost-update.ps1", "ghost-uninstall.cmd", "ghost-uninstall.ps1") { - # Your folder by its variable: these files are read in a code page your name may not be in. - $you = if ($name.EndsWith(".cmd")) { "%USERPROFILE%" } else { '$env:USERPROFILE' } - $text = [IO.File]::ReadAllText("$Repo\bin\windows\$name") - foreach ($path in @(("__PYTHON__", $Py), ("__GHOST_HOME__", $GhostHome), ("__ENG__", $Eng))) { - $text = $text.Replace($path[0], $path[1].Replace($env:USERPROFILE, $you)) - } - Write-Text "$BinDir\$name" ($text -replace "`r?`n", "`r`n") # cmd misreads labels in files with bare newlines -} +"ghost.cmd", "ghost-login.cmd", "ghost-update.cmd", "ghost-update.ps1" | ForEach-Object { Install-Command $_ } & "$Repo\scripts\fork-engine.ps1" -Eng $Eng -GhostHome $GhostHome -RefreshGateway -$userPath = [Environment]::GetEnvironmentVariable("Path", "User") -if ("$userPath" -notlike "*$BinDir*") { [Environment]::SetEnvironmentVariable("Path", "$BinDir;$userPath", "User") } +$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Environment", $true) # (with its variables left as they are) +$userPath = $key.GetValue("Path", "", "DoNotExpandEnvironmentNames") +if (($userPath -split ";") -notcontains $BinDir -and ($userPath -split ";") -notcontains "%USERPROFILE%\.local\bin") { + $key.SetValue("Path", "$BinDir;$userPath", "ExpandString") + [Environment]::SetEnvironmentVariable("GHOST_PATH_SET", $null, "User") # tells the open windows that something changed +} +$key.Close() +$other = Get-Command ghost -CommandType Application -ErrorAction SilentlyContinue | Where-Object { (Split-Path $_.Source) -ne $BinDir } | Select-Object -First 1 +if ($other) { Write-Host " Another program called ghost is on your PATH ($($other.Source)). This one is $BinDir\ghost.cmd." } $who = & $Py -Es "$Priv\ghost_login.py" --status if ($LASTEXITCODE -eq 0) { Say "ghost is ready. $who." } else { Say "ghost is ready. It asks you to log in the first time." } diff --git a/install.sh b/install.sh index 2406bcc..0a6d929 100755 --- a/install.sh +++ b/install.sh @@ -13,6 +13,7 @@ # GHOST_NO_BROWSER=1 skip Chromium and the computer-use driver (a smaller, faster install) # GHOST_VERBOSE=1 show everything as it runs, instead of keeping it in ~/.ghost/install.log set -euo pipefail +unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_COMMON_DIR GIT_OBJECT_DIRECTORY GIT_NAMESPACE # some other repository's main() { OS="$(uname -s)" @@ -168,7 +169,7 @@ on_exit() { printf ' %s✗%s %s\n\n' "$RED" "$OFF" "$STEP" >&3 [ "$code" -ne 130 ] || { printf ' Stopped. Run the installer again to carry on.\n\n' >&3; return 0; } if [ -z "${GHOST_VERBOSE:-}" ]; then - tail -n 15 "$LOG" | sed 's/^/ /' >&3 + { grep -E '^ *(✗|!!|error:|ERROR)' "$LOG" | tail -n 3 || true; tail -n 15 "$LOG"; } | awk '!seen[$0]++' | sed 's/^/ /' >&3 printf '\n The whole log is in %s\n' "$LOG" >&3 fi printf ' Nothing is half-installed: run the installer again once that is fixed.\n\n' >&3 @@ -189,6 +190,10 @@ check_machine() { need_git local tool open for tool in curl tar find; do have "$tool" || die "ghost needs $tool: install it with your package manager, then run this again."; done + if [ "$OS" = Darwin ] && [ "$(uname -m)" = x86_64 ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" != 1 ] \ + && [ ! -d "$ENG" ] && ! { have cargo && ls -d /usr/local/opt/openssl@3 >/dev/null 2>&1; }; then # (the engine's cryptography) + die "ghost needs two things on an Intel Mac, to build a part that has no Intel download any more. First: brew install rust openssl@3" + fi case "$(ldd --version 2>&1 || true)" in *musl*) die "ghost needs a Linux with glibc (Debian, Ubuntu, Fedora, Arch, ...). This one uses musl, as Alpine does." ;; esac if ! open="$(GHOST_ENGINE="$ENG" GHOST_HOME="$GHOST_HOME" bash "$REPO/scripts/fork-engine.sh" --check 2>&1)"; then case "$open" in "!! ghost is open"*) die "${open#!! }" ;; *) echo "$open"; return 1 ;; esac @@ -227,11 +232,9 @@ install_bridge() { if [ -e "$PRIV/.scrub" ]; then # someone relied on it: say so rather than let them find out NOTES+=("Redaction was removed. What you send is sealed to a TEE enclave, but no longer redacted first.") fi - local old # older releases' - for old in scrubbing_proxy.py presidio_scrub.py scrub_patterns.py ensure_scrubber_route.py \ - .scrub .no_scrub .full_redaction .presidio .presidio_failed .pass_paths .proxy; do rm -f "$PRIV/$old"; done cp "$REPO"/privacy/*.py "$PRIV/" cp "$REPO/profile/uncensored_prefill.json" "$PRIV/" + command_file ghost-uninstall # the way out, should a later step fail } build_engine() { @@ -268,14 +271,14 @@ write_profile() { free_port() { # stopping a service finishes in its own time, and two bridges can't share the port local _ for _ in $(seq 1 50); do - curl -s -o /dev/null --max-time 1 http://127.0.0.1:8788/healthz || return 0 + curl --noproxy '*' -s -o /dev/null --max-time 1 http://127.0.0.1:8788/healthz || return 0 sleep 0.2 done } stop_bridge() { # whichever process holds the port, as it says itself, if it is ours (minimal systems have no `pkill`, nor `ps`) local pid - pid="$(curl -s -D - -o /dev/null --max-time 2 http://127.0.0.1:8788/healthz | tr -d '\r' | sed -n 's/^X-Ghost-Pid: \([0-9]*\)$/\1/p' || true)" + pid="$(curl --noproxy '*' -s -D - -o /dev/null --max-time 2 http://127.0.0.1:8788/healthz | tr -d '\r' | sed -n 's/^X-Ghost-Pid: \([0-9]*\)$/\1/p' || true)" [ -n "$pid" ] || return 0 case "$(ps -ww -o command= -p "$pid" 2>/dev/null || tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null || true)" in *"$PRIV/"*) kill "$pid" || true ;; @@ -296,7 +299,7 @@ start_service() { launchctl bootout "$domain/$label" 2>/dev/null || launchctl unload "$agents/$label.plist" 2>/dev/null || true rm -f "$agents/$label.plist" done - free_port + stop_bridge; free_port fill "$REPO/launchd/ai.dreamfort.ghost.plist" > "$agents/ai.dreamfort.ghost.plist" for _ in 1 2 3 4 5; do ! launchctl bootstrap "$domain" "$agents/ai.dreamfort.ghost.plist" || break @@ -311,34 +314,42 @@ start_service() { rm -f "$units/$unit.service" done fill "$REPO/systemd/ghost-bridge.service" > "$units/ghost-bridge.service" - systemctl --user daemon-reload - systemctl --user enable ghost-bridge.service - systemctl --user restart ghost-bridge.service - loginctl enable-linger "$(id -un)" || true # so it's there after a reboot, before you log in + systemctl --user stop ghost-bridge.service || true + stop_bridge; free_port + { systemctl --user daemon-reload && systemctl --user enable ghost-bridge.service && systemctl --user restart ghost-bridge.service; } \ + || echo "systemd won't have it, so ghost starts it when it's needed" + if [ "$(loginctl show-user "$(id -un)" --property=Linger --value 2>/dev/null)" = no ]; then # so it's there after a reboot, before you log in + loginctl enable-linger "$(id -un)" && : > "$GHOST_HOME/.linger" || true + fi else stop_bridge pkill -f "$PRIV/scrubbing_proxy.py" || true # older releases' bridge and og-veil pkill -f "veil serve --foreground --skip-setup --port 11435" || true free_port fi + local old # what only those ran + for old in scrubbing_proxy.py presidio_scrub.py scrub_patterns.py ensure_scrubber_route.py \ + .scrub .no_scrub .full_redaction .presidio .presidio_failed .pass_paths .proxy; do rm -f "$PRIV/$old"; done local why why="$(GHOST_HOME="$GHOST_HOME" "$PYTHON" -Es -c 'import sys; sys.path.insert(0, sys.argv[1]); import launch print("" if launch.ensure_bridge() else launch.bridge_problem())' "$PRIV")" || why="its log is $PRIV/bridge.log" [ -z "$why" ] || die "ghost's background service isn't running: $why." } +command_file() { + mkdir -p "$BIN" + fill "$REPO/bin/$1" > "$BIN/.$1.new" + chmod +x "$BIN/.$1.new" + mv -f "$BIN/.$1.new" "$BIN/$1" # in one move: `ghost update` is running from one of these +} + install_commands() { local name - mkdir -p "$BIN" if [ -e "$BIN/ghost" ] && ! grep -qsi -e GHOST_HOME -e hermes "$BIN/ghost"; then mv "$BIN/ghost" "$BIN/ghost.other" # (the Ghost blog's command has that name too) NOTES+=("There was another program at $BIN/ghost. It is now $BIN/ghost.other.") fi - for name in ghost ghost-login ghost-update ghost-uninstall; do - fill "$REPO/bin/$name" > "$BIN/.$name.new" - chmod +x "$BIN/.$name.new" - mv -f "$BIN/.$name.new" "$BIN/$name" # in one move: `ghost update` is running from one of these - done + for name in ghost ghost-login ghost-update ghost-uninstall; do command_file "$name"; done add_to_path GHOST_ENGINE="$ENG" GHOST_HOME="$GHOST_HOME" bash "$REPO/scripts/fork-engine.sh" --refresh-gateway } diff --git a/privacy/bridge.py b/privacy/bridge.py index f6b0942..748d1b3 100755 --- a/privacy/bridge.py +++ b/privacy/bridge.py @@ -555,5 +555,10 @@ def _send_stream(self, reply): except OSError: pass spend.prune() + try: + server = LocalServer(LISTEN, Handler) + except OSError as e: + log(f"can't listen on {LISTEN[0]}:{LISTEN[1]}: {e}") + raise SystemExit(1) log(f"bridge up on {LISTEN[0]}:{LISTEN[1]}") - LocalServer(LISTEN, Handler).serve_forever() + server.serve_forever() diff --git a/privacy/doctor.py b/privacy/doctor.py index e2cb3ae..850fe8b 100644 --- a/privacy/doctor.py +++ b/privacy/doctor.py @@ -80,7 +80,8 @@ def spending(): def main(): - color = sys.stdout.isatty() + import ghost_login + color = sys.stdout.isatty() and ghost_login.ansi() def style(text, code): return f"\x1b[{code}m{text}\x1b[0m" if color else text diff --git a/privacy/ghost_login.py b/privacy/ghost_login.py index a8815e3..b1debb8 100644 --- a/privacy/ghost_login.py +++ b/privacy/ghost_login.py @@ -38,7 +38,20 @@ LOCAL = 3 # exit code: they chose the offline model instead of logging in TTY = sys.stdin.isatty() and sys.stdout.isatty() -COLOR = TTY and "NO_COLOR" not in os.environ and os.environ.get("TERM") != "dumb" + + +def ansi(): + """Windows' classic console shows colour codes as they are until it's told otherwise.""" + if os.name != "nt": + return True + import ctypes + kernel32, mode = ctypes.windll.kernel32, ctypes.c_uint32() + kernel32.GetStdHandle.restype = ctypes.c_void_p + handle = ctypes.c_void_p(kernel32.GetStdHandle(-11)) + return bool(kernel32.GetConsoleMode(handle, ctypes.byref(mode)) and kernel32.SetConsoleMode(handle, mode.value | 4)) + + +COLOR = TTY and ansi() and "NO_COLOR" not in os.environ and os.environ.get("TERM") != "dumb" ART = """\ ▄████████████▄ @@ -444,6 +457,12 @@ def check_key(key): return "This key works, but its account has no credits yet." if probe.status_code == 402 else None +def piped_key(raw): + """What a script sent us. (PowerShell writes UTF-16, or a byte-order mark.)""" + text = raw.decode("utf-16" if raw[:2] in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig", "replace") + return next((line.strip() for line in text.replace("\0", "").splitlines() if line.strip()), "") + + def api_key_login(key=None): interactive = key is None if interactive: @@ -520,7 +539,7 @@ def main(argv=None): try: with Keys() as keys: if args.with_api_key: - api_key_login(sys.stdin.readline().strip()) + api_key_login(piped_key(sys.stdin.buffer.readline() if TTY else sys.stdin.buffer.read())) elif args.api_key: api_key_login() elif args.account or args.device or args.browser or args.paste: diff --git a/privacy/launch.py b/privacy/launch.py index 05b75ea..c551f3c 100644 --- a/privacy/launch.py +++ b/privacy/launch.py @@ -167,15 +167,16 @@ def ensure_bridge(): return True if port_taken() and not bridge_up(): return False - if not _start_service(): # no service manager here, or none that has it + for start in (_start_service, _start_process): # no service manager here, or none that has it, or it won't try: - _start_process() + if start() is False: + continue except OSError: return False - for _ in range(60): - time.sleep(0.2) - if bridge_up(): - return True + for _ in range(40): + time.sleep(0.2) + if bridge_up(): + return True return False diff --git a/privacy/localhttp.py b/privacy/localhttp.py index 09ce0bf..284ced8 100644 --- a/privacy/localhttp.py +++ b/privacy/localhttp.py @@ -1,12 +1,17 @@ -"""A localhost HTTP server that answers as soon as it's started.""" +"""A localhost HTTP server that answers as soon as it's started, alone on its port.""" +import os +import socket import socketserver from http.server import ThreadingHTTPServer class LocalServer(ThreadingHTTPServer): daemon_threads = True + allow_reuse_address = os.name != "nt" # there it would let others share the port, under another account too def server_bind(self): + if os.name == "nt": + self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) # The standard one looks up its own name here, before it listens. With slow reverse DNS, as on many a # Mac, that is half a minute of refused connections. socketserver.TCPServer.server_bind(self) diff --git a/scripts/fork-engine.ps1 b/scripts/fork-engine.ps1 index 68b61b9..96e4096 100644 --- a/scripts/fork-engine.ps1 +++ b/scripts/fork-engine.ps1 @@ -70,7 +70,21 @@ function Assert-Closed { $open = @(Get-EngineProcess | Where-Object { $_.CommandLine -notmatch 'gateway run' }) if ($open.Count) { throw "ghost is open (pid $($open.ProcessId -join ', ')). Close those windows and re-run, or set GHOST_FORCE=1." } } -function Get-GatewayTask { Get-ScheduledTask -TaskName "Hermes_Gateway_uncensored" -ErrorAction SilentlyContinue } +$Startup = "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\Hermes_Gateway_uncensored.vbs" +function Test-Gateway { # installed, as a task, or where Task Scheduler wouldn't have it, in the Startup folder + [bool](Get-ScheduledTask -TaskName "Hermes_Gateway_uncensored" -ErrorAction SilentlyContinue) -or + ((Test-Path $Startup) -and [IO.File]::ReadAllText($Startup).Contains("\.ghost\")) +} +$env:HERMES_NONINTERACTIVE = "1" +# Antivirus, or a program that inherited the folder, may hold it for a moment. +function Move-Tree($from, $to) { + for ($i = 1; ; $i++) { try { [IO.Directory]::Move($from, $to); return } catch { if ($i -eq 10) { throw }; Start-Sleep -Milliseconds 500 } } +} +function Restore-Engine { + if (Test-Path $Eng) { Remove-Item -Recurse -Force $Eng -ErrorAction SilentlyContinue } + if (Test-Path $Eng) { Move-Tree $Eng "$Eng.broken-$PID" } + Move-Tree $Old $Eng +} # What this build is made from. The engine there is current if it was made from the same, and still launches. $made = (@("..\engine.pin", "debrand.py", "fork-engine.ps1") | ForEach-Object { [IO.File]::ReadAllText((Join-Path $here $_)) }) -join "" @@ -83,7 +97,7 @@ function Test-Current { if ($Check) { Assert-Closed; return } if ($RefreshGateway) { if (-not (Test-Path $Refresh)) { return } - if (-not (Get-GatewayTask)) { Remove-Item $Refresh; return } + if (-not (Test-Gateway)) { Remove-Item $Refresh; return } if (Launcher) { Write-Host "==> moving the background gateway onto the new engine" $start = if (Test-Path $Restart) { "--start-now" } else { "--no-start-now" } # one you had stopped stays stopped @@ -93,6 +107,8 @@ if ($RefreshGateway) { } return } +# A build that was killed part-way left the engine it was replacing set aside: put that one back first. +if (Test-Path $Old) { if (Test-Launches) { Remove-Item -Recurse -Force $Old } else { Restore-Engine } } if (Test-Current) { Write-Host "==> the engine is already this build: $Eng"; exit 0 } Assert-Closed @@ -102,7 +118,9 @@ if (Test-Path $New) { Remove-Item -Recurse -Force $New } New-Item -ItemType Directory -Force -Path $GhostHome | Out-Null for ($i = 1; $i -le 3; $i++) { # core.longpaths: the tree has paths past MAX_PATH; autocrlf would change every byte the engine's lock hashes. - & git -c advice.detachedHead=false -c core.longpaths=true -c core.autocrlf=false clone --quiet --depth 1 --branch "v$Version" $RepoUrl $New + # (A network that inspects TLS has a certificate only Windows knows, and git may be using a list of its own.) + $tls = if ($i -gt 1) { @("-c", "http.sslBackend=schannel", "-c", "http.schannelCheckRevoke=false") } else { @() } + & git -c advice.detachedHead=false -c core.longpaths=true -c core.autocrlf=false @tls clone --quiet --depth 1 --branch "v$Version" $RepoUrl $New if ($LASTEXITCODE -eq 0) { break } if (Test-Path $New) { Remove-Item -Recurse -Force $New } if ($i -eq 3) { throw "could not fetch $RepoUrl" } @@ -130,27 +148,22 @@ $stamp = [ordered]@{ [IO.File]::WriteAllText("$New\install-stamp.json", ($stamp | ConvertTo-Json) + "`n") # ---------- 3. stop the background gateway, then swap the trees ---------- -# A build that was killed part-way left the engine it was replacing set aside: put that one back first. -if ((Test-Path $Old) -and -not (Test-Launches)) { - if (Test-Path $Eng) { Remove-Item -Recurse -Force $Eng } - Move-Item $Old $Eng -} -if (Test-Path $Old) { Remove-Item -Recurse -Force $Old } - +Assert-Closed # (that took a while) $oldBin = Launcher if (-not $oldBin -and (Test-Path "$Eng\venv\Scripts\hermes.exe")) { $oldBin = "$Eng\venv\Scripts\hermes.exe" } if ($oldBin) { - $task = Get-GatewayTask - if ($task -and ($task.State -eq 'Running' -or (Get-EngineProcess | Where-Object { $_.CommandLine -match 'gateway run' }))) { - New-Item -ItemType File -Force -Path $Restart | Out-Null - } + $running = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -match 'gateway run' -and $_.CommandLine -notmatch 'idle-exit' -and + ($_.CommandLine.Contains("$Eng\") -or $_.CommandLine.Contains("$GhostHome\") -or $_.CommandLine.Contains($Eng.Replace('\', '\\'))) } + if ((Test-Gateway) -and $running) { New-Item -ItemType File -Force -Path $Restart | Out-Null } $env:HERMES_HOME = $GhostHome - Invoke-Quietly { & $oldBin -p uncensored gateway stop } | Out-Null + # (--yes: it won't stop in the middle of something, a cron job say, without being told. Old engines don't know the word.) + Invoke-Quietly { & $oldBin -p uncensored gateway stop --yes; if ($LASTEXITCODE) { & $oldBin -p uncensored gateway stop } } | Out-Null } +$built = $false try { - if (Test-Path $Eng) { Move-Item $Eng $Old } - Move-Item $New $Eng + if (Test-Path $Eng) { Move-Tree $Eng $Old } + Move-Tree $New $Eng # ---------- 4. runtime + launcher ---------- Write-Host "==> installing the engine runtime (Python, Node, ripgrep, locked dependencies)" @@ -169,6 +182,9 @@ try { # Web search is on by default in ghost, so its backend ships rather than installing mid-conversation. & $storePy -m pm.cli install --extra ddgs | Out-Null if ($LASTEXITCODE -ne 0) { throw "could not install the web-search backend" } + # It remembers that you did without these, until they're asked for by name. + $declined = Get-ChildItem "$GhostHome\installs\*\declined-packages.json" -ErrorAction SilentlyContinue | Where-Object { [IO.File]::ReadAllText($_.FullName).Contains("chromium") } + if (-not $env:GHOST_NO_BROWSER -and $declined) { & $storePy -m pm.cli install chromium cua-driver | Out-Null; if ($LASTEXITCODE -ne 0) { throw "could not install the browser" } } } finally { Pop-Location } $mint = Join-Path ([IO.Path]::GetTempPath()) "ghost-mint-$PID.py" @@ -189,23 +205,27 @@ sys.exit(0 if ensure_install_launchers(root, root / ".hermes" / "bin") else "cou $first = @(Invoke-Engine @("--version"))[0] # collected whole: Select-Object -First would cut the process off Write-Host " $first" if (-not "$first".StartsWith("Ghost v$Version")) { throw "expected 'Ghost v$Version'" } -} catch { - if (Test-Path $New) { Remove-Item -Recurse -Force $New } - if (Test-Path $Old) { - if (Test-Path $Eng) { Remove-Item -Recurse -Force $Eng } - Move-Item $Old $Eng - Write-Host "!! engine build failed -- restored the previous engine" - if (Test-Path $Restart) { - $env:HERMES_HOME = $GhostHome - Invoke-Quietly { & $oldBin -p uncensored gateway start } | Out-Null - Remove-Item $Restart -ErrorAction SilentlyContinue + $built = $true +} finally { # (which Ctrl-C reaches too) + if (-not $built) { + if (Test-Path $New) { Remove-Item -Recurse -Force $New -ErrorAction SilentlyContinue } + if (Test-Path $Old) { + Restore-Engine + Write-Host "!! engine build failed -- restored the previous engine" + if (Test-Path $Restart) { + $env:HERMES_HOME = $GhostHome + Invoke-Quietly { & $oldBin -p uncensored gateway start } | Out-Null + Remove-Item $Restart -ErrorAction SilentlyContinue + } } } - throw } New-Item -ItemType File -Force -Path $Refresh | Out-Null [IO.File]::WriteAllText("$Eng\.ghost-recipe", $Recipe) if (Test-Path $Old) { Remove-Item -Recurse -Force $Old -ErrorAction SilentlyContinue } +Push-Location $Eng; $env:HERMES_HOME = $GhostHome +Invoke-Quietly { & $storePy -m pm.cli gc } | Out-Null # drop dependency generations nothing uses any more +Pop-Location Write-Host "==> engine ready: $Eng" exit 0 diff --git a/scripts/fork-engine.sh b/scripts/fork-engine.sh index af2b5cb..c67011f 100755 --- a/scripts/fork-engine.sh +++ b/scripts/fork-engine.sh @@ -41,6 +41,7 @@ service_installed() { [ -f "$UNIT" ] && grep -qF -e "$ENG/" -e "$GHOST_HOME/" "$ # The engine's package manager must see only its own toolchain: install.sh exports # UV_PROJECT_ENVIRONMENT for ghost's privacy venv, and uv would happily sync the engine into it. +unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_COMMON_DIR GIT_OBJECT_DIRECTORY GIT_NAMESPACE # some other repository's unset UV_PROJECT_ENVIRONMENT VIRTUAL_ENV PYTHONHOME PYTHONPATH HERMES_RUNTIME_DIR HERMES_INSTALL_DIR \ HERMES_INSTALL_ROOT HERMES_REVISION HERMES_PROFILE @@ -61,12 +62,12 @@ processes() { # each one's pid, parent and command (minimal systems have no `p } check_closed() { [ -d "$ENG" ] && [ -z "${GHOST_FORCE:-}" ] || return 0 - # Launched by path, or as `python -c "... '' ..."`. What the gateway started isn't a window either, nor is - # the reaper that goes with every engine process. + # Launched by path (through a link, perhaps), or as `python -c "... '' ..."`. What the gateway started isn't a + # window either, nor is the reaper that goes with every engine process. local pids - pids="$( (processes 2>/dev/null || true) | awk -v e="$ENG" -v h="$GHOST_HOME" ' - { parent[$1] = $2; engine[$1] = index($0, e "/") || index($0, e "\047") - gateway[$1] = (engine[$1] || index($0, h "/tools/")) && /gateway run/; reaper[$1] = /process_supervisor[.]sh/ } + pids="$( (processes 2>/dev/null || true) | awk -v e="$ENG" -v r="$(cd "$ENG" && pwd -P)" -v h="$GHOST_HOME/tools/" -v hr="$(cd "$GHOST_HOME" 2>/dev/null && pwd -P)/tools/" ' + { parent[$1] = $2; engine[$1] = index($0, e "/") || index($0, e "\047") || index($0, r "/") || index($0, r "\047") + gateway[$1] = (engine[$1] || index($0, h) || index($0, hr)) && /gateway run/; reaper[$1] = /process_supervisor[.]sh/ } END { for (p in engine) { if (!engine[p] || reaper[p]) continue @@ -101,7 +102,16 @@ case "${1:-}" in "") ;; *) echo "usage: fork-engine.sh [--check | --refresh-gateway]" >&2; exit 2 ;; esac +# A build that was killed part-way left the engine it was replacing set aside: put that one back first. +ours() { [ -f "$1/install-stamp.json" ] || [ -d "$1/hermes_cli" ] || [ -e "$1/venv/bin/hermes" ]; } +if [ -d "$OLD" ] && ours "$OLD"; then + if ! launches >/dev/null 2>&1; then rm -rf "$ENG"; mv "$OLD" "$ENG"; else rm -rf "$OLD"; fi +fi if current; then echo "==> the engine is already this build: $ENG"; exit 0; fi +if [ -e "$ENG" ] && ! ours "$ENG" && [ -n "$(ls -A "$ENG" 2>/dev/null)" ]; then + echo "!! $ENG is there already, and it isn't an engine ghost built. Move it away (or set GHOST_ENGINE) and run this again." >&2 + exit 1 +fi check_closed # ---------- 1. fetch ---------- @@ -156,15 +166,13 @@ cat > "$NEW/install-stamp.json" </dev/null 2>&1; then rm -rf "$ENG"; mv "$OLD" "$ENG"; fi -rm -rf "$OLD" - +check_closed # (that took a while) OLD_BIN="" for bin in "$LAUNCH" "$ENG/venv/bin/hermes"; do [ -x "$bin" ] && { OLD_BIN="$bin"; break; }; done -old_engine() { HERMES_HOME="$GHOST_HOME" "$OLD_BIN" -p uncensored "$@" /dev/null 2>&1 || true; } +old_engine() { HERMES_HOME="$GHOST_HOME" "$OLD_BIN" -p uncensored "$@" /dev/null 2>&1; } if service_installed && service_running; then : > "$RESTART"; fi -[ -z "$OLD_BIN" ] || old_engine gateway stop +# (--yes: it won't stop in the middle of something, a cron job say, without being told. Old engines don't know the word.) +[ -z "$OLD_BIN" ] || old_engine gateway stop --yes || old_engine gateway stop || true rollback() { [ $? -eq 0 ] && return @@ -172,7 +180,7 @@ rollback() { [ -d "$OLD" ] || return 0 rm -rf "$ENG"; mv "$OLD" "$ENG" echo "!! engine build failed -- restored the previous engine" >&2 - if [ -e "$RESTART" ]; then old_engine gateway start; rm -f "$RESTART"; fi + if [ -e "$RESTART" ]; then old_engine gateway start || true; rm -f "$RESTART"; fi } trap rollback EXIT [ ! -d "$ENG" ] || mv "$ENG" "$OLD" @@ -187,6 +195,8 @@ HERMES_HOME="$GHOST_HOME" bash "$ENG/scripts/install.sh" "${flags[@]}" STORE_PY="$(ls -d "$GHOST_HOME"/tools/python-*/bin/python3 2>/dev/null | sort | tail -1)" [ -x "$STORE_PY" ] || { echo "!! the engine's Python was not installed under $GHOST_HOME/tools" >&2; exit 1; } pm() { (cd "$ENG" && HERMES_HOME="$GHOST_HOME" "$STORE_PY" -m pm.cli "$@" /dev/null diff --git a/systemd/ghost-bridge.service b/systemd/ghost-bridge.service index 7ac9f43..f43352c 100644 --- a/systemd/ghost-bridge.service +++ b/systemd/ghost-bridge.service @@ -5,7 +5,7 @@ Description=ghost's local bridge to the TEE gateway (127.0.0.1:8788) Environment="GHOST_HOME=__GHOST_HOME__" ExecStart="__PYTHON__" -Es "__GHOST_HOME__/privacy/bridge.py" Restart=always -RestartSec=2 +RestartSec=5 [Install] WantedBy=default.target diff --git a/tests/test_fork_engine.py b/tests/test_fork_engine.py index 8ab8a75..43b83e0 100644 --- a/tests/test_fork_engine.py +++ b/tests/test_fork_engine.py @@ -129,7 +129,7 @@ def test_upgrade_from_an_older_ghost(box, broken): launcher.chmod(0o755) done = box.run(src=box.source("new", broken=broken)) assert (done.returncode != 0) == broken, done.stderr - assert "old -p uncensored gateway stop" in box.calls() + assert "old -p uncensored gateway stop --yes" in box.calls() assert launcher.exists() == broken and (box.engine / "new").exists() != broken @@ -263,7 +263,7 @@ def test_running_gateway_is_stopped_then_restarted_on_the_new_engine(box): assert box.run(src=box.source("one")).returncode == 0 box.service(running=True) assert box.run(src=box.source("two")).returncode == 0 - assert "-p uncensored gateway stop" in box.calls() and box.restart.exists() + assert "-p uncensored gateway stop --yes" in box.calls() and box.restart.exists() assert box.run("--refresh-gateway").returncode == 0 assert box.calls()[-1] == "-p uncensored gateway install --force --start-now --start-on-login" assert not box.restart.exists() diff --git a/tests/test_install.py b/tests/test_install.py index 7dcff26..9dda1c9 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -142,7 +142,8 @@ def test_a_new_install_contacts_nobody_until_you_log_in(machine): assert (chat.returncode, chat.stdout) == (1, "") and "not logged in. Run: ghost login" in chat.stderr assert m.command("ghost", "--version").stdout == "Ghost v9\n" assert m.command("ghost-login", "--status").returncode == 1 - assert {c for c in m.calls() if c.startswith("curl")} <= {"curl -s -o /dev/null --max-time 1 http://127.0.0.1:8788/healthz", + assert {c for c in m.calls() if c.startswith("curl")} <= {"curl --noproxy * -s -o /dev/null --max-time 1 http://127.0.0.1:8788/healthz", + "curl --noproxy * -s -D - -o /dev/null --max-time 2 http://127.0.0.1:8788/healthz", f"curl -LsSf https://astral.sh/uv/{UV_VERSION}/install.sh"} @@ -427,7 +428,7 @@ def test_uninstall_keeps_your_data(installed): assert not any((m.ghost / name).exists() for name in ("venv", "uv", "python", "cache", ".src", ".installing")) assert {p.name: p.read_text() for p in (m.ghost / "privacy").iterdir()} == kept assert (m.profile / "state.db").read_text() == "chats" and session.exists() and m.repo.exists() - assert "engine -p uncensored gateway stop" in m.calls() + assert "engine -p uncensored gateway stop --yes" in m.calls() back = m.install() # and back again, as you left it assert back.returncode == 0 and "Logged in with your DreamFort API key (df_sk_…abcd)" in back.stdout assert (m.profile / "state.db").read_text() == "chats" and (m.ghost / "privacy" / "budget").read_text() == "20\n" diff --git a/tests/test_login.py b/tests/test_login.py index b63ed72..c0674a5 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -224,8 +224,18 @@ def test_a_damaged_session_file_is_no_login(dream): # ── API key ─────────────────────────────────────────────────────────────────── +def piped(text, encoding="utf-8"): + return io.TextIOWrapper(io.BytesIO(text.encode(encoding))) + + +@pytest.mark.parametrize("encoding", ["utf-16", "utf-8-sig"]) +def test_a_key_file_powershell_wrote(dream, monkeypatch, encoding): + monkeypatch.setattr(sys, "stdin", piped(f"\r\n{GOOD_KEY}\r\n", encoding)) + assert ghost_login.main(["--with-api-key"]) == 0 and ghost_auth.api_key() == GOOD_KEY + + def test_api_key_from_stdin(dream, monkeypatch, capsys): - monkeypatch.setattr(sys, "stdin", io.StringIO(GOOD_KEY + "\n")) + monkeypatch.setattr(sys, "stdin", piped(GOOD_KEY + "\n")) assert ghost_login.main(["--with-api-key"]) == 0 out = capsys.readouterr().out assert "Logged in with your DreamFort API key (df_sk_…1234)" in out and GOOD_KEY not in out @@ -235,14 +245,14 @@ def test_api_key_from_stdin(dream, monkeypatch, capsys): @pytest.mark.parametrize("key, words", [(BAD_KEY, "doesn't accept that key"), ("sk-other", "start with df_sk_"), ("", "start with df_sk_")]) def test_a_key_that_does_not_work_is_not_stored(dream, monkeypatch, capsys, key, words): - monkeypatch.setattr(sys, "stdin", io.StringIO(key + "\n")) + monkeypatch.setattr(sys, "stdin", piped(key + "\n")) assert ghost_login.main(["--with-api-key"]) == 1 assert words in capsys.readouterr().out and ghost_auth.mode() is None def test_a_key_without_credits_says_so(dream, monkeypatch, capsys): dream.credits = False - monkeypatch.setattr(sys, "stdin", io.StringIO(GOOD_KEY)) + monkeypatch.setattr(sys, "stdin", piped(GOOD_KEY)) assert ghost_login.main(["--with-api-key"]) == 0 assert "no credits yet" in capsys.readouterr().out and ghost_auth.mode() == "api_key" @@ -250,7 +260,7 @@ def test_a_key_without_credits_says_so(dream, monkeypatch, capsys): # ── switching, status, logout ───────────────────────────────────────────────── def test_the_last_login_is_the_one_used(dream, monkeypatch): ghost_login.main(["--device"]) - monkeypatch.setattr(sys, "stdin", io.StringIO(GOOD_KEY)) + monkeypatch.setattr(sys, "stdin", piped(GOOD_KEY)) ghost_login.main(["--with-api-key"]) assert ghost_auth.mode() == "api_key" dream.polls_before_approval = 0 From 5dcc90a9ab9b7067b9f012930b89da23cb3ffa7d Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:42:54 +0000 Subject: [PATCH 3/5] Tests: no SIGHUP on Windows --- tests/test_fork_engine.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_fork_engine.py b/tests/test_fork_engine.py index 43b83e0..60ec05c 100644 --- a/tests/test_fork_engine.py +++ b/tests/test_fork_engine.py @@ -198,7 +198,7 @@ def test_what_a_chat_leaves_running_does_not_count_either(box): os.killpg(box.procs[-1].pid, 9) -@pytest.mark.parametrize("stop", [signal.SIGINT, signal.SIGTERM, signal.SIGHUP]) +@pytest.mark.parametrize("stop", ["SIGINT", "SIGTERM", "SIGHUP"]) def test_a_build_that_is_stopped_restores_the_previous_engine(box, stop): """Ctrl-C, a shutdown, or a closed terminal window.""" assert box.run(src=box.source("one")).returncode == 0 @@ -210,7 +210,7 @@ def test_a_build_that_is_stopped_restores_the_previous_engine(box, stop): while not (box.home / "building").exists(): assert time.time() < deadline time.sleep(0.05) - os.killpg(build.pid, stop) + os.killpg(build.pid, getattr(signal, stop)) assert build.wait(timeout=20) == 130 assert (box.engine / "one").exists() and not (box.engine / "two").exists() and not box.old.exists() From cbd491137983869be3ecc9f373440d08c88bdc0d Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:54:57 +0000 Subject: [PATCH 4/5] CI: the commands folder may be gone too --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8c477c6..ff25204 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -87,7 +87,7 @@ jobs: case "$RUNNER_OS" in Windows) cmd //c "$(cygpath -w "$HOME/.local/bin/ghost.cmd")" uninstall --yes ;; *) "$HOME/.local/bin/ghost" uninstall --yes ;; esac sleep 3 test ! -e "$HOME/.ghost-engine"; test ! -e "$HOME/.ghost/venv"; test -e "$HOME/.ghost/profiles/uncensored/config.yaml" - ls "$HOME/.local/bin" | tee left + (ls "$HOME/.local/bin" 2>/dev/null || true) | tee left # (removed too, if it was only ghost's) if grep -q "^ghost" left; then exit 1; fi if curl -fs --max-time 3 http://127.0.0.1:8788/healthz; then exit 1; fi From 64a2b89f506b7b934150fc6e6cf2f00fe2d40de9 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 19:00:03 +0000 Subject: [PATCH 5/5] CI: a slow runner may take a few seconds --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ff25204..21492bf 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -49,7 +49,7 @@ jobs: case "$RUNNER_OS" in Windows) ghost() { cmd //c "$(cygpath -w "$HOME/.local/bin/$1.cmd")" "${@:2}"; } ;; *) ghost() { "$HOME/.local/bin/$1" "${@:2}"; } ;; esac ghost ghost --version | tee version; grep -q "^Ghost v" version curl -fs http://127.0.0.1:8788/healthz - if grep -E "✓ Starting the background service [0-9]+s" "$HOME/install.txt"; then exit 1; fi # it takes a second, not half a minute + if grep -E "✓ Starting the background service [0-9]{2,}s" "$HOME/install.txt"; then exit 1; fi # it takes a moment, not half a minute started=$SECONDS if ghost ghost -z hi out 2>&1; then exit 1; fi cat out; grep -q "not logged in" out; test $((SECONDS - started)) -lt 15