From d1e82f7f193939f0945cfe8fb5750660c58c3a26 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:04:56 +0000 Subject: [PATCH 01/15] 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 02/15] 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 03/15] 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 2853a1de517a9215711b1a372b64c33eecd9b584 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:42:56 +0000 Subject: [PATCH 04/15] Nothing of yours but what you send, and paid for once --- .github/workflows/test.yml | 4 +- README.md | 25 +++--- SECURITY.md | 1 + privacy/bridge.py | 155 +++++++++++++++++++++++++++++++------ privacy/doctor.py | 50 +++++++----- privacy/enclaves.py | 32 ++++---- privacy/ghost_auth.py | 35 ++++++--- privacy/launch.py | 65 ++++++++++++++-- privacy/outbound.py | 60 ++++++++++++-- privacy/spend.py | 9 ++- profile/config.yaml | 27 ++++--- pyproject.toml | 2 +- scripts/debrand.py | 30 +++++++ scripts/write_profile.py | 10 ++- tests/fake_dreamfort.py | 3 +- tests/test_bridge.py | 149 +++++++++++++++++++++++++++++------ tests/test_engine.py | 66 +++++++++++++++- tests/test_install.py | 4 +- tests/test_launch.py | 39 ++++++++-- tests/test_login.py | 15 +++- tests/test_outbound.py | 52 ++++++++++++- uv.lock | 18 ++++- 22 files changed, 702 insertions(+), 149 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8c477c6..e38e3cb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,7 +13,7 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.11" - - run: pip install pytest httpx truststore "opengradient-ohttp>=0.1,<0.2" + - run: pip install pytest "httpx[socks]" truststore "opengradient-ohttp>=0.1,<0.2" - run: pytest tests/ -q # The real thing: install ghost the way a user does, use it before logging in, and check the engine it built. @@ -33,7 +33,7 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.11" - - run: pip install pytest uv httpx truststore "opengradient-ohttp>=0.1,<0.2" + - run: pip install pytest "httpx[socks]" truststore "opengradient-ohttp>=0.1,<0.2" - name: Install ghost if: runner.os != 'Windows' run: set -o pipefail; ./install.sh | tee "$HOME/install.txt" diff --git a/README.md b/README.md index efba9f2..a7f1a9b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-3DDC97?style=flat-square)](LICENSE)  ![Platform](https://img.shields.io/badge/platform-macOS%20%C2%B7%20Linux%20%C2%B7%20Windows-lightgrey?style=flat-square)  [![Built on Hermes Agent](https://img.shields.io/badge/built%20on-Hermes%20Agent-7C5CFF?style=flat-square)](https://github.com/NousResearch/hermes-agent)  ![Open-weight only](https://img.shields.io/badge/models-open--weight%20only-FF8A3D?style=flat-square) -**A private, unrestricted agentic harness.** A real terminal agent that runs commands, edits files, executes code, and searches the web, with every hosted request sealed to OpenGradient's TEE gateway so that nobody on the way can tie what you asked to who you are. It answers what you actually ask, drops to a fully-offline local model on demand, and phones home to no one. +**A private, unrestricted agentic harness.** A real terminal agent that runs commands, edits files, executes code, and searches the web, with every hosted request sealed to OpenGradient's TEE gateway so that nobody on the way can tie what you asked to who you are. It answers what you actually ask, drops to a local model on demand, and phones home to no one. Built on the [Hermes Agent](https://github.com/NousResearch/hermes-agent) engine by Nous Research, wired to OpenGradient's gateway and to only open-weight, unrestricted models. @@ -12,7 +12,7 @@ Built on the [Hermes Agent](https://github.com/NousResearch/hermes-agent) engine ## Install -One command, about two minutes. The only prerequisite is `git`; ghost brings its own Python, Node and engine, and touches nothing else on your machine. +One command, about two minutes and 2.5 GB of disk. The only prerequisite is `git`: ghost brings its own Python, Node and engine, and keeps all of it in `~/.ghost` and `~/.ghost-engine`. Outside those there is only its command in `~/.local/bin` (and a line in your shell's startup file if it didn't look there). **macOS, Linux, WSL2:** @@ -20,7 +20,7 @@ One command, about two minutes. The only prerequisite is `git`; ghost brings its curl -fsSL https://raw.githubusercontent.com/OpenGradient/ghost/main/install.sh | bash ``` -**Windows (PowerShell, no administrator needed):** +**Windows (PowerShell, no administrator needed; on ARM, use WSL2):** ```powershell irm https://raw.githubusercontent.com/OpenGradient/ghost/main/install.ps1 | iex @@ -36,7 +36,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 account** | Your plan and credits. Sign in on [dreamfort.ai](https://www.dreamfort.ai) and ghost picks it up; over SSH, paste what the page shows. | | **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: `cat keyfile | ghost-login --with-api-key`. @@ -47,7 +47,7 @@ The first run asks how you want to log in. Nothing is contacted before that. |---|---| | `ghost` | Start chatting. `ghost -c` continues your last chat. | | `ghost -z "question"` | Ask once and print the answer. | -| `ghost --local` | Use the offline model: nothing leaves this machine. | +| `ghost --local` | Use the offline model: what you type stays on this machine, and the web tools are off. | | `ghost doctor` | Check that everything works, and what to do if it doesn't. | | `ghost usage` / `ghost budget` | What hosted models have cost you, what credits are left, and the hourly limit. | | `ghost login` / `ghost logout` | Change how you're connected. | @@ -64,7 +64,7 @@ Set these as environment variables on the install command (`curl ... | GHOST_LOC | | | |---|---| | `GHOST_LOCAL=1` | Also install Ollama and an offline model (6GB), which becomes the fallback. `GHOST_LOCAL_32B=1` adds the stronger 32B (26GB). | -| `GHOST_NO_BROWSER=1` | Skip Chromium and the computer-use driver: a smaller, faster install. | +| `GHOST_NO_BROWSER=1` | Skip Chromium and the computer-use driver: a smaller (1 GB), faster install. | | `GHOST_VERBOSE=1` | Show everything the installer runs. Otherwise it's in `~/.ghost/install.log`. | On Windows, from a clone: `.\install.ps1 -Local -NoBrowser`. @@ -95,7 +95,7 @@ An update installs that release's `config.yaml` and `SOUL.md`; if you changed yo **The Problem.** "Hosted inference" means your prompts, your code, whatever you're working on, land on someone else's servers with your name on them: one company holds both who you are and everything you asked. -**The Fix.** Every hosted request is sealed on your machine (HPKE/OHTTP, with [opengradient-ohttp](https://github.com/OpenGradient/sdk/tree/main/packages/opengradient-ohttp)) and opened only inside an attested **TEE enclave**. The relay that knows your account sees ciphertext. The enclave that opens the prompt never learns whose it is, and passes it to the model's host under its own key with nothing of yours attached. Its signature is checked before a single token reaches you. [Who sees what](#how-the-private-path-works), exactly. Need zero egress? `ghost --local` runs an offline model where nothing leaves the box. +**The Fix.** Every hosted request is sealed on your machine (HPKE/OHTTP, with [opengradient-ohttp](https://github.com/OpenGradient/sdk/tree/main/packages/opengradient-ohttp)) and opened only inside an attested **TEE enclave**. The relay that knows your account sees ciphertext. The enclave that opens the prompt never learns whose it is, and passes it to the model's host under its own key with nothing of yours attached. Its signature is checked before a single token reaches you. [Who sees what](#how-the-private-path-works), exactly. Need zero egress? `ghost --local` runs a model on your own machine, with the web tools off. > [!TIP] > And it doesn't give up. Most agents stop and ask after the first error; ghost reads the actual error, installs what's missing, changes tactics, and keeps going until the task is done. Set a standing goal with `/goal ` and it works toward it across turns on its own. @@ -119,8 +119,8 @@ Switch with `/model`, all open-weight, nothing closed or refusing: |---|---| | `abliteration/abliterated-model-large-v2` **(default)** | Uncensored by abliteration, with refusals removed from the weights rather than steered past. 1M context; built for authorized offensive-security, red-team and long-horizon agent work. | | `deepseek/deepseek-v4-pro` | Strongest open reasoning + coding model; uncensored via ghost's steer. | -| `abliteration/deepseek-v4.1-flash-abliterated` | Fast and far cheaper ($0.30 / $1.20 per million tokens in / out, against the default's $3 / $5), reads images, 1M context, and the one whose host runs in TEEs too. Runs ghost's auxiliary tasks (titles, compression, etc.). | -| `nous/hermes-4-405b` | Flagship uncensored open model, the most steerable. Also the hosted fallback. | +| `abliteration/deepseek-v4.1-flash-abliterated` | Fast and far cheaper ($0.41 / $1.62 per million tokens in / out, against the default's $4.05 / $6.75), reads images, 1M context, and the one whose host runs in TEEs too. Runs ghost's auxiliary tasks (titles, compression, etc.). | +| `nous/hermes-4-405b` | Flagship uncensored open model, the most steerable. | | local (opt-in) | Abliterated 7B / 32B via `GHOST_LOCAL`, fully offline, zero egress. | ## How the private path works @@ -139,13 +139,18 @@ ghost engine | The enclave | **No** | Yes, inside attested hardware | | The model's host | **No** | Yes | -The model's host is NEAR AI for DeepSeek V4.1 Flash Abliterated (served from TEEs as well), abliteration.ai for Abliterated Large v2, Together for DeepSeek V4 Pro, and the cheapest host on OpenRouter for Hermes 4 405B. They get the text and nothing else: no account, no IP, no header of yours. What's *in* the text is still in the text, so a prompt that names you names you. When that isn't good enough, `ghost --local` sends nothing anywhere. +The model's host is NEAR AI for DeepSeek V4.1 Flash Abliterated (served from TEEs as well), abliteration.ai for Abliterated Large v2, Together for DeepSeek V4 Pro, and the cheapest host on OpenRouter for Hermes 4 405B. They get the text and nothing else: no account, no IP, no header of yours, and ghost leaves your user name out of what it tells the model about your machine. What's *in* the text is still in the text: a prompt that names you names you, and so does a file or a command's output that the agent reads for you. When that isn't good enough, `ghost --local` sends it nowhere. + +The agent's own web searches, page fetches and browser go out from your machine like any browser's, not through the enclave. Searches ask DuckDuckGo, then Brave, Startpage, Mojeek, Yahoo and Google until one answers. ## Honest limits - **Hosted models cost credits.** `ghost usage` shows what you've spent, and ghost pauses itself after $5 in an hour so nothing runs away with your balance; change that with `ghost budget 20` or `ghost budget off`. What comes back unusable is reported, not paid for again: at most one retry, when the connection broke. +- **Chats don't stay.** A chat is deleted a day after it ends, along with what you typed. To keep them, set `sessions.auto_prune: false` in `~/.ghost/profiles/uncensored/config.yaml`. +- **Your keys stay yours.** Keys for other vendors in your environment (OpenAI, OpenRouter, ...) are kept from the engine, so nothing goes to them by surprise. Put one in `~/.ghost/profiles/uncensored/.env` to use it on purpose. - **Replies arrive whole.** The signature covers the complete reply, so ghost shows it once it's verified rather than word by word. - **The local model is opt-in and weaker.** Off by default (`GHOST_LOCAL`); it's a weaker agentic searcher and may still lean on the hosted gateway for tool orchestration. +- **It asks before it deletes.** Commands that delete folders, overwrite system files and the like wait for your OK; `--yolo` turns that off. - **The engine is forked, not rewritten.** It's one pinned Hermes release ([`engine.pin`](engine.pin)), patched and self-contained: no separate Hermes install is needed or touched, and `ghost update` is what moves it. Internal package names stay `hermes_cli`. - **Two small background processes.** The bridge is a service (launchd, systemd or Task Scheduler) that starts with your machine. Your sessions run in a local gateway that ghost starts when you do and that exits after 10 idle minutes (unless you install it as a service with `ghost gateway install`). diff --git a/SECURITY.md b/SECURITY.md index c2f132c..c4aca35 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -24,6 +24,7 @@ Include what you found, how to reproduce it, and the impact. We aim to acknowled and opengradient-ohttp. - **A login leaking** -- your session or API key readable by another user, logged, or sent anywhere but DreamFort. +- **Someone else on this machine using your bridge**, or standing in for it. - **A response accepted without verification** (the verify-before-emit guarantee bypassed). - **The engine phoning home** -- an update check, telemetry, a remote catalog or plugin fetch, or a side task that leaves the private path. diff --git a/privacy/bridge.py b/privacy/bridge.py index 748d1b3..92b4481 100755 --- a/privacy/bridge.py +++ b/privacy/bridge.py @@ -11,10 +11,14 @@ verified before a token of it reaches the engine. The login (`ghost-login`) is a DreamFort account or API key: see ghost_auth.py. """ +import hashlib +import hmac import json import os import random import re +import select +import socket import threading import time import warnings @@ -26,7 +30,7 @@ import ghost_auth import outbound import spend -from enclaves import REGISTRY, Enclaves +from enclaves import REGISTRY, Enclaves, RegistryError from ghost_auth import AuthError from localhttp import LocalServer @@ -142,6 +146,33 @@ def _apply_model_steer(obj): return obj +# ── Who you are ─────────────────────────────────────────────────────────────── +# The engine tells the model where it is: your home folder, the folder you're in, its own. That's your user name, in a +# prompt that promises not to carry it, so `~` it is. (What you write, and what the agent reads, goes as it is.) +def _homes(): + home = os.path.expanduser("~") + found = {home, os.path.realpath(home), home.replace("\\", "/")} + if os.name == "nt": # as Git Bash writes it + found.add("/" + home[0].lower() + home[2:].replace("\\", "/")) + return sorted((h for h in found if len(h) > 3), key=len, reverse=True) + + +_HOME = re.compile("(?:" + "|".join(map(re.escape, _homes()) or ["(?!)"]) + r")(?![\w-])(?!\.\w)", re.I if os.name == "nt" else 0) + + +def _without_home(obj): + for message in obj.get("messages") or []: + if not isinstance(message, dict) or message.get("role") not in ("system", "developer"): + continue + content = message.get("content") + if isinstance(content, str): + message["content"] = _HOME.sub("~", content) + for part in content if isinstance(content, list) else []: + if isinstance(part, dict) and isinstance(part.get("text"), str): + part["text"] = _HOME.sub("~", part["text"]) + return obj + + # ── Limits ──────────────────────────────────────────────────────────────────── # The gateway caps a reply at 4096 tokens unless the request says otherwise, and that includes the # model's hidden reasoning: left alone, a long answer comes back cut off or empty, marked "stop", and @@ -171,9 +202,10 @@ def _apply_limits(obj): # retried only while it has not been accepted, and a reply that comes back unusable is reported as that # instead of being quietly paid for again. UPSTREAM = "https://ohttp.invalid/v1/chat/completions" # routed by the transport; never contacted -# Hidden reasoning is silent, sometimes for minutes: giving up on it only means paying twice. -TIMEOUT = httpx.Timeout(1200.0, connect=15.0, pool=60.0) -_RETRY_STATUS = frozenset({500, 502, 503}) # (a 504 is a load balancer giving up on a request that goes on running) +# Hidden reasoning is silent, sometimes for minutes: giving up on it only means paying twice. The relay itself gives +# up on an enclave after four, so five of silence is a connection that died (a laptop that slept, say). +TIMEOUT = httpx.Timeout(300.0, connect=15.0, pool=60.0) +_RETRY_STATUS = frozenset({500, 502, 503}) _NEVER_ARRIVED = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout, httpx.WriteError, httpx.WriteTimeout, httpx.ProxyError) _MAX_TRIES = 3 _BUSY_WAITS = (5, 10, 20, 30) # seconds: the relay takes 40 requests a minute, which a quick agent can reach @@ -181,13 +213,17 @@ def _apply_limits(obj): _lock = threading.Lock() _clients = {} -_last_break = 0.0 +_broke = {} # request -> when it last came back unusable class Unusable(Exception): """A reply that was generated, and billed, but can't be used.""" +class HungUp(Exception): + """Whoever asked has gone (Ctrl-C, say).""" + + class Refused(Exception): """The relay or the enclave said no before generating anything.""" @@ -196,13 +232,31 @@ def __init__(self, status, message): self.status = status -def _upstream(): +class Relay(httpx.BaseTransport): + """The way to the relay. What isn't sealed didn't come from it: some networks answer for everyone, with a login page.""" + + def __init__(self, inner): + self.inner = inner + + def handle_request(self, request): + resp = self.inner.handle_request(request) + kind = resp.headers.get("content-type", "") + if resp.status_code < 400 and (resp.status_code != 200 or kind.startswith(("text/", "application/json"))): + resp.close() + return httpx.Response(502, json={"detail": "something on this network answers instead of DreamFort (a login page, perhaps)"}) + return resp + + def close(self): + self.inner.close() + + +def _upstream(refused=None): """(client, headers) for the login in use. Raises AuthError when nobody is logged in.""" - relay, token = ghost_auth.credentials() + relay, token = ghost_auth.credentials(refused) key = (relay, outbound.proxy(relay)) # a laptop changes networks with _lock: if key not in _clients: - transport = OHTTPTransport(relay_url=relay, verify_before_release=True, timeout=TIMEOUT, transport=outbound.transport(relay)) + transport = OHTTPTransport(relay_url=relay, verify_before_release=True, timeout=TIMEOUT, transport=Relay(outbound.transport(relay))) transport._resolver = Enclaves(outbound.transport(REGISTRY, public_only=True), log) _clients[key] = httpx.Client(transport=transport, timeout=TIMEOUT) return _clients[key], {"Authorization": f"Bearer {token}"} @@ -216,11 +270,13 @@ def _wait(seconds): time.sleep(seconds) -def _open(obj): +def _open(obj, gone): """Start one generation and return its open stream. Retries only what the enclave never accepted.""" - tries, waits = 0, list(_BUSY_WAITS) + tries, waits, refused = 0, list(_BUSY_WAITS), None while True: - client, headers = _upstream() + client, headers = _upstream(refused) + if gone(): + raise HungUp try: resp = client.send(client.build_request("POST", UPSTREAM, json=obj, headers=headers), stream=True) except _NEVER_ARRIVED as e: @@ -234,11 +290,16 @@ def _open(obj): if resp.status_code < 400: return resp try: - message = _decode_error(resp.read(), resp.status_code) + raw = resp.read() finally: resp.close() - if resp.status_code == 504: + message = _decode_error(raw, resp.status_code) + if resp.status_code == 504 and b'"tee_' not in raw: # a load balancer, giving up on a request that goes on running raise httpx.ReadTimeout(message) + token = headers["Authorization"].removeprefix("Bearer ") + if resp.status_code == 401 and refused is None and not ghost_auth.api_key(): + refused = token # renew it, once + continue if resp.status_code == 429 and waits: log(f"too many requests this minute; waiting {waits[0]}s") _wait(waits.pop(0)) @@ -332,16 +393,16 @@ def _host_failed(error): return Refused(status, f"the model's host answered: {message[:600]}") -def _generate(obj): +def _generate(obj, gone=lambda: False): """One generation, verified and whole. Always streamed from the enclave: its buffered form cuts long replies off at the relay's timeout and quietly 'repairs' a truncated tool call into valid JSON.""" - global _last_break why = spend.paused() if why: raise Refused(422, why) + asked = hashlib.sha256(json.dumps(obj.get("messages"), sort_keys=True).encode()).digest() # the engine's retry is the same reply, resp, ended = Reply(obj["max_tokens"]), None, False try: - resp = _open({**obj, "stream": True}) + resp = _open({**obj, "stream": True}, gone) for line in resp.iter_lines(): if not line.startswith("data:"): continue @@ -356,14 +417,19 @@ def _generate(obj): ended = ended or reply.finish is not None if not ended: raise httpx.RemoteProtocolError("the reply stopped early") - except (AuthError, Refused): # never accepted, or never billed + except (AuthError, Refused, HungUp): # never accepted, or never billed raise + except httpx.ProxyError as e: + raise Refused(502, f"couldn't reach DreamFort: {e}") from e except Exception as e: # Accepted, so billed, but we never got it (cut off, unverifiable, unreadable). One engine retry is fair; # a second break in a row is not. tokens_in = len(json.dumps(obj)) // 4 spend.record(obj.get("model"), tokens_in, 2000, spend.estimate(obj.get("model"), tokens_in, 2000)) - again, _last_break = time.time() - _last_break < _BREAK_WINDOW, time.time() + now = time.time() + for old in [k for k, at in list(_broke.items()) if now - at > _BREAK_WINDOW]: + _broke.pop(old, None) + again, _broke[asked] = asked in _broke, now log(f"reply lost after it was accepted: {type(e).__name__}: {e}") message = ("a reply came back without the enclave's signature on it, so it was thrown away" if isinstance(e, TeeVerificationError) else f"the connection to the enclave broke before the reply arrived ({type(e).__name__})") @@ -374,10 +440,9 @@ def _generate(obj): if resp is not None: resp.close() tokens_in = int(reply.usage.get("prompt_tokens") or 0) - cost = reply.cost if reply.cost is not None else spend.estimate(obj.get("model"), tokens_in, reply.tokens_out) + cost = reply.cost * spend.MARKUP if reply.cost is not None else spend.estimate(obj.get("model"), tokens_in, reply.tokens_out) spend.record(obj.get("model"), tokens_in, reply.tokens_out, cost) reply.check() - _last_break = 0.0 return reply @@ -398,12 +463,44 @@ def _decode_error(raw: bytes, status) -> str: return message[:600] +def _check(): + """Can a request get from here to an enclave? Nothing is run or billed: the relay's config document and the registry.""" + found = {} + try: + relay, token = ghost_auth.credentials() + with httpx.Client(transport=outbound.transport(relay), timeout=20) as client: + resp = client.get(f"{relay}/config", headers={"Authorization": f"Bearer {token}"}) + found["relay"] = resp.status_code + except AuthError as e: + found["login"] = str(e) + except httpx.HTTPError as e: + found["unreachable"] = str(e) if isinstance(e, httpx.ProxyError) else type(e).__name__ + try: + found["enclaves"] = len(Enclaves(outbound.transport(REGISTRY, public_only=True)).listed()) + except (RegistryError, httpx.HTTPError): + found["enclaves"] = None + return found + + class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *a): pass + def _mine(self): + return hmac.compare_digest(self.headers.get("Authorization") or "", f"Bearer {ghost_auth.bridge_token()}") + + def _gone(self): + """Nobody is waiting for the answer any more, so nothing should be paid for it.""" + try: + readable, _, _ = select.select([self.connection], [], [], 0) + return bool(readable) and self.connection.recv(1, socket.MSG_PEEK) == b"" + except OSError: + return True + except ValueError: # too many open files for select; carry on + return False + # ── tiny helpers ── def _send_json(self, status, obj): payload = json.dumps(obj).encode() @@ -431,6 +528,9 @@ def do_GET(self): self.end_headers() self.wfile.write(body) return + if path == "/check": # for `ghost doctor`: the way out, as the bridge sees it + self._send_json(200, _check()) if self._mine() else self._error(403, "not yours") + return static = {"/model-catalog.json": CATALOG_BYTES, "/models-dev.json": MODELS_DEV_BYTES}.get(self.path) if static is not None: self.send_response(200) @@ -477,6 +577,9 @@ def do_POST(self): if self.headers.get("Origin"): # a web page: it must not spend your credits behind your back self._error(403, "ghost's bridge doesn't answer web pages") return + if not self._mine(): + self._error(403, "ghost's bridge only answers the ghost it belongs to. If that's this one, its settings are out of date: run `ghost update`") + return if not ("chat/completions" in path or path.endswith("/completions")): self._error(404, "ghost's bridge only serves /v1/chat/completions") return @@ -502,12 +605,20 @@ def do_POST(self): return # Apply the per-model uncensor steer (e.g. DeepSeek) and the limits before forwarding. - obj = _apply_limits(_apply_model_steer(obj)) + obj = _apply_limits(_apply_model_steer(_without_home(obj))) log(f"chat/completions model={obj.get('model')} stream={wants_stream} effort={obj['reasoning_effort']} " f"max_tokens={obj['max_tokens']}") try: - reply = _generate(obj) + reply = _generate(obj, self._gone) + except HungUp: + log("whoever asked has gone; nothing was sent") + self.close_connection = True + return + except ghost_auth.Unavailable as e: + log(f"login not renewed: {e}") + self._error(503, str(e)) + return except AuthError as e: log(f"not logged in: {e}") self._error(401, str(e)) diff --git a/privacy/doctor.py b/privacy/doctor.py index 850fe8b..cac4652 100644 --- a/privacy/doctor.py +++ b/privacy/doctor.py @@ -5,8 +5,8 @@ import ghost_auth import launch +import outbound import spend -from ghost_auth import AuthError def engine(): @@ -28,38 +28,52 @@ def login(): def bridge(): + outbound.note() if launch.ensure_bridge(): return True, f"running on 127.0.0.1:{launch.PORT}", None return False, f"isn't running: {launch.bridge_problem()}", None if launch.port_taken() else "ghost update" +def _asked(): + """What the bridge can reach (it, and not this shell, is what your requests go through).""" + import http.client + import json + conn = http.client.HTTPConnection("127.0.0.1", launch.PORT, timeout=45) + try: + conn.request("GET", "/check", headers={"Authorization": f"Bearer {ghost_auth.bridge_token()}"}) + return json.loads(conn.getresponse().read()) + except (OSError, ValueError, http.client.HTTPException): + return {} + finally: + conn.close() + + +_found = {} + + def relay(): """The relay's own config document: it answers only a login it accepts, and nothing is run or billed.""" - import httpx - import outbound started = time.monotonic() - try: - address, token = ghost_auth.credentials() - resp = httpx.get(f"{address}/config", headers={"Authorization": f"Bearer {token}"}, timeout=20, verify=outbound.trust()) - except AuthError as e: - return False, str(e), "ghost login" - except httpx.HTTPError as e: - return False, f"can't be reached ({type(e).__name__}); check your connection, VPN or proxy", None - if resp.status_code in (401, 403): + _found.clear() + _found.update(_asked()) + if "login" in _found: + return False, _found["login"], "ghost login" + if "unreachable" in _found: + return False, f"can't be reached ({_found['unreachable']}); check your connection, VPN or proxy", None + status = _found.get("relay") + if status in (401, 403): return False, "doesn't accept this login any more", "ghost login" - if resp.status_code != 200: - return False, f"isn't well ({resp.status_code}); try again in a moment", None + if status != 200: + return False, f"isn't well ({status or 'the bridge has no answer'}); try again in a moment", None return True, f"reachable, login accepted ({(time.monotonic() - started) * 1000:.0f} ms)", None def enclaves(): """The registry says which enclaves there are. Without it, ghost has some built in.""" - import outbound - from enclaves import REGISTRY, Enclaves, RegistryError - try: - return True, f"{Enclaves(outbound.transport(REGISTRY, public_only=True)).listed()} in the registry", None - except RegistryError: + listed = _found.get("enclaves") + if listed is None: return None, "the registry can't be read right now, so the one built into ghost is used", None + return (True, f"{listed} in the registry", None) if listed else (False, "the registry lists none right now; try again later", None) def credits(): diff --git a/privacy/enclaves.py b/privacy/enclaves.py index 53e7ffd..9eb7aba 100644 --- a/privacy/enclaves.py +++ b/privacy/enclaves.py @@ -1,9 +1,10 @@ """Which enclaves a request may be sealed to: the ones the on-chain TEE registry lists. The chain it lives on has been down (25 November 2026), and a network that inspects TLS can't be believed about -it. When it can't be read, ghost uses the enclaves below instead. Their keys are fixed here, as the registry's -address is, so cutting ghost off from the registry can't point it at an impostor. DreamFort's apps fall back to -the same list (chat-app's lib/api/backupTees.ts, chat-api's src/core/backup_tees.py): keep the three in step. +it. When it can't be read, ghost uses the enclaves below instead; a registry that answers is always obeyed, also +when it lists none. Their keys are fixed here, as the registry's address is, so cutting ghost off from the registry +can't point it at an impostor. DreamFort's apps fall back to the same list (chat-app's lib/api/backupTees.ts, +chat-api's src/core/backup_tees.py): keep the three in step. """ import random @@ -43,17 +44,18 @@ def __init__(self, transport=None, log=lambda message: None): self._log = log def get(self): - try: - return super().get() - except RegistryError as e: - self._log(f"the TEE registry can't be read, using a built-in enclave: {e}") - with self._lock: - self._cache.put(random.choice(BUILT_IN)) - return self._cache.get() + with self._lock: + if not self._cache.get(): + try: + found = self.listed() + except RegistryError as e: + self._log(f"the TEE registry can't be read, using a built-in enclave: {e}") + found = BUILT_IN + if not found: + raise RegistryError("the TEE registry lists no active enclave, so there is nothing to seal this to; try again later") + self._cache.put(random.choice(found)) + return self._cache.get() def listed(self): - """How many enclaves the registry lists. Raises RegistryError when it can't be read.""" - found = len(parse_active_tees(self._fetch(), self._excluded)) - if not found: - raise RegistryError("the registry lists no enclave") - return found + """The enclaves the registry lists. Raises RegistryError when it can't be read.""" + return parse_active_tees(self._fetch(), self._excluded) diff --git a/privacy/ghost_auth.py b/privacy/ghost_auth.py index 2182253..a6c8ec0 100644 --- a/privacy/ghost_auth.py +++ b/privacy/ghost_auth.py @@ -36,6 +36,10 @@ class AuthError(Exception): """Nobody is logged in, or the login no longer works.""" +class Unavailable(AuthError): + """The login may be fine, but DreamFort couldn't be asked to renew it just now.""" + + _lock = threading.RLock() _cached = {} # path -> (mtime_ns, value) @@ -66,15 +70,24 @@ 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.""" +def _bridge_key(): try: - key = BRIDGE_KEY_FILE.read_text(encoding="utf-8") + return 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() + return key + + +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.""" + return hmac.new(_bridge_key().encode(), f"proof {nonce}".encode(), "sha256").hexdigest() + + +def bridge_token(): + """What only your own ghost can send the bridge, which spends your credits.""" + return hmac.new(_bridge_key().encode(), b"token", "sha256").hexdigest()[:40] # ── API key ─────────────────────────────────────────────────────────────────── @@ -124,7 +137,7 @@ def _refresh(session): json={"refresh_token": session["refresh_token"]}, verify=outbound.trust(), headers={"apikey": config.get("supabase_anon_key") or ""}, timeout=15) except httpx.HTTPError as e: - raise AuthError(f"couldn't reach DreamFort to renew your login ({type(e).__name__}); check your connection") from e + raise Unavailable(f"couldn't reach DreamFort to renew your login ({type(e).__name__}); check your connection") from e if resp.status_code in (400, 401, 403): # Another process sharing this file may have renewed it first, which retires our copy. with _lock: @@ -138,7 +151,7 @@ def _refresh(session): body = resp.json() fresh = {**session, "access_token": body["access_token"], "refresh_token": body.get("refresh_token") or session["refresh_token"]} except (httpx.HTTPError, ValueError, KeyError) as e: - raise AuthError("DreamFort couldn't renew your login; try again in a moment") from e + raise Unavailable("DreamFort couldn't renew your login just now; try again in a moment") from e fresh["expires_at"] = body.get("expires_at") or int(time.time()) + int(body.get("expires_in") or 3600) _write_private(SESSION_FILE, json.dumps(fresh, indent=2)) return fresh @@ -164,9 +177,9 @@ def label(): return f"DreamFort account ({email})" if email else "DreamFort account" -def credentials(): - """(relay url, bearer token) for the login in use. Renews an account's token when it is due. Raises - AuthError when there is nothing to use.""" +def credentials(refused=None): + """(relay url, bearer token) for the login in use. Renews an account's token when it is due, or when it's the one + that was just refused (this machine's clock may be behind). Raises AuthError when there is nothing to use.""" key = api_key() if key: return CHAT_API_URL + API_KEY_RELAY, key @@ -174,7 +187,7 @@ def credentials(): session = account() if session is None: raise AuthError(NOT_LOGGED_IN) - if _expired(session): + if _expired(session) or session["access_token"] == refused: session = _refresh(session) return CHAT_API_URL + ACCOUNT_RELAY, session["access_token"] diff --git a/privacy/launch.py b/privacy/launch.py index c551f3c..724f8b7 100644 --- a/privacy/launch.py +++ b/privacy/launch.py @@ -33,13 +33,31 @@ PORT = 8788 SERVICE = "ai.dreamfort.ghost" if platform.system() == "Darwin" else "ghost-bridge" +# Vendors the engine would turn to if it found their key (or address) in your environment: a model in its picker, a +# search, a picture, a browser, unsealed and on your own bill. Put one in ghost's own .env if that's what you want. +# tests/test_engine.py fails when an engine release knows one that isn't here. +VENDORS = """ +ACTUAL AI_GATEWAY ALIBABA_CODING_PLAN ALIBABA_CODING_PLAN_CN ALIBABA_TOKEN_PLAN ALIBABA_TOKEN_PLAN_CN ANTHROPIC ARCEE ARCEEAI AZURE_FOUNDRY BEDROCK +COHERE COMMANDCODE COMMANDCODE_ANTHROPIC DASHSCOPE DASHSCOPE_CN DEEPINFRA DEEPSEEK FIREWORKS GEMINI GLM GMI GOOGLE GROQ HELICONE HF KILOCODE KIMI +KIMI_CN KIMI_CODING LM META META_MODEL MINIMAX MINIMAX_CN MISTRAL MODEL NEBIUS NEBIUS_TOKEN_FACTORY NOUS NOVITA NVIDIA OLLAMA OPENAI OPENCODE_GO +OPENCODE_ZEN OPENROUTER PERPLEXITY QWEN RAMP_ROUTER ROUTER STEPFUN TOGETHER TOKENHUB TOKENPLAN UPSTAGE XAI XIAOMI ZAI Z_AI +BRAVE_SEARCH BROWSERBASE BROWSER_USE BRV CONNECTOR_GATEWAY ELEVENLABS EXA FIRECRAWL HINDSIGHT HONCHO KEENABLE KREA MEM0 OPENVIKING PARALLEL +RETAINDB SUPERMEMORY TAVILY +""".split() +VENDOR_ENV = {f"{vendor}_{what}" for vendor in VENDORS for what in ("API_KEY", "BASE_URL", "API_BASE", "API_URL", "TOKEN", "URL")} | { + "AWS_BEARER_TOKEN_BEDROCK", "BROWSERBASE_PROJECT_ID", "FAL_KEY", "FIRECRAWL_BROWSER_TTL", "FIRECRAWL_GATEWAY_URL", "GOOGLE_APPLICATION_CREDENTIALS", + "HERMES_ANON_API_SECRET", "HERMES_INFERENCE_MODEL", "HERMES_INFERENCE_PROVIDER", "HERMES_MODEL", "HERMES_QWEN_BASE_URL", "HERMES_TUI_PROVIDER", + "LLM_MODEL", "OPENAI_ORG_ID", "OPENAI_ORGANIZATION", "OPENVIKING_ENDPOINT", "PORCUPINE_ACCESS_KEY", "SEARXNG_URL", "TOOL_GATEWAY_DOMAIN", + "TOOL_GATEWAY_SCHEME", "TOOL_GATEWAY_URL", "TOOL_GATEWAY_USER_TOKEN", "VERTEX_CREDENTIALS_PATH", "VOICE_TOOLS_OPENAI_KEY"} +LOCAL_TOOLS = "clarify,code_execution,file,session_search,skills,terminal,todo" # none that reach the web by themselves + HELP = """\ ghost -- a private, unrestricted agent in your terminal ghost start chatting ghost -z "question" ask once and print the answer ghost -c continue your last chat (ghost --resume ID for another) - ghost --local use the offline model (nothing leaves this machine) + ghost --local use the offline model (what you type stays on this machine) ghost login | logout connect your DreamFort account or API key ghost doctor check that everything works @@ -72,7 +90,7 @@ def _setting(config, section, key, indent=2): def default_model(config): model = _setting(config, "model", "default") - return model.rsplit("/", 1)[-1] if model else "ghost" + return model.rsplit("/", 1)[-1] if model else None def local_model(config): @@ -106,6 +124,23 @@ def walk(node): path.write_text(json.dumps(data, indent=2), encoding="utf-8") +def forget_typed(config): + """Chats are deleted a day after they end (sessions.retention_days); so is the list of what you typed.""" + if _setting(config, "sessions", "auto_prune") != "true": + return + path, keep = PROFILE / ".hermes_history", [] + try: + oldest = time.time() - float(_setting(config, "sessions", "retention_days") or 1) * 86400 + entries = re.split(r"(?m)^(?=# \d{4}-\d\d-\d\d )", path.read_text(encoding="utf-8")) + for entry in entries[1:]: + if time.mktime(time.strptime(entry[2:21], "%Y-%m-%d %H:%M:%S")) >= oldest: + keep.append(entry) + if len(keep) < len(entries) - 1: + path.write_text("\n" + "".join(keep), encoding="utf-8") + except (OSError, ValueError): + pass + + # ── the bridge ──────────────────────────────────────────────────────────────── def bridge_up(): """Is the bridge answering, and is it yours?""" @@ -161,6 +196,13 @@ def _start_process(): stdout=out, stderr=out, cwd=str(HOME), **extra) +def leave_proxies(): + """The bridge is a background service, and doesn't see the proxies your shell sets.""" + if urllib.request.getproxies_environment() or (PRIV / "proxies.json").exists(): + import outbound # (not for nothing: it brings an HTTP client along) + outbound.note() + + def ensure_bridge(): """It runs as a background service; start it if something stopped it.""" if bridge_up(): @@ -202,13 +244,15 @@ def engine_proxies(): return {name: value for lower, value in env.items() for name in (lower, lower.upper())} -def run_engine(args): +def run_engine(args, provider="opengradient"): engine = engine_binary() if engine is None: say(f"the engine isn't installed ({ENGINE}). Put it back with: ghost update") return 1 - # An ambient ANTHROPIC_API_KEY would make any `claude` the agent runs bill that key instead of your plan. - os.environ.pop("ANTHROPIC_API_KEY", None) + for name in VENDOR_ENV: + os.environ.pop(name, None) + os.environ["HERMES_INFERENCE_PROVIDER"] = provider # whatever becomes of config.yaml + os.environ.update({"UV_SYSTEM_CERTS": "1", "UV_NATIVE_TLS": "1"}) # for what it installs later on os.environ.update(engine_proxies()) command = [str(engine), "-p", "uncensored", *args] sys.stdout.flush() @@ -229,8 +273,10 @@ def run_local(args, config): say(f"no local model installed ({model}). Reinstall with GHOST_LOCAL=1 to add the offline model.") return 1 if sys.stderr.isatty(): - say(f"{model} · fully offline, nothing leaves this machine") - return run_engine(["-m", model, "--provider", "ollama-local", *args]) + say(f"{model} · runs on this machine, and its web tools are off") + if starts_a_chat(args) and not {"-t", "--toolsets"} & set(args): + args = ["--toolsets", LOCAL_TOOLS, *args] + return run_engine(["-m", model, "--provider", "ollama-local", *args], provider="ollama-local") def starts_a_chat(args): @@ -288,6 +334,10 @@ def main(argv): return run_local(args, config) if not starts_a_chat(args): return run_engine(args) + if not default_model(config) or "\n opengradient:\n" not in config: + say(f"ghost's settings ({PROFILE / 'config.yaml'}) are missing or damaged. Put them back with: ghost update") + return 1 + forget_typed(config) if ghost_auth.mode() is None: stop = log_in_first(config) if stop == "local": @@ -295,6 +345,7 @@ def main(argv): if stop is not None: return stop pin_route() + leave_proxies() 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.") diff --git a/privacy/outbound.py b/privacy/outbound.py index d8c7ff0..666bdd3 100644 --- a/privacy/outbound.py +++ b/privacy/outbound.py @@ -1,12 +1,19 @@ """How ghost's own requests leave this machine: through its proxy, if it has one, and trusting the certificates it trusts, as a company laptop needs. +The bridge is a background service, which doesn't see what your shell sets (HTTPS_PROXY and so on), so `ghost` +leaves a note of it. A proxy that can't be used is an error: going around it would show your address. + With one exception. Which enclaves to trust is read from the TEE registry, so on a network that inspects TLS that read must fail rather than believe the network: it trusts the public authorities only. """ +import json +import os +import socket import ssl import sys import urllib.request +from pathlib import Path from urllib.parse import urlsplit import certifi @@ -22,22 +29,63 @@ def trust(): return context +NOTE = Path(os.environ.get("GHOST_HOME") or Path.home() / ".ghost") / "privacy" / "proxies.json" + + +def note(): + """Leave your shell's proxies for the bridge (or that it has none, when you're there to see to it).""" + found = urllib.request.getproxies_environment() + try: + if any(found.get(kind) for kind in ("http", "https", "all")): + fd = os.open(NOTE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(found, fh) + elif sys.stdin.isatty(): + NOTE.unlink(missing_ok=True) + except (OSError, AttributeError): + pass + + +def _noted(): + try: + found = json.loads(NOTE.read_text(encoding="utf-8")) + return found if isinstance(found, dict) else {} + except (OSError, ValueError): + return {} + + def proxy(url): - """The proxy for `url`, from the environment or the system's settings. None for a direct connection.""" + """The proxy for `url`, from the environment, the system's settings or the note. None for a direct connection.""" parts = urlsplit(url) try: if urllib.request.proxy_bypass(parts.hostname): return None found = urllib.request.getproxies() except OSError: - return None + found = {} + if not any(found.get(kind) for kind in ("http", "https", "all")): + found = _noted() + if found and urllib.request.proxy_bypass_environment(parts.hostname, found): + return None address = found.get(parts.scheme) or found.get("all") - if address and "://" not in address: - return f"http://{address}" - return address if address and urlsplit(address).scheme in ("http", "https") else None + if not address: + return None + address = address if "://" in address else f"http://{address}" + if urlsplit(address).scheme not in ("http", "https", "socks5", "socks5h"): + raise httpx.ProxyError(f"ghost can't use a proxy like {address.split('@')[-1]} (http, https and socks5 ones it can)") + return address + + +def _keepalive(): + """A reply can be minutes of silence, which some routers take for a dead connection, and sleep makes one.""" + options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] + for name, seconds in (("TCP_KEEPIDLE" if hasattr(socket, "TCP_KEEPIDLE") else "TCP_KEEPALIVE", 30), ("TCP_KEEPINTVL", 15), ("TCP_KEEPCNT", 4)): + if hasattr(socket, name): + options.append((socket.IPPROTO_TCP, getattr(socket, name), seconds)) + return options def transport(url, *, public_only=False): verify = ssl.create_default_context(cafile=certifi.where()) if public_only else trust() - return httpx.HTTPTransport(verify=verify, proxy=proxy(url)) + return httpx.HTTPTransport(verify=verify, proxy=proxy(url), socket_options=_keepalive()) diff --git a/privacy/spend.py b/privacy/spend.py index 2fe8990..99de4c5 100644 --- a/privacy/spend.py +++ b/privacy/spend.py @@ -1,8 +1,7 @@ #!/usr/bin/env python3 """What ghost has spent on hosted models, and the limit that stops a runaway. -The bridge records the cost the enclave reports with every reply (model and token counts only, never -content) and refuses new requests once the last hour's total passes the budget. +The bridge records what DreamFort charges for every reply (with the model and token counts, never content) and refuses new requests once the last hour's total passes the budget. ghost usage what you've spent ghost budget show the hourly limit @@ -23,7 +22,9 @@ HOUR, DAY = 3600, 86400 KEEP = 31 * DAY -# Dollars per million tokens (in, out), for replies whose own cost never arrived because they broke off. +# What DreamFort charges, as a multiple of the cost the enclave reports (chat-api's OHTTP_CREDIT_MARKUP). +MARKUP = 1.35 +# The enclave's cost per million tokens (in, out), for replies whose own never arrived because they broke off. PRICES = { "abliterated-model-large-v2": (3.0, 5.0), "deepseek-v4-pro": (1.32, 3.96), @@ -53,7 +54,7 @@ def _load(since): def estimate(model, tokens_in, tokens_out): price_in, price_out = PRICES.get(model, (3.0, 5.0)) - return (tokens_in * price_in + tokens_out * price_out) / 1e6 + return (tokens_in * price_in + tokens_out * price_out) / 1e6 * MARKUP def record(model, tokens_in, tokens_out, usd): diff --git a/profile/config.yaml b/profile/config.yaml index d4e888f..5d850f3 100644 --- a/profile/config.yaml +++ b/profile/config.yaml @@ -9,16 +9,18 @@ model: default: abliteration/abliterated-model-large-v2 provider: opengradient context_length: 1048576 +# Only with GHOST_LOCAL, for when the hosted models can't be reached. There is no hosted fallback: falling back is +# answering again, at your expense, and by a model whose smaller window a long chat would be cut down to. fallback_model: provider: ollama-local model: __LOCAL_MODEL__ providers: # Hosted models are reached through ghost's local bridge (privacy/bridge.py on :8788), which seals each - # request to an attested TEE enclave (OHTTP) and verifies the reply. The api_key here is a placeholder: the - # bridge uses your own login (`ghost login`). + # request to an attested TEE enclave (OHTTP) and verifies the reply. The api_key is what the bridge knows its own + # ghost by; DreamFort gets your own login (`ghost login`). opengradient: base_url: http://127.0.0.1:8788/v1 - api_key: managed-by-ghost + api_key: __BRIDGE_TOKEN__ default_model: abliteration/abliterated-model-large-v2 context_length: 1048576 models: # smaller windows than the 1M above @@ -38,6 +40,8 @@ agent: # The relay bills every attempt it accepts. The bridge already retries what it safely can. api_max_retries: 2 auto_recovery_cycles: 1 + # The bridge hands a reply over whole, so a long one is a long silence. Asking again would only pay again. + local_stream_stale_timeout: 3600 service_tier: fast task_completion_guidance: false environment_probe: false @@ -168,13 +172,17 @@ prefill_messages_file: __GHOST_HOME__/privacy/uncensored_prefill.json compression: threshold_tokens: 160000 proactive_prune_tokens: 48000 + abort_on_summary_failure: true # (a chat is never shortened by just dropping its middle) memory: memory_enabled: false user_profile_enabled: false -# Incognito: conversations are pruned a day after they end. +# Incognito: conversations are deleted a day after they end (and so is what you typed, by the launcher), and the logs +# don't quote them. sessions: auto_prune: true retention_days: 1 +logging: + level: WARNING display: personality: uncensored interface: cli @@ -187,12 +195,12 @@ security: redact_secrets: false approvals: mode: manual +# What an agent does all day isn't asked about; deleting folders and the like is. (A command that does both is: +# scripts/debrand.py.) command_allowlist: - script execution via heredoc - script execution via -e/-c flag - shell command via -c/-lc flag -- recursive delete -- delete in root path terminal: home_mode: real checkpoints: @@ -204,10 +212,11 @@ tool_loop_guardrails: exact_failure: 3 same_tool_failure: 5 idempotent_no_progress: 3 +# Searches go from this machine to public search engines, one at a time until one answers: DuckDuckGo, Brave, +# Startpage, Mojeek, Yahoo, Google (scripts/debrand.py). web: backend: ddgs search_backend: ddgs - # Searches go to the engine chosen above and nowhere else. keyless_fallback: false keyless_rescue: false tts: @@ -278,5 +287,5 @@ _config_version: 54 # ── Fallback model ──────────────────────────────────────────────────── # Every hosted request takes one path: the local bridge, then the TEE gateway. There is deliberately no # other provider here (no Nous Portal, OpenRouter, Claude, GPT or Gemini): that would bypass the enclave and -# the unrestricted-only line-up. The fallback at the top of this file is a hosted unrestricted model, or a -# local one when ghost was installed with GHOST_LOCAL=1. +# the unrestricted-only line-up. The fallback at the top of this file is the local model, when ghost was +# installed with GHOST_LOCAL=1. diff --git a/pyproject.toml b/pyproject.toml index 2a70ea0..f18c973 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,7 +13,7 @@ dependencies = [ # The bridge's transport: seals each request to an attested enclave (OHTTP/HPKE) and checks the # signature on every reply. Pinned so a re-install can't silently change the verification protocol. "opengradient-ohttp>=0.1,<0.2", - "httpx>=0.27", + "httpx[socks]>=0.27", # The certificates this machine trusts, for networks with one of their own. "truststore>=0.10", "certifi", diff --git a/scripts/debrand.py b/scripts/debrand.py index 497e9a6..912f608 100755 --- a/scripts/debrand.py +++ b/scripts/debrand.py @@ -198,6 +198,36 @@ r'if _redact_raw\.lower\(\) not in \{"1", "true", "yes", "on"\}:', "if False: @NOTE", "off on purpose"), + # -- side tasks: one that fails may not be tried again on the main model. With `ghost --local` that would be a + # hosted one (nothing of yours was to leave the machine), and otherwise it is a ten times dearer one. + ("agent/auxiliary_client.py", + r"(def _try_main_agent_model_fallback\((?:.|\n)+?\) -> tuple\[Optional\[Any\], Optional\[str\], str\]:\n)", + r'\1 return None, None, "" @NOTE' "\n", + "a side task stays on its own model"), + # -- web search: `auto` asks Wikipedia and xAI's Grokipedia first, and then a random few at once. + ("plugins/web/ddgs/provider.py", + r" with DDGS\(timeout=10\) as client:\n for i, hit in enumerate\(client\.text\(query, max_results=safe_limit\)\):\n", + " with DDGS(timeout=10) as client:\n" + " found, failed = [], None\n" + ' for engine in ("duckduckgo", "brave", "startpage", "mojeek", "yahoo", "google"): @NOTE\n' + " try:\n" + " found = list(client.text(query, max_results=safe_limit, backend=engine))\n" + " except Exception as e:\n" + " failed = e\n" + " if found:\n" + " break\n" + " if not found and failed:\n" + " raise failed\n" + " for i, hit in enumerate(found):\n", + "one search engine at a time"), + # -- approvals: a command is judged by the first rule it matches, so one that is always allowed + # (`python -c ...`) would carry anything chained after it. + ("tools/approval_detection.py", + r" description = next\(_iter_dangerous_descriptions\(command\), None\)\n", + " _found = list(dict.fromkeys(_iter_dangerous_descriptions(command))) @NOTE\n" + ' _routine = ("script execution via heredoc", "script execution via -e/-c flag", "shell command via -c/-lc flag")\n' + " description = next((d for d in _found if d not in _routine), _found[0] if _found else None)\n", + "what isn't routine about a command decides"), # -- startup tips: skip the ones that point at accounts and closed models ghost doesn't have. ("hermes_cli/tips.py", r" keys = tip_keys\(\)\n", diff --git a/scripts/write_profile.py b/scripts/write_profile.py index c82c647..0d1da18 100644 --- a/scripts/write_profile.py +++ b/scripts/write_profile.py @@ -9,19 +9,23 @@ import argparse import os import re +import sys from pathlib import Path SOURCE = Path(__file__).resolve().parent.parent / "profile" SIDE_TASKS = "abliteration/deepseek-v4.1-flash-abliterated" -FALLBACK = "nous/hermes-4-405b" def config(ghost_home, local_model=None): + os.environ["GHOST_HOME"] = str(ghost_home) + sys.path.insert(0, str(SOURCE.parent / "privacy")) + import ghost_auth text = (SOURCE / "config.yaml").read_text(encoding="utf-8") text = text.replace("__GHOST_HOME__", Path(ghost_home).as_posix()).replace("__LOCAL_MODEL__", local_model or "ghost-tool:latest") - if not local_model: # hosted-only: nothing is served locally, so side tasks and the fallback are hosted too + text = text.replace("__BRIDGE_TOKEN__", ghost_auth.bridge_token()) + if not local_model: # hosted-only: nothing is served locally, so side tasks are hosted too, and there is no fallback + text = re.sub(r"(?m)^(# Only with GHOST_LOCAL.*\n(?:#.*\n)*)?fallback_model:\n(?: .*\n)+", "", text) text = re.sub(r"provider: ollama-local\n(\s*)model: \S+", rf"provider: opengradient\n\1model: {SIDE_TASKS}", text) - text = re.sub(r"(?m)^(fallback_model:\n provider: opengradient\n model: )\S+", rf"\g<1>{FALLBACK}", text) text = re.sub(r"(?m)^ ollama-local:\n(?: .*\n)+", "", text) # or /model would offer it return text diff --git a/tests/fake_dreamfort.py b/tests/fake_dreamfort.py index e4aadd3..4458872 100644 --- a/tests/fake_dreamfort.py +++ b/tests/fake_dreamfort.py @@ -36,7 +36,8 @@ "402": (402, {"detail": "Insufficient credits"}), "429": (429, {"error": "Rate limit exceeded: 40 per 1 minute"}), "503": (503, {"detail": {"code": "tee_unreachable", "message": "TEE OHTTP request failed"}}), "retired": (502, {"detail": {"code": "tee_not_active", "message": "Selected TEE is not active"}}), - "page": (502, b"

502 Bad Gateway

"), "451": (451, {"error": "Content policy violation"}), + "page": (502, b"

502 Bad Gateway

"), "portal": (200, b"Welcome to the hotel"), + "slow": (504, {"detail": {"code": "tee_timeout", "message": "no answer from the enclave"}}), "451": (451, {"error": "Content policy violation"}), # accepted, and then not delivered "504": (504, b"

504 Gateway Time-out

"), "silent": None, "empty": None, "cut": None, "drop": None, "forged": None, "unsigned": None, diff --git a/tests/test_bridge.py b/tests/test_bridge.py index 6ca99f7..94a42b7 100644 --- a/tests/test_bridge.py +++ b/tests/test_bridge.py @@ -5,6 +5,8 @@ """ import json import os +import re +import socket import sys import threading import time @@ -67,7 +69,7 @@ def __call__(self, request): def enclave(monkeypatch): enclave = Enclave() client = httpx.Client(transport=httpx.MockTransport(enclave)) - monkeypatch.setattr(sp, "_upstream", lambda: (client, {"Authorization": "Bearer t"})) + monkeypatch.setattr(sp, "_upstream", lambda refused=None: (client, {"Authorization": "Bearer t"})) return enclave @@ -75,24 +77,27 @@ def enclave(monkeypatch): def bridge(monkeypatch, tmp_path): monkeypatch.setattr(sp, "_backoff", lambda attempt: None) monkeypatch.setattr(sp, "_wait", lambda seconds: None) - monkeypatch.setattr(sp, "_last_break", 0.0) + monkeypatch.setattr(sp, "_broke", {}) monkeypatch.setattr(sp, "LOG", str(tmp_path / "log")) + monkeypatch.setattr(sp.ghost_auth, "BRIDGE_KEY_FILE", tmp_path / "bridge.key") for name, value in (("DIR", tmp_path), ("LEDGER", tmp_path / "spend.jsonl"), ("BUDGET_FILE", tmp_path / "budget")): monkeypatch.setattr(spend, name, value) monkeypatch.setattr(spend, "_entries", None) server = ThreadingHTTPServer(("127.0.0.1", 0), sp.Handler) threading.Thread(target=server.serve_forever, daemon=True).start() - def ask(stream=True, origin=None, **extra): + ask_headers = {"Content-Type": "application/json", "Authorization": f"Bearer {sp.ghost_auth.bridge_token()}"} + + def ask(stream=True, headers=None, **extra): body = {"model": MODEL, "stream": stream, "messages": [{"role": "user", "content": "rewrite these scenes"}], **extra} req = urllib.request.Request(f"http://127.0.0.1:{server.server_port}/v1/chat/completions", - json.dumps(body).encode(), {"Content-Type": "application/json", **({"Origin": origin} if origin else {})}) + json.dumps(body).encode(), {**ask_headers, **(headers or {})}) try: with urllib.request.urlopen(req, timeout=10) as resp: return resp.status, resp.read().decode() except urllib.error.HTTPError as e: return e.code, json.loads(e.read())["error"]["message"] - ask.url = f"http://127.0.0.1:{server.server_port}" + ask.url, ask.port, ask.headers = f"http://127.0.0.1:{server.server_port}", server.server_port, ask_headers yield ask server.shutdown() server.server_close() @@ -162,10 +167,84 @@ def test_connection_lost_after_acceptance_is_not_retried_here(enclave, bridge): assert len(enclave.accepted) == 2 # one per request the engine made -def test_a_good_reply_clears_the_streak(enclave, bridge): - broken = sse(text("partial"), done=False) - enclave.replies = [broken, sse(text("hi"), closing()), broken] - assert [bridge()[0] for _ in range(3)] == [502, 200, 502] +def test_each_request_has_its_own_streak(enclave, bridge): + """Three windows and one blip: none of them is on its second break. And one window's luck is not another's.""" + enclave.replies = [sse(text("partial"), done=False)] + windows = [{"messages": [{"role": "user", "content": f"window {i}"}]} for i in range(3)] + assert [bridge(**w)[0] for w in windows] == [502] * 3 + enclave.replies, enclave.seen = [sse(text("hi"), closing())], 0 + assert bridge(messages=[{"role": "user", "content": "window 4"}])[0] == 200 + enclave.replies, enclave.seen = [sse(text("partial"), done=False)], 0 + assert [bridge(**w)[0] for w in windows] == [422] * 3 + + +def test_a_login_that_is_refused_is_renewed_once(monkeypatch, enclave, bridge): + """This machine's clock may be behind, so an access token is only known to be old when it's turned away.""" + asked = [] + + def upstream(refused=None): + asked.append(refused) + return httpx.Client(transport=httpx.MockTransport(enclave)), {"Authorization": "Bearer renewed" if refused else "Bearer old"} + monkeypatch.setattr(sp, "_upstream", upstream) + monkeypatch.setattr(sp.ghost_auth, "api_key", lambda: None) + refusal = httpx.Response(401, json={"error": {"message": "x"}}) + enclave.replies = [refusal, sse(text("hi"), closing())] + assert bridge()[0] == 200 and asked == [None, "old"] + enclave.replies, enclave.seen, asked[:] = [refusal], 0, [] + assert bridge()[0] == 401 and asked == [None, "old"] and enclave.seen == 2 + + +def test_a_login_that_cannot_be_renewed_just_now_is_not_called_expired(monkeypatch, enclave, bridge): + def upstream(refused=None): + raise sp.ghost_auth.Unavailable("couldn't reach DreamFort to renew your login (ConnectError)") + monkeypatch.setattr(sp, "_upstream", upstream) + status, message = bridge() + assert status == 503 and "couldn't reach DreamFort" in message # which the engine tries again, and 401 not + + +def test_nothing_is_paid_for_someone_who_has_gone(monkeypatch, enclave, bridge): + """Ctrl-C while the bridge waits for a busy relay.""" + arrived, gone = threading.Event(), threading.Event() + monkeypatch.setattr(sp, "_wait", lambda seconds: (arrived.set(), gone.wait(5))) + enclave.replies = [httpx.Response(429, json={"error": "Rate limit exceeded"}), sse(text("hi"), closing())] + body = json.dumps({"model": MODEL, "messages": [{"role": "user", "content": "x"}]}).encode() + sock = socket.create_connection(("127.0.0.1", bridge.port)) + sock.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\n" + "".join(f"{k}: {v}\r\n" for k, v in bridge.headers.items()).encode() + + f"Content-Length: {len(body)}\r\n\r\n".encode() + body) + assert arrived.wait(5) + sock.close() + time.sleep(0.2) + gone.set() + time.sleep(0.5) + assert enclave.seen == 1 and enclave.accepted == [] + with open(sp.LOG) as fh: + assert "whoever asked has gone" in fh.read() + + +def test_a_login_page_is_not_an_enclave(enclave): + """A hotel's, say: it answers 200 for everyone, and that's not a reply that was paid for.""" + for answer in (httpx.Response(200, html="Welcome"), httpx.Response(302, headers={"Location": "https://hotel.example"}), + httpx.Response(200, json={"ok": True})): + relay = sp.Relay(httpx.MockTransport(lambda request, answer=answer: answer)) + got = relay.handle_request(httpx.Request("POST", "https://relay.example/x")) + assert got.status_code == 502 and "answers instead of DreamFort" in got.json()["detail"] + sealed = httpx.Response(200, headers={"content-type": "message/ohttp-chunked-res"}, content=b"x") + assert sp.Relay(httpx.MockTransport(lambda request: sealed)).handle_request(httpx.Request("POST", "https://relay.example/x")) is sealed + + +# ── your name stays here ────────────────────────────────────────────────────── +def test_the_engines_own_prompt_does_not_name_you(monkeypatch, enclave, bridge): + monkeypatch.setattr(sp, "_HOME", re.compile("(?:/Users/jane)(?![\\w-])(?!\\.\\w)")) + prompt = "Home: /Users/jane\nFolder: /Users/jane/work, data /Users/jane/.ghost/x. Not /Users/janet/y or /Users/jane.doe/z. In /Users/jane." + bridge(messages=[{"role": "system", "content": prompt}, {"role": "user", "content": "is /Users/jane/x mine?"}]) + system, user = enclave.accepted[0]["messages"] + assert system["content"] == "Home: ~\nFolder: ~/work, data ~/.ghost/x. Not /Users/janet/y or /Users/jane.doe/z. In ~." + assert user["content"] == "is /Users/jane/x mine?" # yours, as you wrote it + + +def test_home_is_this_users(monkeypatch): + monkeypatch.setenv("USERPROFILE" if os.name == "nt" else "HOME", os.path.join(os.sep, "home", "mara")) + assert os.path.expanduser("~") in sp._homes() # ── not accepted, so not billed: safe to retry ──────────────────────────────── @@ -198,7 +277,7 @@ def test_a_busy_relay_is_waited_out(enclave, bridge, monkeypatch): def test_not_logged_in_fails_at_once(monkeypatch, enclave, bridge): - def nobody(): + def nobody(refused=None): raise sp.AuthError(sp.ghost_auth.NOT_LOGGED_IN) monkeypatch.setattr(sp, "_upstream", nobody) started = time.time() @@ -225,7 +304,7 @@ def handle_request(self, request): monkeypatch.setattr(sp, "_upstream", REAL_UPSTREAM) monkeypatch.setattr(sp, "OHTTPTransport", Transport) monkeypatch.setattr(sp, "_clients", {}) - monkeypatch.setattr(sp.ghost_auth, "credentials", lambda: (relay, token)) + monkeypatch.setattr(sp.ghost_auth, "credentials", lambda refused=None: (relay, token)) monkeypatch.setattr(sp.ghost_auth, "api_key", lambda: token if login["mode"] == "api_key" else None) status, message = bridge() assert (status, seen) == (402, [(relay, f"Bearer {token}")]) and words in message @@ -252,7 +331,7 @@ def dream(monkeypatch): threading.Thread(target=server.serve_forever, daemon=True).start() url = f"http://127.0.0.1:{server.server_port}" monkeypatch.setattr(outbound, "transport", lambda url, public_only=False: fake_dreamfort.Redirected(server.server_port)) - monkeypatch.setattr(sp.ghost_auth, "credentials", lambda: (url + sp.ghost_auth.API_KEY_RELAY, fake_dreamfort.API_KEY)) + monkeypatch.setattr(sp.ghost_auth, "credentials", lambda refused=None: (url + sp.ghost_auth.API_KEY_RELAY, fake_dreamfort.API_KEY)) monkeypatch.setattr(sp.ghost_auth, "api_key", lambda: fake_dreamfort.API_KEY) monkeypatch.setattr(sp, "_clients", {}) yield service @@ -267,7 +346,7 @@ def says(content): def test_a_sealed_request_is_answered(dream, bridge): status, body = bridge(stream=False, **says("[[say hello there]]")) assert status == 200 and json.loads(body)["choices"][0]["message"]["content"] == "hello there" and len(dream.billed) == 1 - assert dream.accepted[0]["messages"] == [{"role": "user", "content": "[[say hello there]]"}] and spend.spent(3600) == pytest.approx(0.001) + assert dream.accepted[0]["messages"] == [{"role": "user", "content": "[[say hello there]]"}] and spend.spent(3600) == pytest.approx(0.001 * spend.MARKUP) BROKE = ("the connection to the enclave broke", "twice in a row") @@ -275,7 +354,8 @@ def test_a_sealed_request_is_answered(dream, bridge): # refused: not billed, and said plainly ("402", (402, 402), 0, ("out of credits",)), ("429", (429, 429), 0, ("Rate limit exceeded: 40 per 1 minute",)), ("451", (451, 451), 0, ("Content policy violation",)), ("503", (503, 503), 0, ("TEE OHTTP request failed",)), - ("page", (502, 502), 0, ("DreamFort isn't answering properly (502)",)), ("retired", (502, 502), 0, ("isn't active any more",)), + ("page", (502, 502), 0, ("DreamFort isn't answering properly (502)",)), ("slow", (504, 504), 0, ("no answer from the enclave",)), + ("portal", (502, 502), 0, ("answers instead of DreamFort",)), ("retired", (502, 502), 0, ("isn't active any more",)), # billed, maybe, but never delivered: the engine may try once more, and that's all ("504", (502, 422), 2, BROKE), ("silent", (502, 422), 2, BROKE), ("empty", (502, 422), 2, BROKE), ("cut", (502, 422), 2, BROKE), ("drop", (502, 422), 2, BROKE), ("forged", (502, 422), 2, ("without the enclave's signature", "twice in a row")), ("unsigned", (502, 422), 2, BROKE), @@ -283,7 +363,7 @@ def test_a_sealed_request_is_answered(dream, bridge): ("host400", (400, 400), 0, ("maximum context length",)), ("host503", (502, 502), 0, ("overloaded",)), ]) def test_however_a_request_fails(dream, bridge, kind, statuses, billed, words): - got = [bridge(**says(f"[[fail {kind}]] {i}")) for i in range(2)] + got = [bridge(**says(f"[[fail {kind}]]")) for _ in range(2)] # (the engine's retry is the same request) assert tuple(status for status, _ in got) == statuses and len(dream.billed) == billed assert all(any(word in message for _, message in got) for word in words) assert len(dream.accepted) <= 2 and (spend.spent(3600) > 0) == bool(billed) # what may have been billed counts @@ -302,6 +382,13 @@ def test_when_the_registry_cannot_be_read(monkeypatch, dream, bridge): assert bridge(**says("[[say three]]"))[0] == 200 and len(dream.billed) == 3 +def test_a_registry_that_lists_none_is_obeyed(monkeypatch, dream, bridge): + """All of them revoked, say. That is an answer, and no reason to use one it doesn't list.""" + monkeypatch.setattr(enclaves.Enclaves, "listed", lambda self: []) + status, message = bridge(**says("[[say hi]]")) + assert status == 503 and "lists no active enclave" in message and dream.accepted == [] + + def test_the_built_in_enclaves_are_the_apps_own(): """chat-app's lib/api/backupTees.ts and chat-api's src/core/backup_tees.py list the same one.""" assert [t.tee_id for t in enclaves.BUILT_IN] == ["0xe1443d7ed558fbd19117c4dc70e6245fc71d6063d64af3bc3f790081bc94e9aa"] @@ -311,7 +398,7 @@ def test_the_built_in_enclaves_are_the_apps_own(): # ── what else the bridge answers ────────────────────────────────────────────── @pytest.mark.parametrize("body", [b"", b"[]", b'"hi"', b"{", b"null"]) def test_nonsense_is_turned_away(enclave, bridge, body): - req = urllib.request.Request(f"{bridge.url}/v1/chat/completions", body, {"Content-Type": "application/json"}) + req = urllib.request.Request(f"{bridge.url}/v1/chat/completions", body, bridge.headers) with pytest.raises(urllib.error.HTTPError) as failed: urllib.request.urlopen(req, timeout=5) assert failed.value.code == 400 and enclave.seen == 0 @@ -335,7 +422,25 @@ def test_the_bridge_proves_that_it_is_yours(monkeypatch, tmp_path, bridge): def test_a_web_page_cannot_spend_your_credits(enclave, bridge): """Any site can make a browser POST to localhost; only the engine (which sends no Origin) is answered.""" - assert bridge(origin="https://evil.example")[0] == 403 and enclave.seen == 0 + assert bridge(headers={"Origin": "https://evil.example"})[0] == 403 and enclave.seen == 0 + + +@pytest.mark.parametrize("authorization", ["", "Bearer managed-by-ghost", "Bearer " + "0" * 40]) +def test_nor_can_anyone_else_on_this_machine(enclave, bridge, authorization): + """They can reach the port, but not the file only you can read.""" + status, message = bridge(headers={"Authorization": authorization}) + assert status == 403 and "ghost update" in message and enclave.seen == 0 + with pytest.raises(urllib.error.HTTPError): + urllib.request.urlopen(urllib.request.Request(bridge.url + "/check", headers={"Authorization": authorization}), timeout=5) + + +def test_the_doctor_is_told_what_the_bridge_can_reach(dream, bridge): + def check(): + with urllib.request.urlopen(urllib.request.Request(bridge.url + "/check", headers=bridge.headers), timeout=20) as resp: + return json.load(resp) + assert check() == {"relay": 200, "enclaves": 1} and dream.accepted == [] + dream.registry_up = False + assert check() == {"relay": 200, "enclaves": None} @pytest.mark.parametrize("path, key", [("/model-catalog.json", "providers"), ("/models-dev.json", "opengradient"), ("/v1/models", "data")]) @@ -367,15 +472,15 @@ def system(**extra): def test_spend_is_recorded_from_the_reply(enclave, bridge): enclave.replies = [sse(text("hi"), closing(cost="0.25"))] bridge() - assert spend.spent(3600) == pytest.approx(0.25) - assert json.loads(spend.LEDGER.read_text())["usd"] == 0.25 and "rewrite" not in spend.LEDGER.read_text() + assert spend.spent(3600) == pytest.approx(0.25 * 1.35) # what DreamFort charges for it + assert json.loads(spend.LEDGER.read_text())["usd"] == 0.3375 and "rewrite" not in spend.LEDGER.read_text() def test_budget_stops_a_runaway(enclave, bridge): enclave.replies = [sse(text("hi"), closing(cost="2.0"))] - statuses = [bridge()[0] for _ in range(5)] - assert statuses == [200, 200, 200, 422, 422] and len(enclave.accepted) == 3 # $5 default, checked before each - assert "ghost paused: $6.00" in bridge()[1] + statuses = [bridge()[0] for _ in range(4)] + assert statuses == [200, 200, 422, 422] and len(enclave.accepted) == 2 # $5 default, checked before each + assert "ghost paused: $5.40" in bridge()[1] @pytest.mark.parametrize("setting, allowed", [("off", True), ("20", True), ("1", False)]) diff --git a/tests/test_engine.py b/tests/test_engine.py index f5a60fc..b36e46a 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -154,6 +154,69 @@ def test_prefill_reaches_the_model(engine): assert out.endswith("/.ghost/privacy/uncensored_prefill.json") +def test_no_vendor_key_of_yours_is_used(engine): + """What the engine would act on if it found it in the environment, `ghost` takes out of it first.""" + known = engine(""" +from hermes_cli.auth import PROVIDER_REGISTRY +from hermes_cli.config import OPTIONAL_ENV_VARS +names = {v for p in PROVIDER_REGISTRY.values() for v in (*p.api_key_env_vars, p.base_url_env_var) if v} +out = sorted(names | {n for n, m in OPTIONAL_ENV_VARS.items() if m.get("category") in ("provider", "tool")}) +""") + sys.path.insert(0, str(REPO / "privacy")) + import launch + # the agent's own git and claude; which AWS account; and nothing else + spared = {"GITHUB_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "AWS_PROFILE", "AWS_REGION"} + assert not set(known) - launch.VENDOR_ENV - spared + + +def test_the_engine_without_settings_has_no_provider(engine, tmp_path): + """Pinned in its environment too, so a damaged config.yaml leads nowhere rather than to a vendor.""" + out = engine(""" +import os +os.environ["HERMES_INFERENCE_PROVIDER"] = "opengradient" +from hermes_cli import runtime_provider, config +config.load_config = lambda *a, **k: {} +try: + out = runtime_provider.resolve_runtime_provider().get("base_url") +except Exception as e: + out = "refused" +""") + assert out in ("refused", None, "") or "127.0.0.1" in out + + +def test_a_side_task_stays_on_its_own_model(engine): + assert engine("from agent.auxiliary_client import _try_main_agent_model_fallback as f\nout = list(f('opengradient', task='title_generation'))") == [None, None, ""] + + +def test_searches_ask_one_engine_at_a_time(engine): + asked = engine(""" +import sys, types +asked = [] +class DDGS: + def __init__(self, timeout=None): pass + def __enter__(self): return self + def __exit__(self, *a): pass + def text(self, query, max_results=None, backend=None): + asked.append(backend) + if backend == "brave": raise RuntimeError("blocked") + return [{"title": "t", "href": "https://x", "body": "b"}] if backend == "startpage" else [] +sys.modules["ddgs"] = types.SimpleNamespace(DDGS=DDGS) +from plugins.web.ddgs.provider import _run_ddgs_search +out = [asked, len(_run_ddgs_search("q", 5))] +""") + assert asked == [["duckduckgo", "brave", "startpage"], 1] + + +@pytest.mark.parametrize("command, rule", [ + ("python3 -c 'print(1)'", "script execution via -e/-c flag"), ("python3 -c 'print(1)'; chmod 777 notes.txt", "world/other-writable permissions"), + ("rm -r build", "recursive delete"), ("ls", None), +]) +def test_what_is_not_routine_about_a_command_decides(engine, profile, command, rule): + found = engine(f"from tools.approval_detection import detect_dangerous_command as d\nout = d({command!r})[1]") + assert found == rule + assert (rule in profile["command_allowlist"]) == (rule == "script execution via -e/-c flag") + + def test_long_chats_are_summarized_before_they_get_expensive(engine): """No prompt cache on the gateway: at $3/M a 500K-token chat would cost $1.50 a step.""" out = engine("from run_agent import AIAgent\nfrom hermes_cli.runtime_provider import resolve_runtime_provider\n" @@ -167,7 +230,8 @@ def test_long_chats_are_summarized_before_they_get_expensive(engine): def test_every_route_is_served_by_the_bridge(profile): bridge = (REPO / "privacy" / "bridge.py").read_text(encoding="utf-8") served = set(re.findall(r'(?m)^ \("([\w./-]+)", "', bridge.split("_CATALOG_MODELS = [", 1)[1].split("\n]", 1)[0])) - routes = [profile["model"]["default"], profile["fallback_model"]["model"]] + routes = [profile["model"]["default"]] + assert not profile.get("fallback_model") and not profile.get("fallback_providers") # falling back is answering again, at your expense routes += [route["model"] for route in profile["auxiliary"].values()] assert served and set(routes) - served == set() diff --git a/tests/test_install.py b/tests/test_install.py index 9dda1c9..410dde0 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -102,7 +102,7 @@ def do_GET(self): # as ghost's own bridge 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.send_header("X-Ghost-Proof", hmac.new(key.read_bytes(), b"proof " + self.path.partition("?")[2].encode(), "sha256").hexdigest()) self.end_headers() def log_message(self, *args): @@ -130,7 +130,7 @@ def test_fresh_install(machine, system): 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 + assert "ollama-local" not in config and "fallback_model:" not in config and not re.search("__[A-Z]", config) and f"{m.ghost}/privacy/uncensored_prefill.json" in config assert (m.profile / ".env").exists() and (m.ghost / "privacy" / "uncensored_prefill.json").exists() diff --git a/tests/test_launch.py b/tests/test_launch.py index 8255fa8..c7786a4 100644 --- a/tests/test_launch.py +++ b/tests/test_launch.py @@ -44,7 +44,7 @@ def __init__(self, root, monkeypatch): self.configure(HOSTED) for name, value in (("HOME", root), ("PRIV", root / "privacy"), ("PROFILE", self.profile), ("ENGINE", root / "engine")): monkeypatch.setattr(launch, name, value) - monkeypatch.setattr(launch, "run_engine", lambda args: self.ran.append(list(args)) or 0) + monkeypatch.setattr(launch, "run_engine", lambda args, provider="opengradient": self.ran.append(list(args)) or 0) monkeypatch.setattr(launch, "ensure_bridge", lambda: self.started.append(1) or True) monkeypatch.setattr(launch.ghost_auth, "KEY_FILE", root / "privacy" / "dreamfort_api_key") monkeypatch.setattr(launch.ghost_auth, "SESSION_FILE", root / "veil" / "session.json") @@ -132,6 +132,28 @@ def test_a_dead_bridge_is_reported_and_the_engine_still_runs(box, monkeypatch, c assert "background service isn't running" in capsys.readouterr().err +@pytest.mark.parametrize("config", ["", "model:\n default: gpt-9\n", HOSTED.replace(" opengradient:\n", " other:\n")]) +def test_without_its_settings_it_does_not_start(box, capsys, config): + """The engine would go by its own defaults then: any vendor whose key it finds.""" + box.log_in() + box.configure(config) + assert launch.main([]) == 1 and box.ran == [] and "ghost update" in capsys.readouterr().err + + +def test_what_you_typed_goes_when_the_chats_do(box): + history = box.profile / ".hermes_history" + old, new = (time.strftime("%Y-%m-%d %H:%M:%S.000000", time.localtime(time.time() - s)) for s in (90000, 3600)) + entries = {old: "\n# {}\n+my secret\n+# 2020-01-01 not a date line\n", new: "\n# {}\n+today\n"} + history.write_text("".join(text.format(at) for at, text in entries.items())) + box.log_in() + box.configure(HOSTED + "sessions:\n auto_prune: false\n retention_days: 1\n") + launch.main([]) + assert "my secret" in history.read_text() + box.configure(HOSTED + "sessions:\n auto_prune: true\n retention_days: 1\n") + launch.main([]) + assert history.read_text() == f"\n# {new}\n+today\n" + + 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) @@ -160,7 +182,10 @@ def test_asking_for_redaction_says_it_is_gone(box, capsys, flag): def test_local_contacts_nobody(box, monkeypatch, capsys): monkeypatch.setattr(launch.subprocess, "run", lambda *a, **k: subprocess.CompletedProcess(a, 0, "ghost-tool:latest 6GB", "")) assert launch.main(["--local", "-z", "hi"]) == 0 - assert box.ran == [["-m", "ghost-tool:latest", "--provider", "ollama-local", "-z", "hi"]] and box.started == [] + assert box.ran == [["-m", "ghost-tool:latest", "--provider", "ollama-local", "--toolsets", launch.LOCAL_TOOLS, "-z", "hi"]] and box.started == [] + assert not {"web", "browser", "image_gen", "delegation"} & set(launch.LOCAL_TOOLS.split(",")) # nothing that reaches out by itself + launch.main(["--local", "-t", "web", "-z", "hi"]) + assert box.ran[-1] == ["-m", "ghost-tool:latest", "--provider", "ollama-local", "-t", "web", "-z", "hi"] # unless you ask for it box.configure(HOSTED[:HOSTED.index(" ollama-local:")]) # Ollama is there, but ghost wasn't installed with it assert launch.main(["--local"]) == 1 and "no local model installed" in capsys.readouterr().err box.configure(HOSTED) @@ -174,7 +199,7 @@ def test_settings_are_read_from_the_shipped_profile(): for text, offline in ((shipped, True), (HOSTED, False), (OFFLINE, True)): assert launch.default_model(text) == "abliterated-model-large-v2" and launch.local_fallback(text) is offline assert launch.local_model(HOSTED) == "ghost-tool:latest" - assert launch.default_model("") == "ghost" and launch.local_fallback("") is False + assert launch.default_model("") is None and launch.local_fallback("") is False def test_a_refreshed_nous_login_stays_on_the_bridge(box): @@ -269,12 +294,12 @@ def test_our_own_bridge_process(tmp_path, monkeypatch): def test_the_engine_gets_ghosts_profile_and_not_your_api_key(tmp_path): engine = tmp_path / "engine" / ".hermes" / "bin" / "hermes" engine.parent.mkdir(parents=True) - engine.write_text('#!/bin/sh\necho "$HERMES_HOME|$ANTHROPIC_API_KEY|$*"\nexit 7\n') + engine.write_text('#!/bin/sh\necho "$HERMES_HOME|$ANTHROPIC_API_KEY$OPENROUTER_API_KEY$FAL_KEY|$HERMES_INFERENCE_PROVIDER|$MY_API_KEY|$*"\nexit 7\n') engine.chmod(0o755) - env = {**os.environ, "GHOST_HOME": str(tmp_path / "state"), "GHOST_ENGINE": str(tmp_path / "engine"), - "ANTHROPIC_API_KEY": "sk-secret", "HERMES_HOME": "/somewhere/else"} + env = {**os.environ, "GHOST_HOME": str(tmp_path / "state"), "GHOST_ENGINE": str(tmp_path / "engine"), "OPENROUTER_API_KEY": "sk-secret", + "FAL_KEY": "secret", "ANTHROPIC_API_KEY": "sk-secret", "HERMES_HOME": "/somewhere/else", "HERMES_INFERENCE_PROVIDER": "openrouter", "MY_API_KEY": "mine"} done = subprocess.run([sys.executable, "-Es", launch.__file__, "sessions", "list", "a b"], env=env, capture_output=True, text=True, timeout=30) - assert (done.returncode, done.stdout) == (7, f"{tmp_path / 'state'}||-p uncensored sessions list a b\n") + assert (done.returncode, done.stdout) == (7, f"{tmp_path / 'state'}||opengradient|mine|-p uncensored sessions list a b\n") def test_a_missing_engine_is_explained(tmp_path): diff --git a/tests/test_login.py b/tests/test_login.py index c0674a5..30b1cf3 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -304,8 +304,17 @@ def machine(dream, tmp_path, monkeypatch): monkeypatch.setattr(spend, "_entries", [(time.time(), 0.21)]) monkeypatch.setattr(spend, "BUDGET_FILE", tmp_path / "budget") monkeypatch.setattr(spend, "LEDGER", tmp_path / "spend.jsonl") - monkeypatch.setattr("enclaves.Enclaves.listed", lambda self: 3) - return doctor + import bridge + import enclaves + monkeypatch.setattr("enclaves.Enclaves.listed", lambda self: [1, 2, 3]) + monkeypatch.setattr(ghost_auth, "BRIDGE_KEY_FILE", tmp_path / "bridge.key") + monkeypatch.setattr(bridge, "LOG", str(tmp_path / "bridge.log")) + server = bridge.LocalServer(("127.0.0.1", 0), bridge.Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + monkeypatch.setattr(launch, "PORT", server.server_port) + yield doctor + server.shutdown() + server.server_close() def test_doctor_when_all_is_well(dream, machine, capsys): @@ -332,7 +341,7 @@ def test_doctor_contacts_nobody_before_you_log_in(dream, machine, capsys): (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"), + "✗ Bridge isn't running: another program is using port"), (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"), ]) diff --git a/tests/test_outbound.py b/tests/test_outbound.py index 7f16999..20b6ccc 100644 --- a/tests/test_outbound.py +++ b/tests/test_outbound.py @@ -1,4 +1,5 @@ """Company networks: the system's proxy and certificates, and the one read that trusts neither.""" +import os import socket import ssl import sys @@ -19,6 +20,7 @@ def no_proxy_of_this_machine(monkeypatch): for name in PROXY_VARIABLES: monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(outbound, "NOTE", Path(os.devnull) / "none") monkeypatch.setattr(outbound.urllib.request, "getproxies", outbound.urllib.request.getproxies_environment) monkeypatch.setattr(outbound.urllib.request, "proxy_bypass", outbound.urllib.request.proxy_bypass_environment) @@ -30,7 +32,7 @@ def no_proxy_of_this_machine(monkeypatch): ({"ALL_PROXY": "http://proxy.corp:8080"}, "https://chat-api.example/x", "http://proxy.corp:8080"), ({"HTTP_PROXY": "http://proxy.corp:8080"}, "https://chat-api.example/x", None), ({"HTTPS_PROXY": "http://proxy.corp:8080", "NO_PROXY": ".example"}, "https://chat-api.example/x", None), - ({"HTTPS_PROXY": "socks5://proxy.corp:1080"}, "https://chat-api.example/x", None), + ({"ALL_PROXY": "socks5://127.0.0.1:9050"}, "https://chat-api.example/x", "socks5://127.0.0.1:9050"), # Tor, say ]) def test_which_proxy(monkeypatch, env, url, expect): for name, value in env.items(): @@ -38,6 +40,50 @@ def test_which_proxy(monkeypatch, env, url, expect): assert outbound.proxy(url) == expect +def test_a_proxy_that_cannot_be_used_is_not_gone_around(monkeypatch): + """That would show your address to whoever you were hiding it from.""" + monkeypatch.setenv("ALL_PROXY", "socks4://me:secret@127.0.0.1:9050") + with pytest.raises(httpx.ProxyError, match="can't use a proxy like 127.0.0.1:9050"): + outbound.transport("https://chat-api.example") + + +def test_socks_is_spoken(monkeypatch): + pytest.importorskip("socksio") + listener = socket.create_server(("127.0.0.1", 0)) + heard = [] + + def refuse(): + conn, _ = listener.accept() + heard.append(conn.recv(3)) + conn.sendall(b"\x05\xff") + conn.close() + threading.Thread(target=refuse, daemon=True).start() + monkeypatch.setenv("ALL_PROXY", f"socks5://127.0.0.1:{listener.getsockname()[1]}") + with httpx.Client(transport=outbound.transport("https://chat-api.example")) as client: + with pytest.raises(httpx.ProxyError): + client.get("https://chat-api.example/x") + assert heard[0][:1] == b"\x05" + + +def test_the_bridge_is_told_what_your_shell_sets(monkeypatch, tmp_path): + """It's a background service: launchd and systemd don't give it your shell's variables.""" + monkeypatch.setattr(outbound, "NOTE", tmp_path / "proxies.json") + monkeypatch.setenv("HTTPS_PROXY", "http://me:secret@proxy.corp:8080") + monkeypatch.setenv("NO_PROXY", "intranet.corp") + outbound.note() + for name in PROXY_VARIABLES: + monkeypatch.delenv(name, raising=False) + assert outbound.proxy("https://chat-api.example/x") == "http://me:secret@proxy.corp:8080" + assert outbound.proxy("https://intranet.corp/x") is None + assert os.name == "nt" or (tmp_path / "proxies.json").stat().st_mode & 0o77 == 0 + monkeypatch.setattr(sys.stdin, "isatty", lambda: False, raising=False) + outbound.note() # a cron job without them is no reason to forget + assert outbound.proxy("https://chat-api.example/x") + monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False) + outbound.note() # but you, at home, are + assert outbound.proxy("https://chat-api.example/x") is None + + @pytest.mark.parametrize("public_only", [False, True]) def test_the_relay_and_the_registry_are_reached_through_it(monkeypatch, public_only): listener = socket.create_server(("127.0.0.1", 0)) @@ -69,13 +115,13 @@ def test_the_bridge_reads_the_registry_that_way(monkeypatch): import bridge made = {} monkeypatch.setattr(bridge, "_clients", {}) - monkeypatch.setattr(bridge.ghost_auth, "credentials", lambda: ("https://relay.example/x", "t")) + monkeypatch.setattr(bridge.ghost_auth, "credentials", lambda refused=None: ("https://relay.example/x", "t")) monkeypatch.setattr(bridge.outbound, "transport", lambda url, **options: (url, options)) sealing = httpx.MockTransport(lambda request: None) monkeypatch.setattr(bridge, "OHTTPTransport", lambda **options: made.update(options) or sealing) bridge._upstream() from opengradient_ohttp import DEFAULT_RPC_URL - assert made["transport"] == ("https://relay.example/x", {}) + assert made["transport"].inner == ("https://relay.example/x", {}) assert sealing._resolver._transport == (DEFAULT_RPC_URL, {"public_only": True}) and sealing._resolver._rpc_url == DEFAULT_RPC_URL diff --git a/uv.lock b/uv.lock index 1102582..0d0ca8e 100644 --- a/uv.lock +++ b/uv.lock @@ -373,7 +373,7 @@ version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "certifi" }, - { name = "httpx" }, + { name = "httpx", extra = ["socks"] }, { name = "opengradient-ohttp" }, { name = "truststore" }, ] @@ -381,7 +381,7 @@ dependencies = [ [package.metadata] requires-dist = [ { name = "certifi" }, - { name = "httpx", specifier = ">=0.27" }, + { name = "httpx", extras = ["socks"], specifier = ">=0.27" }, { name = "opengradient-ohttp", specifier = ">=0.1,<0.2" }, { name = "truststore", specifier = ">=0.10" }, ] @@ -423,6 +423,11 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, ] +[package.optional-dependencies] +socks = [ + { name = "socksio" }, +] + [[package]] name = "idna" version = "3.18" @@ -732,6 +737,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/da/80/35b4c33c804a165a7f55289afda3ea9e3eb6d15800341a2d66455c0f1f30/regex-2026.5.9-cp314-cp314t-win_arm64.whl", hash = "sha256:5e41809d2683fcde7d5a8c87a6567ba1fb1ce0de9f31bff578de00a4b2d76daa", size = 275713, upload-time = "2026-05-09T23:15:16.98Z" }, ] +[[package]] +name = "socksio" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f8/5c/48a7d9495be3d1c651198fd99dbb6ce190e2274d0f28b9051307bdec6b85/socksio-1.0.0.tar.gz", hash = "sha256:f88beb3da5b5c38b9890469de67d0cb0f9d494b78b106ca1845f96c10b91c4ac", size = 19055, upload-time = "2020-04-17T15:50:34.664Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/37/c3/6eeb6034408dac0fa653d126c9204ade96b819c936e136c5e8a6897eee9c/socksio-1.0.0-py3-none-any.whl", hash = "sha256:95dc1f15f9b34e8d7b16f06d74b8ccf48f609af32ab33c608d08761c5dcbb1f3", size = 12763, upload-time = "2020-04-17T15:50:31.878Z" }, +] + [[package]] name = "toolz" version = "1.1.0" From cbd491137983869be3ecc9f373440d08c88bdc0d Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:54:57 +0000 Subject: [PATCH 05/15] 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 1daeeefb9dacc217cbb560cbdda54a031c8b360f Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:54:59 +0000 Subject: [PATCH 06/15] Leave an unchanged bridge running on update --- README.md | 2 +- bin/ghost-uninstall | 3 ++- bin/windows/ghost-uninstall.ps1 | 2 +- install.ps1 | 22 +++++++++++++-------- install.sh | 34 ++++++++++++++++++++------------- privacy/bridge.py | 2 ++ tests/test_install.py | 33 +++++++++++++++++++++++++------- 7 files changed, 67 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index a7f1a9b..af3f32b 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Set these as environment variables on the install command (`curl ... | GHOST_LOC | `GHOST_NO_BROWSER=1` | Skip Chromium and the computer-use driver: a smaller (1 GB), faster install. | | `GHOST_VERBOSE=1` | Show everything the installer runs. Otherwise it's in `~/.ghost/install.log`. | -On Windows, from a clone: `.\install.ps1 -Local -NoBrowser`. +On Windows, from a clone: `powershell -ExecutionPolicy Bypass -File .\install.ps1 -Local -NoBrowser`. An update installs that release's `config.yaml` and `SOUL.md`; if you changed yours, they're kept beside them as `.prev`. diff --git a/bin/ghost-uninstall b/bin/ghost-uninstall index b7f68ce..62ef844 100644 --- a/bin/ghost-uninstall +++ b/bin/ghost-uninstall @@ -129,7 +129,8 @@ if [ -n "$PURGE" ]; then 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/.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* + "$GHOST_HOME/privacy/uncensored_prefill.json" "$GHOST_HOME/privacy/bridge.key" "$GHOST_HOME/privacy/.made" \ + "$GHOST_HOME/privacy/proxies.json" "$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/windows/ghost-uninstall.ps1 b/bin/windows/ghost-uninstall.ps1 index 8cb9517..76cb20d 100644 --- a/bin/windows/ghost-uninstall.ps1 +++ b/bin/windows/ghost-uninstall.ps1 @@ -75,7 +75,7 @@ if ($purge) { 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-Hard "$GhostHome\$name" } + "privacy\bridge.key", "privacy\.made", "privacy\proxies.json", "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") { diff --git a/install.ps1 b/install.ps1 index af33829..3dae0dd 100644 --- a/install.ps1 +++ b/install.ps1 @@ -120,11 +120,16 @@ Write-Text "$GhostHome\.install-env" (($chosen | ForEach-Object { "$_`n" }) -joi # --- 2. the bridge --------------------------------------------------------------------------- Say "Installing the privacy bridge" -# Windows won't replace the files of a program that is running. -foreach ($task in "ghost-bridge", "ghost-scrubber", "ghost-veil") { Stop-ScheduledTask -TaskName $task -ErrorAction SilentlyContinue } -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 } +function Ask-Launch($what) { & $Py -Es -c "import sys; sys.path.insert(0, sys.argv[1]); import launch; print($what)" $Priv } +$made = (@(Get-ChildItem "$Repo\privacy\*.py" | Sort-Object Name | ForEach-Object { [IO.File]::ReadAllText($_.FullName) }) + [IO.File]::ReadAllText("$Repo\uv.lock")) -join "" +$made = (Get-FileHash -InputStream ([IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes($made)))).Hash +$same = (Test-Path "$Priv\.made") -and [IO.File]::ReadAllText("$Priv\.made") -eq $made -and (Test-Path $Py) -and "$(Ask-Launch 'launch.bridge_up()')" -eq "True" +if (-not $same) { # Windows won't replace the files of a program that is running + foreach ($task in "ghost-bridge", "ghost-scrubber", "ghost-veil") { Stop-ScheduledTask -TaskName $task -ErrorAction SilentlyContinue } + 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 } +} $env:UV_PROJECT_ENVIRONMENT = $Venv Push-Location $Repo @@ -180,7 +185,7 @@ $flags = @(); if ($LocalModel) { $flags += @("--local-model", $LocalModel) } # --- 6. the background service --------------------------------------------------------------- Say "Starting the background service" $Pyw = "$Venv\Scripts\pythonw.exe"; if (-not (Test-Path $Pyw)) { $Pyw = $Py } -try { +if (-not $same) { try { $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name $task = @{ TaskName = "ghost-bridge" @@ -191,9 +196,10 @@ try { -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) } Register-ScheduledTask @task -Force | Out-Null -} 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 +} catch { Write-Host " Task Scheduler refused it ($($_.Exception.Message.Trim())), so ghost starts it when needed." } } +$why = Ask-Launch "'' if launch.ensure_bridge() else launch.bridge_problem()" if ("$why".Trim() -or $LASTEXITCODE -ne 0) { throw "ghost's background service isn't running: $why" } +Write-Text "$Priv\.made" $made 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 } diff --git a/install.sh b/install.sh index 0a6d929..73288f6 100755 --- a/install.sh +++ b/install.sh @@ -90,13 +90,17 @@ one_at_a_time() { # (two would build the engine over each other) 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) + case "$([ -z "$pid" ] || command_of "$pid")" in *install*) + echo "ghost is already being installed or updated (pid $pid). Wait for that to finish." >&2; exit 1 ;; + esac # (or whoever left it there is gone) fi echo $$ > "$LOCK/pid" } +command_of() { # what a process is running, if it's there (minimal systems have no `ps`) + ps -ww -o command= -p "$1" 2>/dev/null || tr '\0' ' ' < "/proc/$1/cmdline" 2>/dev/null || true +} + remember() { # what `ghost update` and `ghost uninstall` need to know local name echo "$REPO" > "$GHOST_HOME/.src" @@ -276,21 +280,26 @@ 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, if it is ours (minimal systems have no `pkill`, nor `ps`) +stop_bridge() { # whichever process holds the port, as it says itself, if it is ours local pid 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 ;; - esac + case "$(command_of "$pid")" in *"$PRIV/"*) kill "$pid" || true ;; esac } +ask_launch() { GHOST_HOME="$GHOST_HOME" "$PYTHON" -Es -c "import sys; sys.path.insert(0, sys.argv[1]); import launch; print($1)" "$PRIV"; } + 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. start_service() { - local label unit + local label unit made file="$HOME/.config/systemd/user/ghost-bridge.service" + [ "$OS" != Darwin ] || file="$HOME/Library/LaunchAgents/ai.dreamfort.ghost.plist" + made="$(cat "$REPO"/privacy/*.py "$REPO/uv.lock" "$REPO/launchd/ai.dreamfort.ghost.plist" "$REPO/systemd/ghost-bridge.service" | git hash-object --stdin)" + if [ -f "$file" ] && [ "$(cat "$PRIV/.made" 2>/dev/null)" = "$made" ] && [ "$(ask_launch "launch.bridge_up()")" = True ]; then + return 0 # running, and nothing new: a background task may be in the middle of something + fi if [ "$OS" = Darwin ]; then local agents="$HOME/Library/LaunchAgents" domain; domain="gui/$(id -u)" mkdir -p "$agents" @@ -327,13 +336,10 @@ start_service() { 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" + why="$(ask_launch "'' if launch.ensure_bridge() else launch.bridge_problem()")" || why="its log is $PRIV/bridge.log" [ -z "$why" ] || die "ghost's background service isn't running: $why." + echo "$made" > "$PRIV/.made" } command_file() { @@ -345,6 +351,8 @@ command_file() { install_commands() { local name + for name 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/$name"; done # older releases' 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.") diff --git a/privacy/bridge.py b/privacy/bridge.py index 92b4481..59e2557 100755 --- a/privacy/bridge.py +++ b/privacy/bridge.py @@ -471,6 +471,8 @@ def _check(): with httpx.Client(transport=outbound.transport(relay), timeout=20) as client: resp = client.get(f"{relay}/config", headers={"Authorization": f"Bearer {token}"}) found["relay"] = resp.status_code + except ghost_auth.Unavailable as e: + found["unreachable"] = str(e) except AuthError as e: found["login"] = str(e) except httpx.HTTPError as e: diff --git a/tests/test_install.py b/tests/test_install.py index 410dde0..00b2681 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -58,7 +58,7 @@ def __init__(self, root, system, port, home="home"): directory.mkdir() for name in ("bin", "launchd", "systemd", "privacy", "profile", "scripts"): shutil.copytree(REPO / name, self.repo / name, ignore=shutil.ignore_patterns("__pycache__")) - for name in ("install.sh", "engine.pin", "models.txt"): + for name in ("install.sh", "engine.pin", "models.txt", "uv.lock"): shutil.copy(REPO / name, self.repo / name) (self.repo / "scripts" / "fork-engine.sh").write_text(FORK_ENGINE) launch = self.repo / "privacy" / "launch.py" @@ -161,7 +161,8 @@ def test_services_on_a_mac(machine): domain = f"gui/{os.getuid()}" assert calls == [*(f"launchctl bootout {domain}/{label}" for label in OLD_AGENTS), f"launchctl bootstrap {domain} {agents}/ai.dreamfort.ghost.plist"] - m.install() # again: the running one is replaced + (m.ghost / "privacy" / ".made").unlink() + m.install() # something new: the running one is replaced assert [c for c in m.calls() if c.startswith("launchctl")][3:] == [f"launchctl bootout {domain}/ai.dreamfort.ghost", calls[-1]] @@ -333,11 +334,29 @@ 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() + other = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)", "/x/.ghost-src/install.sh"]) + try: + (lock / "pid").write_text(str(other.pid)) # someone who is still at it + done = m.install() + assert done.returncode == 1 and "already being installed or updated" in done.stderr and not m.engine.exists() + finally: + other.kill() + other.wait() + for gone in (other.pid, 1): # and someone who isn't, or whose number someone else has now + (lock / "pid").write_text(str(gone)) + assert m.install().returncode == 0 and not lock.exists() + lock.mkdir() + + +def test_an_update_with_nothing_new_leaves_the_bridge_alone(machine): + """A background task may be in the middle of a reply, which is billed all the same.""" + m = machine("Darwin") + m.install() + (m.home / "calls").unlink() + assert m.install().returncode == 0 and not any(c.startswith("launchctl") for c in m.calls()) + bridge = m.repo / "privacy" / "bridge.py" + bridge.write_text(bridge.read_text(encoding="utf-8") + "# newer\n", encoding="utf-8") + assert m.install().returncode == 0 and any(c.startswith("launchctl bootstrap") for c in m.calls()) def test_nobody_else_can_look_into_it(machine): From 7c6bb0e25b7296fc49851d3d5c047f9de3e83ebb Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:55:52 +0000 Subject: [PATCH 07/15] CI: log in and use it, end to end, on every system --- .github/workflows/test.yml | 13 ++++- tests/e2e.py | 116 +++++++++++++++++++++++++++++++++++++ tests/fake_dreamfort.py | 8 ++- 3 files changed, 133 insertions(+), 4 deletions(-) create mode 100644 tests/e2e.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7b97338..dcd8abd 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -56,9 +56,16 @@ jobs: if ghost ghost-login --status; then exit 1; fi if echo df_sk_not_a_real_key | ghost ghost-login --with-api-key; then exit 1; fi ghost ghost usage - code=$(curl -s -o reply -w '%{http_code}' http://127.0.0.1:8788/v1/chat/completions -H 'content-type: application/json' \ - -d '{"model": "abliteration/abliterated-model-large-v2", "messages": [{"role": "user", "content": "hi"}]}') - cat reply; test "$code" = 401 + token=$(sed -n 's/^ api_key: \([0-9a-f]\{40\}\).*$/\1/p' "$HOME/.ghost/profiles/uncensored/config.yaml"); test -n "$token" + post() { curl -s -o reply -w '%{http_code}' http://127.0.0.1:8788/v1/chat/completions -H 'content-type: application/json' "$@" \ + -d '{"model": "abliteration/abliterated-model-large-v2", "messages": [{"role": "user", "content": "hi"}]}'; } + test "$(post)" = 403 # the bridge answers this ghost only + test "$(post -H "Authorization: Bearer $token")" = 401; cat reply + - name: Log in and use it, against a stand-in for DreamFort + shell: bash + run: | + case "$RUNNER_OS" in Windows) py="$HOME/.ghost/venv/Scripts/python.exe" ;; *) py="$HOME/.ghost/venv/bin/python" ;; esac + "$py" tests/e2e.py - name: Update over it, with the background gateway running if: runner.os != 'Windows' run: | diff --git a/tests/e2e.py b/tests/e2e.py new file mode 100644 index 0000000..0e294ed --- /dev/null +++ b/tests/e2e.py @@ -0,0 +1,116 @@ +"""The ghost installed on this machine, end to end, against the stand-in DreamFort (fake_dreamfort.py). + +CI runs it after installing. It takes the bridge's place, so don't run it on a machine whose ghost you use: + + ~/.ghost/venv/bin/python tests/e2e.py +""" +import json +import os +import platform +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +HERE, HOME = Path(__file__).resolve().parent, Path.home() +GHOST, BIN, PORT, LOG = HOME / ".ghost", HOME / ".local" / "bin", 38990, HOME / "e2e-requests.jsonl" +WINDOWS = os.name == "nt" +ENV = {**os.environ, "GHOST_CHAT_API_URL": f"http://127.0.0.1:{PORT}", "OPENROUTER_API_KEY": "sk-or-not-yours", "PYTHONUTF8": "1"} + + +def run(name, *args, stdin="", timeout=240): + command = [str(BIN / (name + (".cmd" if WINDOWS else ""))), *args] + done = subprocess.run(command, input=stdin, env=ENV, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout) + return done.returncode, done.stdout + done.stderr + + +def requests(): + rows = [json.loads(line) for line in LOG.read_text(encoding="utf-8").splitlines()] + LOG.write_text("", encoding="utf-8") + return rows + + +def up(): + try: + with urllib.request.urlopen("http://127.0.0.1:8788/healthz", timeout=2) as resp: + return int(resp.headers["X-Ghost-Pid"]) + except OSError: + return None + + +def service(verb): + """Stop or start the real bridge.""" + if platform.system() == "Darwin": + domain, plist = f"gui/{os.getuid()}", HOME / "Library/LaunchAgents/ai.dreamfort.ghost.plist" + command = ["launchctl", "bootout", f"{domain}/ai.dreamfort.ghost"] if verb == "stop" else ["launchctl", "bootstrap", domain, str(plist)] + elif WINDOWS: + command = ["schtasks", "/end" if verb == "stop" else "/run", "/tn", "ghost-bridge"] + else: + command = ["systemctl", "--user", verb, "ghost-bridge.service"] + subprocess.run(command, capture_output=True) + pid = up() + if verb == "stop" and pid: # one ghost started itself + subprocess.run(["taskkill", "/f", "/pid", str(pid)] if WINDOWS else ["kill", str(pid)], capture_output=True) + + +def check(what, ok, shown=""): + print(f" {'ok ' if ok else 'BAD'} {what}" + ("" if ok else f"\n{shown}"), flush=True) + return ok + + +def main(): + service("stop") + deadline = time.time() + 30 + while up() and time.time() < deadline: + time.sleep(0.5) + LOG.write_text("", encoding="utf-8") + fake = [sys.executable, str(HERE / "fake_dreamfort.py"), str(PORT)] + started = [subprocess.Popen([*fake, str(LOG)]), + subprocess.Popen([*fake, "--bridge", str(GHOST / "privacy" / "bridge.py")], env={**os.environ, "GHOST_HOME": str(GHOST)})] + good = True + try: + deadline = time.time() + 60 + while not up(): + assert time.time() < deadline, "the bridge didn't start" + time.sleep(0.5) + code, out = run("ghost-login", "--with-api-key", stdin="df_sk_wrong\n") + good &= check("a bad key is turned away", code != 0 and "doesn't accept that key" in out, out) + code, out = run("ghost-login", "--with-api-key", stdin="df_sk_good0000\n") + good &= check("a good one isn't", code == 0, out) + + requests() + code, out = run("ghost", "-z", "[[say hello from the stand-in]]") + asked = requests() + good &= check("it answers", code == 0 and "hello from the stand-in" in out, out) + good &= check("for one request, with its limits", [(r["accepted"], r["max_tokens"], r["effort"]) for r in asked][:1] + == [("abliterated-model-large-v2", 32000, "low")] and len(asked) <= 2, asked) + good &= check("which doesn't name you", not any(r["named"] for r in asked), asked) + + code, out = run("ghost", "-z", "[[run echo made-by-ghost]]", "--yolo") + good &= check("it runs a command", "ran: " in out and "made-by-ghost" in out, out) + requests() + code, out = run("ghost", "-z", "[[fail cut]]") + good &= check("a reply that breaks off is paid for twice at most", sum(r.get("billed", False) for r in requests()) <= 2 and "stopped retrying" in out, out) + code, out = run("ghost", "-z", "[[fail 402]]") + good &= check("no credits is said plainly", "credits" in out and not requests()[0].get("billed"), out) + + code, out = run("ghost", "sessions", "list") + good &= check("the chat is there", code == 0 and "hello from the stand-in" in out, out) + code, out = run("ghost", "doctor") + good &= check("doctor is content", code == 0 and "login accepted" in out and "1 in the registry" in out, out) + code, out = run("ghost", "usage") + good &= check("usage counts", code == 0 and "Last hour" in out and "0 replies" not in out.splitlines()[0], out) + code, out = run("ghost", "logout") + good &= check("logged out", code == 0 and run("ghost-login", "--status")[0] != 0, out) + finally: + for process in started: + process.kill() + process.wait() + LOG.unlink(missing_ok=True) + service("start") + return 0 if good else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/fake_dreamfort.py b/tests/fake_dreamfort.py index 4458872..38e704b 100644 --- a/tests/fake_dreamfort.py +++ b/tests/fake_dreamfort.py @@ -106,6 +106,12 @@ def asked(inner): after.append(content) return text, after + @staticmethod + def names(inner): + """Does the harness's own prompt say whose machine this is?""" + home = os.path.expanduser("~") + return any(home in str(m.get("content")) or home.replace("\\", "/") in str(m.get("content")) for m in inner["messages"] if m["role"] == "system") + def failure(self, text): found = re.search(r"\[\[fail (\w+) ?(\d*)\]\]", text) if not found: @@ -190,7 +196,7 @@ def relay(self, body): if billed: service.billed.append(inner) service.note(accepted=inner["model"], billed=billed, kind=kind, max_tokens=inner.get("max_tokens"), effort=inner.get("reasoning_effort"), - tools=len(inner.get("tools") or []), asked=service.asked(inner)[0][:80]) + tools=len(inner.get("tools") or []), asked=service.asked(inner)[0][:80], named=service.names(inner)) if kind == "504": return self.send(*refused, "text/html") self.close_connection = True From 275099f9307aea4c88ae1905c0ba7ef95f99cf43 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 18:59:37 +0000 Subject: [PATCH 08/15] An update keeps your settings --- .github/workflows/test.yml | 8 +- README.md | 2 +- pyproject.toml | 2 + scripts/write_profile.py | 137 +++++++++++++++++++++++++---- tests/test_install.py | 16 ++-- tests/test_profile.py | 175 +++++++++++++++++++++++++++++++++++++ uv.lock | 11 +++ 7 files changed, 319 insertions(+), 32 deletions(-) create mode 100644 tests/test_profile.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dcd8abd..3939035 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,7 +13,7 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.11" - - run: pip install pytest "httpx[socks]" truststore "opengradient-ohttp>=0.1,<0.2" + - run: pip install pytest "httpx[socks]" truststore ruamel.yaml "opengradient-ohttp>=0.1,<0.2" - run: pytest tests/ -q # The real thing: install ghost the way a user does, use it before logging in, and check the engine it built. @@ -33,7 +33,7 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.11" - - run: pip install pytest "httpx[socks]" truststore "opengradient-ohttp>=0.1,<0.2" + - run: pip install pytest "httpx[socks]" truststore ruamel.yaml "opengradient-ohttp>=0.1,<0.2" - name: Install ghost if: runner.os != 'Windows' run: set -o pipefail; ./install.sh | tee "$HOME/install.txt" @@ -71,7 +71,7 @@ jobs: run: | ghost="$HOME/.local/bin/ghost" pid() { python -c "import json, pathlib; print(json.loads((pathlib.Path.home() / '.ghost/profiles/uncensored/gateway_state.json').read_text())['pid'])"; } - profile="$HOME/.ghost/profiles/uncensored"; echo "# mine" | tee -a "$profile/SOUL.md" >> "$profile/config.yaml" + profile="$HOME/.ghost/profiles/uncensored"; echo "# mine" >> "$profile/SOUL.md"; "$ghost" config set display.show_reasoning true "$ghost" gateway install --start-now --start-on-login sleep 15; "$ghost" gateway status; before="$(pid)"; kill -0 "$before" started=$SECONDS; ./install.sh # nothing new: the engine isn't built again, and the gateway is left alone @@ -81,7 +81,7 @@ jobs: sleep 15; "$ghost" gateway status; after="$(pid)"; kill -0 "$after" test "$before" != "$after"; if kill -0 "$before" 2>/dev/null; then exit 1; fi test ! -e "$HOME/.ghost/.restart-gateway" - for f in SOUL.md config.yaml; do grep -q "# mine" "$profile/$f.prev"; if grep -q "# mine" "$profile/$f"; then exit 1; fi; done + grep -q "# mine" "$profile/SOUL.md"; grep -q "show_reasoning: true" "$profile/config.yaml"; if ls "$profile"/*.prev*; then exit 1; fi curl -fs http://127.0.0.1:8788/healthz - name: Check the engine shell: bash diff --git a/README.md b/README.md index af3f32b..bf491ec 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Set these as environment variables on the install command (`curl ... | GHOST_LOC On Windows, from a clone: `powershell -ExecutionPolicy Bypass -File .\install.ps1 -Local -NoBrowser`. -An update installs that release's `config.yaml` and `SOUL.md`; if you changed yours, they're kept beside them as `.prev`. +An update keeps the settings you changed in `~/.ghost/profiles/uncensored/config.yaml`, and a `SOUL.md` of your own (the release's is then beside it, as `SOUL.md.new`). **On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`) and the certificates the system trusts. It needs to reach `chat-api.memchat.io`, and `ogevmdevnet.opengradient.ai`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection, and falls back to an enclave built into the release. diff --git a/pyproject.toml b/pyproject.toml index f18c973..6c7a64c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,8 @@ dependencies = [ # The certificates this machine trusts, for networks with one of their own. "truststore>=0.10", "certifi", + # Puts your settings back on top of a new release's, comments and all (scripts/write_profile.py). + "ruamel-yaml>=0.18", ] [tool.uv] diff --git a/scripts/write_profile.py b/scripts/write_profile.py index 0d1da18..c9ecc78 100644 --- a/scripts/write_profile.py +++ b/scripts/write_profile.py @@ -1,12 +1,15 @@ #!/usr/bin/env python3 """Write ghost's profile for the options chosen at install time (both installers use this). -This release's config.yaml and SOUL.md replace the ones there; what you had is kept beside them as `.prev` -when it differs. +An update brings a new config.yaml and SOUL.md. What you changed stays changed: each is kept as it was shipped +(in .shipped, beside them), so your changes can be told from the release's and put back on top of the new ones +(the file as it was is then in config.yaml.before-update). A SOUL.md of yours is left alone, with the new one beside it as SOUL.md.new. Where yours can't be told apart (an +older ghost kept no copy, or a config.yaml isn't YAML any more), it is set aside as `.prev`. write_profile.py PROFILE_DIR --ghost-home DIR [--local-model NAME] """ import argparse +import io import os import re import sys @@ -14,6 +17,9 @@ SOURCE = Path(__file__).resolve().parent.parent / "profile" SIDE_TASKS = "abliteration/deepseek-v4.1-flash-abliterated" +# The release's whatever you do: the engine's schema, and what connects it to the bridge. +OURS = {("_config_version",), ("providers", "opengradient", "api_key"), ("prefill_messages_file",)} +DELETED = object() def config(ghost_home, local_model=None): @@ -30,16 +36,84 @@ def config(ghost_home, local_model=None): return text -def install(path, text, keep=True): - """Returns where the previous version went, if it differed.""" - previous = None - if path.exists() and keep: - if path.read_bytes() == text.encode("utf-8"): - return None - previous = path.with_name(path.name + ".prev") - os.replace(path, previous) - path.write_bytes(text.encode("utf-8")) - return previous +# ── what you changed ────────────────────────────────────────────────────────── +def changes(shipped, yours, path=()): + """(path, value) of every setting that isn't as it was shipped.""" + for key in [*shipped, *(k for k in yours if k not in shipped)]: + here = (*path, key) + if here in OURS: + continue + if key not in yours: + yield here, DELETED + elif key in shipped and isinstance(shipped[key], dict) and isinstance(yours[key], dict): + yield from changes(shipped[key], yours[key], here) + elif key not in shipped or shipped[key] != yours[key]: + yield here, yours[key] + + +def put(settings, path, value): + for key in path[:-1]: + if not isinstance(settings.get(key), dict): + if value is DELETED: + return + settings[key] = {} + settings = settings[key] + if value is DELETED: + settings.pop(path[-1], None) + else: + settings[path[-1]] = value + + +def merged(shipped, yours, new): + """This release's config.yaml with your changes on it. None when yours can't be read.""" + from ruamel.yaml import YAML + from ruamel.yaml.error import YAMLError + yaml = YAML() + yaml.preserve_quotes, yaml.width = True, 120 + yaml.indent(mapping=2, sequence=4, offset=2) + try: + before, mine, after = (yaml.load(text) for text in (shipped, yours, new)) + except YAMLError: + return None + if not isinstance(mine, dict) or not isinstance(before, dict): + return None + found = list(changes(before, mine)) + for path, value in found: + put(after, path, value) + if after == mine: # nothing new: as you laid it out, with your comments + return yours + if not found: + return new + out = io.StringIO() + yaml.dump(after, out) + return out.getvalue() + + +# ── writing ─────────────────────────────────────────────────────────────────── +def write(path, text): + """In one move, readable by you only.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "wb") as fh: + fh.write(text.encode("utf-8")) + os.replace(tmp, path) + + +def read(path): + try: + return path.read_bytes().decode("utf-8").replace("\r\n", "\n") + except (OSError, UnicodeDecodeError): + return None + + +def set_aside(path): + previous, n = path.with_name(path.name + ".prev"), 1 + while previous.exists(): # an earlier one may be all there is of something + n += 1 + previous = path.with_name(f"{path.name}.prev-{n}") + os.replace(path, previous) + print(f"your previous {path.name} is kept as {previous}") def main(argv=None): @@ -49,17 +123,42 @@ def main(argv=None): parser.add_argument("--local-model") args = parser.parse_args(argv) args.profile.mkdir(parents=True, exist_ok=True) - yours = (args.profile / "config.yaml").exists() # in a new profile, a SOUL.md is only the engine's default - for name, text in (("config.yaml", config(args.ghost_home, args.local_model)), - ("SOUL.md", (SOURCE / "SOUL.md").read_text(encoding="utf-8"))): - previous = install(args.profile / name, text, keep=yours) - if previous: - print(f"your previous {name} is kept as {previous}") + settings, soul, kept = args.profile / "config.yaml", args.profile / "SOUL.md", args.profile / ".shipped" + had_settings = settings.exists() # in a new profile, a SOUL.md is only the engine's default + + new, yours, shipped = config(args.ghost_home, args.local_model), read(settings), read(kept / "config.yaml") + final = new + if yours is not None and yours != new: + final = merged(shipped, yours, new) if shipped is not None else None + if final is None: + set_aside(settings) + final = new + elif final != yours and yours != shipped: + write(settings.with_name("config.yaml.before-update"), yours) # comments of yours, say + elif settings.exists() and yours is None: + set_aside(settings) + if final != yours: + write(settings, final) + write(kept / "config.yaml", new) + + new, yours, shipped = (SOURCE / "SOUL.md").read_text(encoding="utf-8"), read(soul), read(kept / "SOUL.md") + if yours is None or yours == new or yours == shipped or not had_settings: + if yours != new: + write(soul, new) + soul.with_name("SOUL.md.new").unlink(missing_ok=True) + elif shipped is None: + set_aside(soul) + write(soul, new) + elif shipped != new: + write(soul.with_name("SOUL.md.new"), new) + print(f"your own SOUL.md is kept; this release's is beside it as {soul.with_name('SOUL.md.new')}") + write(kept / "SOUL.md", new) + for cache in ("provider_models_cache.json", "models_dev_cache.json", "cache/model_catalog.json"): (args.profile / cache).unlink(missing_ok=True) # what /model lists, which a new release may have changed env = args.profile / ".env" if not env.exists(): - env.write_bytes((SOURCE / ".env.example").read_bytes()) + write(env, (SOURCE / ".env.example").read_text(encoding="utf-8")) if __name__ == "__main__": diff --git a/tests/test_install.py b/tests/test_install.py index 00b2681..8d0903e 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -227,17 +227,17 @@ def test_an_update_brings_the_new_model_list(machine): assert not any(cache.exists() for cache in caches) -def test_your_edits_are_kept_beside_the_new_files(machine): +def test_an_update_keeps_your_settings(machine): + """(tests/test_profile.py has the rest.) An older ghost's, which can't be told from its defaults, are set aside.""" m = machine() m.install() - for name in ("config.yaml", "SOUL.md"): - with open(m.profile / name, "a") as fh: - fh.write("# mine\n") + with open(m.profile / "config.yaml", "a") as fh: + fh.write("mcp_servers:\n mine:\n command: x\n") done = m.install() - for name in ("config.yaml", "SOUL.md"): - assert f"Your previous {name} is kept as {m.profile / name}.prev" in done.stdout - assert "# mine" in (m.profile / f"{name}.prev").read_text() and "# mine" not in (m.profile / name).read_text() - assert "previous" not in m.install().stdout and "# mine" in (m.profile / "config.yaml.prev").read_text() + assert "previous" not in done.stdout and "mcp_servers" in (m.profile / "config.yaml").read_text() + shutil.rmtree(m.profile / ".shipped") + assert f"Your previous config.yaml is kept as {m.profile / 'config.yaml'}.prev" in m.install().stdout + assert "mcp_servers" in (m.profile / "config.yaml.prev").read_text() and "mcp_servers" not in (m.profile / "config.yaml").read_text() @pytest.mark.parametrize("verbose", ["", "1"]) diff --git a/tests/test_profile.py b/tests/test_profile.py new file mode 100644 index 0000000..12c3d25 --- /dev/null +++ b/tests/test_profile.py @@ -0,0 +1,175 @@ +"""An update may change what it shipped, and never what you did.""" +import importlib.util +import os +import shutil +import sys +from pathlib import Path + +import pytest + +pytest.importorskip("ruamel.yaml") +from ruamel.yaml import YAML # noqa: E402 + +REPO = Path(__file__).resolve().parent.parent + + +@pytest.fixture +def profile(tmp_path, monkeypatch, capsys): + """The installer's step, over a copy of the release that a test can change.""" + source = tmp_path / "release" + shutil.copytree(REPO / "profile", source) + spec = importlib.util.spec_from_file_location("write_profile", REPO / "scripts" / "write_profile.py") + writer = importlib.util.module_from_spec(spec) + spec.loader.exec_module(writer) + monkeypatch.setattr(writer, "SOURCE", source) + monkeypatch.setattr(writer, "config", lambda home, local=None, text=source / "config.yaml": text.read_text(encoding="utf-8") + .replace("__GHOST_HOME__", "/g").replace("__LOCAL_MODEL__", "m").replace("__BRIDGE_TOKEN__", "token")) + + class Profile: + home, release = tmp_path / "profile", source + + def install(self): + writer.main([str(self.home), "--ghost-home", "/g"]) + return capsys.readouterr().out + + def path(self, name): + return self.home / name + + def settings(self): + return YAML(typ="safe").load(self.path("config.yaml").read_text(encoding="utf-8")) + + def change(self, change, name="config.yaml", where=None): + path = (where or self.home) / name + yaml = YAML() + data = yaml.load(path.read_text(encoding="utf-8")) + change(data) + with open(path, "w", encoding="utf-8") as fh: + yaml.dump(data, fh) # as the engine writes it: laid out its own way + return Profile() + + +def test_a_new_profile_is_the_releases(profile): + assert profile.install() == "" + assert profile.path("config.yaml").read_text(encoding="utf-8") == (profile.release / "config.yaml").read_text(encoding="utf-8").replace( + "__GHOST_HOME__", "/g").replace("__LOCAL_MODEL__", "m").replace("__BRIDGE_TOKEN__", "token") + assert profile.install() == "" and not list(profile.home.glob("*.prev*")) # and again: nothing to say + if os.name != "nt": + assert all(profile.path(n).stat().st_mode & 0o77 == 0 for n in ("config.yaml", "SOUL.md", ".env", ".shipped/config.yaml")) + + +def test_your_settings_survive_an_update(profile): + profile.install() + + def mine(c): + c["mcp_servers"] = {"jira": {"command": "jira-mcp", "args": ["--read-only"]}} + c["model"]["default"] = "deepseek/deepseek-v4-pro" + c["sessions"]["auto_prune"] = False + c["platform_toolsets"]["cli"].append("memory") + del c["agent"]["personalities"]["catgirl"] + + def theirs(c): + c["agent"]["max_turns"] = 300 + c["auxiliary"]["new_task"] = {"provider": "opengradient", "model": "x"} + c["_config_version"] = 60 + del c["tts"] + c["agent"]["personalities"]["pirate"] = "Yarr." + profile.change(mine) + profile.change(theirs, where=profile.release) + assert profile.install() == "" + got = profile.settings() + assert got["mcp_servers"]["jira"] == {"command": "jira-mcp", "args": ["--read-only"]} + assert got["model"]["default"] == "deepseek/deepseek-v4-pro" and got["sessions"]["auto_prune"] is False + assert "memory" in got["platform_toolsets"]["cli"] and "catgirl" not in got["agent"]["personalities"] + assert (got["agent"]["max_turns"], got["_config_version"]) == (300, 60) + assert "new_task" in got["auxiliary"] and "tts" not in got and got["agent"]["personalities"]["pirate"] == "Yarr." + text = profile.path("config.yaml").read_text(encoding="utf-8") + assert "# Every side task" in text # still explained + for _ in range(3): # and the ones after that + assert profile.install() == "" and profile.settings() == got + assert not list(profile.home.glob("*.prev*")) + + +def test_your_comments_stay_while_there_is_nothing_new(profile): + profile.install() + path = profile.path("config.yaml") + path.write_text(path.read_text(encoding="utf-8") + "# mine\n", encoding="utf-8") + assert profile.install() == "" and path.read_text(encoding="utf-8").endswith("# mine\n") + profile.change(lambda c: c["agent"].update(max_turns=300), where=profile.release) + assert profile.install() == "" and profile.settings()["agent"]["max_turns"] == 300 + assert profile.path("config.yaml.before-update").read_text(encoding="utf-8").endswith("# mine\n") + + +def test_where_you_and_the_release_changed_the_same_thing_it_is_yours(profile): + profile.install() + profile.change(lambda c: c["agent"].update(reasoning_effort="high")) + profile.change(lambda c: c["agent"].update(reasoning_effort="medium"), where=profile.release) + profile.install() + assert profile.settings()["agent"]["reasoning_effort"] == "high" + + +def test_what_connects_it_to_the_bridge_is_always_the_releases(profile): + profile.install() + + def mine(c): + c["providers"]["opengradient"]["api_key"] = "stale" + c["_config_version"] = 1 + c["prefill_messages_file"] = "/elsewhere" + profile.change(mine) + profile.install() + got = profile.settings() + assert got["providers"]["opengradient"]["api_key"] == "token" and got["_config_version"] > 1 + assert got["prefill_messages_file"] == "/g/privacy/uncensored_prefill.json" + + +@pytest.mark.parametrize("damage", ["model: [unclosed\n", "just words\n", "\x00\x01"]) +def test_a_damaged_file_is_set_aside(profile, damage): + profile.install() + profile.path("config.yaml").write_text(damage, encoding="utf-8") + assert "your previous config.yaml is kept as" in profile.install() + assert profile.path("config.yaml.prev").read_text(encoding="utf-8") == damage and profile.settings()["model"]["provider"] == "opengradient" + + +def test_a_file_that_is_not_text_is_set_aside(profile): + profile.install() + profile.path("config.yaml").write_bytes(b"\xff\xfe\x00m") + assert "kept as" in profile.install() and profile.settings()["model"]["provider"] == "opengradient" + + +def test_from_an_older_ghost_which_kept_no_copy(profile): + """Its defaults can't be told from your changes, so both are set aside, and nothing set aside is ever replaced.""" + profile.home.mkdir() + for n in ("", "-2"): + for name in ("config.yaml", "SOUL.md"): + profile.path(name).write_text(f"old: {n}\n", encoding="utf-8") + if n: + shutil.rmtree(profile.path(".shipped")) + out = profile.install() + for name in ("config.yaml", "SOUL.md"): + assert f"{name}.prev{n}" in out and profile.path(f"{name}.prev{n}").read_text(encoding="utf-8") == f"old: {n}\n" + + +def test_a_soul_of_yours_is_left_alone(profile): + profile.install() + profile.path("SOUL.md").write_text("You are Mara's.\n", encoding="utf-8") + assert profile.install() == "" # this release's hasn't changed + (profile.release / "SOUL.md").write_text("You are newer.\n", encoding="utf-8") + assert "SOUL.md.new" in profile.install() + assert profile.path("SOUL.md").read_text(encoding="utf-8") == "You are Mara's.\n" + assert profile.path("SOUL.md.new").read_text(encoding="utf-8") == "You are newer.\n" + + +def test_a_soul_you_did_not_touch_is_updated(profile): + profile.install() + (profile.release / "SOUL.md").write_text("You are newer.\n", encoding="utf-8") + assert profile.install() == "" and profile.path("SOUL.md").read_text(encoding="utf-8") == "You are newer.\n" + + +def test_windows_line_endings_are_not_a_change(profile): + profile.install() + path = profile.path("config.yaml") + path.write_bytes(path.read_bytes().replace(b"\n", b"\r\n")) + assert profile.install() == "" and not list(profile.home.glob("*.prev*")) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-q"])) diff --git a/uv.lock b/uv.lock index 0d0ca8e..b9d158c 100644 --- a/uv.lock +++ b/uv.lock @@ -375,6 +375,7 @@ dependencies = [ { name = "certifi" }, { name = "httpx", extra = ["socks"] }, { name = "opengradient-ohttp" }, + { name = "ruamel-yaml" }, { name = "truststore" }, ] @@ -383,6 +384,7 @@ requires-dist = [ { name = "certifi" }, { name = "httpx", extras = ["socks"], specifier = ">=0.27" }, { name = "opengradient-ohttp", specifier = ">=0.1,<0.2" }, + { name = "ruamel-yaml", specifier = ">=0.18" }, { name = "truststore", specifier = ">=0.10" }, ] @@ -737,6 +739,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/da/80/35b4c33c804a165a7f55289afda3ea9e3eb6d15800341a2d66455c0f1f30/regex-2026.5.9-cp314-cp314t-win_arm64.whl", hash = "sha256:5e41809d2683fcde7d5a8c87a6567ba1fb1ce0de9f31bff578de00a4b2d76daa", size = 275713, upload-time = "2026-05-09T23:15:16.98Z" }, ] +[[package]] +name = "ruamel-yaml" +version = "0.19.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c7/3b/ebda527b56beb90cb7652cb1c7e4f91f48649fbcd8d2eb2fb6e77cd3329b/ruamel_yaml-0.19.1.tar.gz", hash = "sha256:53eb66cd27849eff968ebf8f0bf61f46cdac2da1d1f3576dd4ccee9b25c31993", size = 142709, upload-time = "2026-01-02T16:50:31.84Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/0c/51f6841f1d84f404f92463fc2b1ba0da357ca1e3db6b7fbda26956c3b82a/ruamel_yaml-0.19.1-py3-none-any.whl", hash = "sha256:27592957fedf6e0b62f281e96effd28043345e0e66001f97683aa9a40c667c93", size = 118102, upload-time = "2026-01-02T16:50:29.201Z" }, +] + [[package]] name = "socksio" version = "1.0.0" From 64a2b89f506b7b934150fc6e6cf2f00fe2d40de9 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 19:00:03 +0000 Subject: [PATCH 09/15] 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 From fca026d6575c36bff7e4235f8faed0a7ed38f44f Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 19:00:49 +0000 Subject: [PATCH 10/15] README: install hosts, and what stays --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index bf491ec..5929cc9 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ The first run asks how you want to log in. Nothing is contacted before that. | `ghost usage` / `ghost budget` | What hosted models have cost you, what credits are left, and the hourly limit. | | `ghost login` / `ghost logout` | Change how you're connected. | | `ghost update` | Get the latest release, with the options you installed with. | -| `ghost uninstall` | Remove ghost. Your chats and settings stay unless you add `--purge`. | +| `ghost uninstall` | Remove ghost. Your chats, settings and login stay unless you add `--purge`. | Inside a chat, `/model` switches models, `/goal ` sets a standing goal, `/help` lists the rest. @@ -71,7 +71,7 @@ On Windows, from a clone: `powershell -ExecutionPolicy Bypass -File .\install.ps An update keeps the settings you changed in `~/.ghost/profiles/uncensored/config.yaml`, and a `SOUL.md` of your own (the release's is then beside it, as `SOUL.md.new`). -**On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`) and the certificates the system trusts. It needs to reach `chat-api.memchat.io`, and `ogevmdevnet.opengradient.ai`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection, and falls back to an enclave built into the release. +**On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`) and the certificates the system trusts. It needs to reach `chat-api.memchat.io`, and `ogevmdevnet.opengradient.ai`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection, and falls back to an enclave built into the release. Installing also needs `github.com`, `*.githubusercontent.com`, `astral.sh`, `*.astral.sh`, `pypi.org`, `files.pythonhosted.org`, `nodejs.org`, `registry.npmjs.org` and, for the browser, `cdn.playwright.dev` and `storage.googleapis.com`. @@ -149,7 +149,7 @@ The agent's own web searches, page fetches and browser go out from your machine - **Chats don't stay.** A chat is deleted a day after it ends, along with what you typed. To keep them, set `sessions.auto_prune: false` in `~/.ghost/profiles/uncensored/config.yaml`. - **Your keys stay yours.** Keys for other vendors in your environment (OpenAI, OpenRouter, ...) are kept from the engine, so nothing goes to them by surprise. Put one in `~/.ghost/profiles/uncensored/.env` to use it on purpose. - **Replies arrive whole.** The signature covers the complete reply, so ghost shows it once it's verified rather than word by word. -- **The local model is opt-in and weaker.** Off by default (`GHOST_LOCAL`); it's a weaker agentic searcher and may still lean on the hosted gateway for tool orchestration. +- **The local model is opt-in and weaker.** Off by default (`GHOST_LOCAL`); it's a much smaller model, and it shows in long agentic work. - **It asks before it deletes.** Commands that delete folders, overwrite system files and the like wait for your OK; `--yolo` turns that off. - **The engine is forked, not rewritten.** It's one pinned Hermes release ([`engine.pin`](engine.pin)), patched and self-contained: no separate Hermes install is needed or touched, and `ghost update` is what moves it. Internal package names stay `hermes_cli`. - **Two small background processes.** The bridge is a service (launchd, systemd or Task Scheduler) that starts with your machine. Your sessions run in a local gateway that ghost starts when you do and that exits after 10 idle minutes (unless you install it as a service with `ghost gateway install`). From d94a22e17fd7e360d1afaa0ad1fcc9c26ea682e7 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 19:01:19 +0000 Subject: [PATCH 11/15] README: long questions --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5929cc9..83bc3c7 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ The first run asks how you want to log in. Nothing is contacted before that. | | | |---|---| | `ghost` | Start chatting. `ghost -c` continues your last chat. | -| `ghost -z "question"` | Ask once and print the answer. | +| `ghost -z "question"` | Ask once and print the answer. A long question can come from a file: `ghost chat --query-file FILE` (`-` for stdin). | | `ghost --local` | Use the offline model: what you type stays on this machine, and the web tools are off. | | `ghost doctor` | Check that everything works, and what to do if it doesn't. | | `ghost usage` / `ghost budget` | What hosted models have cost you, what credits are left, and the hourly limit. | From 188a5684a3bdd1f1525a9fe9219dadbe6cd8f6c8 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 19:02:43 +0000 Subject: [PATCH 12/15] Follow a company's proxy script on Windows --- README.md | 2 +- privacy/doctor.py | 3 ++- privacy/launch.py | 5 ++++- privacy/outbound.py | 33 ++++++++++++++++++++++++++++++++- 4 files changed, 39 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 83bc3c7..95f5462 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ On Windows, from a clone: `powershell -ExecutionPolicy Bypass -File .\install.ps An update keeps the settings you changed in `~/.ghost/profiles/uncensored/config.yaml`, and a `SOUL.md` of your own (the release's is then beside it, as `SOUL.md.new`). -**On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`) and the certificates the system trusts. It needs to reach `chat-api.memchat.io`, and `ogevmdevnet.opengradient.ai`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection, and falls back to an enclave built into the release. Installing also needs `github.com`, `*.githubusercontent.com`, `astral.sh`, `*.astral.sh`, `pypi.org`, `files.pythonhosted.org`, `nodejs.org`, `registry.npmjs.org` and, for the browser, `cdn.playwright.dev` and `storage.googleapis.com`. +**On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`, which a Mac with a proxy script needs) and the certificates the system trusts. It needs to reach `chat-api.memchat.io`, and `ogevmdevnet.opengradient.ai`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection, and falls back to an enclave built into the release. Installing also needs `github.com`, `*.githubusercontent.com`, `astral.sh`, `*.astral.sh`, `pypi.org`, `files.pythonhosted.org`, `nodejs.org`, `registry.npmjs.org` and, for the browser, `cdn.playwright.dev` and `storage.googleapis.com`. diff --git a/privacy/doctor.py b/privacy/doctor.py index cac4652..ce24065 100644 --- a/privacy/doctor.py +++ b/privacy/doctor.py @@ -59,7 +59,8 @@ def relay(): if "login" in _found: return False, _found["login"], "ghost login" if "unreachable" in _found: - return False, f"can't be reached ({_found['unreachable']}); check your connection, VPN or proxy", None + script = "; this machine finds its proxy with a script, so set HTTPS_PROXY to its address" if outbound.scripted() and not outbound._noted() else "" + return False, f"can't be reached ({_found['unreachable']}){script or '; check your connection, VPN or proxy'}", None status = _found.get("relay") if status in (401, 403): return False, "doesn't accept this login any more", "ghost login" diff --git a/privacy/launch.py b/privacy/launch.py index 724f8b7..877071a 100644 --- a/privacy/launch.py +++ b/privacy/launch.py @@ -198,7 +198,7 @@ def _start_process(): def leave_proxies(): """The bridge is a background service, and doesn't see the proxies your shell sets.""" - if urllib.request.getproxies_environment() or (PRIV / "proxies.json").exists(): + if urllib.request.getproxies_environment() or (PRIV / "proxies.json").exists() or os.name == "nt": import outbound # (not for nothing: it brings an HTTP client along) outbound.note() @@ -237,6 +237,9 @@ def engine_binary(): def engine_proxies(): """What an engine needs to reach the world through this machine's proxy, and the bridge without it.""" found = urllib.request.getproxies() # the environment's, or the system's settings + if os.name == "nt" and not found: + import outbound + found = outbound._noted() env = {f"{scheme}_proxy": found[scheme] for scheme in ("http", "https", "all") if found.get(scheme)} if env: direct = [h.strip() for h in (found.get("no") or "").split(",") if h.strip()] diff --git a/privacy/outbound.py b/privacy/outbound.py index 666bdd3..f9e35e8 100644 --- a/privacy/outbound.py +++ b/privacy/outbound.py @@ -2,7 +2,7 @@ it trusts, as a company laptop needs. The bridge is a background service, which doesn't see what your shell sets (HTTPS_PROXY and so on), so `ghost` -leaves a note of it. A proxy that can't be used is an error: going around it would show your address. +leaves a note of it, and on Windows of the proxy a company's script (PAC) picks. A proxy that can't be used is an error: going around it would show your address. With one exception. Which enclaves to trust is read from the TEE registry, so on a network that inspects TLS that read must fail rather than believe the network: it trusts the public authorities only. @@ -11,6 +11,7 @@ import os import socket import ssl +import subprocess import sys import urllib.request from pathlib import Path @@ -32,9 +33,39 @@ def trust(): NOTE = Path(os.environ.get("GHOST_HOME") or Path.home() / ".ghost") / "privacy" / "proxies.json" +def scripted(): + """Does this machine find its proxy with a script (PAC)? Python doesn't follow those.""" + if os.name == "nt": + import winreg + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings") as key: + return bool(winreg.QueryValueEx(key, "AutoConfigURL")[0]) + except OSError: + return False + if sys.platform == "darwin": + try: + return "ProxyAutoConfigEnable : 1" in subprocess.run(["scutil", "--proxy"], capture_output=True, text=True, timeout=5).stdout + except (OSError, subprocess.SubprocessError): + return False + return False + + +def _picked(): + """What that script picks for DreamFort. (Windows' own code can be asked.)""" + ask = ("$u = [Uri]'https://chat-api.memchat.io/'; $p = [Net.WebRequest]::GetSystemWebProxy().GetProxy($u); " + "if ($p -and $p.AbsoluteUri -ne $u.AbsoluteUri) { $p.AbsoluteUri }") + try: + found = subprocess.run(["powershell", "-NoProfile", "-Command", ask], capture_output=True, text=True, timeout=30).stdout.strip().rstrip("/") + except (OSError, subprocess.SubprocessError): + return {} + return {"http": found, "https": found, "no": "127.0.0.1,localhost"} if found else {} + + def note(): """Leave your shell's proxies for the bridge (or that it has none, when you're there to see to it).""" found = urllib.request.getproxies_environment() + if os.name == "nt" and not urllib.request.getproxies() and scripted(): + found = _picked() try: if any(found.get(kind) for kind in ("http", "https", "all")): fd = os.open(NOTE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) From cf6b348f1b5ebd2d093dbf416d422ec30be7d081 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 19:07:48 +0000 Subject: [PATCH 13/15] When the registry can't be read, use the enclaves it listed before --- .github/workflows/enclaves.yml | 17 ++++++ README.md | 2 +- bin/ghost-uninstall | 2 +- bin/windows/ghost-uninstall.ps1 | 2 +- privacy/doctor.py | 4 +- privacy/enclaves.py | 98 +++++++++++++++++++++++++++------ tests/check_enclaves.py | 29 ++++++++++ tests/test_bridge.py | 44 ++++++++++++--- tests/test_login.py | 1 + 9 files changed, 167 insertions(+), 32 deletions(-) create mode 100644 .github/workflows/enclaves.yml create mode 100644 tests/check_enclaves.py diff --git a/.github/workflows/enclaves.yml b/.github/workflows/enclaves.yml new file mode 100644 index 0000000..bed2d6e --- /dev/null +++ b/.github/workflows/enclaves.yml @@ -0,0 +1,17 @@ +name: enclaves +on: + schedule: + - cron: "17 6 * * *" + workflow_dispatch: + +jobs: + # ghost falls back to these when the registry can't be read, and an enclave has new keys each time it is deployed. + built-in: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: pip install -q "opengradient-ohttp>=0.1,<0.2" + - run: python tests/check_enclaves.py diff --git a/README.md b/README.md index 95f5462..2520cef 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ On Windows, from a clone: `powershell -ExecutionPolicy Bypass -File .\install.ps An update keeps the settings you changed in `~/.ghost/profiles/uncensored/config.yaml`, and a `SOUL.md` of your own (the release's is then beside it, as `SOUL.md.new`). -**On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`, which a Mac with a proxy script needs) and the certificates the system trusts. It needs to reach `chat-api.memchat.io`, and `ogevmdevnet.opengradient.ai`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection, and falls back to an enclave built into the release. Installing also needs `github.com`, `*.githubusercontent.com`, `astral.sh`, `*.astral.sh`, `pypi.org`, `files.pythonhosted.org`, `nodejs.org`, `registry.npmjs.org` and, for the browser, `cdn.playwright.dev` and `storage.googleapis.com`. +**On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`, which a Mac with a proxy script needs) and the certificates the system trusts. It needs to reach `chat-api.memchat.io`, and `ogevmdevnet.opengradient.ai`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection, and has only the enclaves it knew when it was released to go by, which change every few weeks. Installing also needs `github.com`, `*.githubusercontent.com`, `astral.sh`, `*.astral.sh`, `pypi.org`, `files.pythonhosted.org`, `nodejs.org`, `registry.npmjs.org` and, for the browser, `cdn.playwright.dev` and `storage.googleapis.com`. diff --git a/bin/ghost-uninstall b/bin/ghost-uninstall index 62ef844..776ae3f 100644 --- a/bin/ghost-uninstall +++ b/bin/ghost-uninstall @@ -130,7 +130,7 @@ 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/.linger" "$GHOST_HOME/install.log" "$GHOST_HOME"/privacy/*.py \ "$GHOST_HOME/privacy/uncensored_prefill.json" "$GHOST_HOME/privacy/bridge.key" "$GHOST_HOME/privacy/.made" \ - "$GHOST_HOME/privacy/proxies.json" "$GHOST_HOME"/privacy/bridge.log* + "$GHOST_HOME/privacy/proxies.json" "$GHOST_HOME/privacy/enclaves.json" "$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/windows/ghost-uninstall.ps1 b/bin/windows/ghost-uninstall.ps1 index 76cb20d..e5519b1 100644 --- a/bin/windows/ghost-uninstall.ps1 +++ b/bin/windows/ghost-uninstall.ps1 @@ -75,7 +75,7 @@ if ($purge) { 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\.made", "privacy\proxies.json", "privacy\bridge.log*", ".src", ".install-env", ".installing") { Remove-Hard "$GhostHome\$name" } + "privacy\bridge.key", "privacy\.made", "privacy\proxies.json", "privacy\enclaves.json", "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") { diff --git a/privacy/doctor.py b/privacy/doctor.py index ce24065..d9c1cd1 100644 --- a/privacy/doctor.py +++ b/privacy/doctor.py @@ -70,10 +70,10 @@ def relay(): def enclaves(): - """The registry says which enclaves there are. Without it, ghost has some built in.""" + """The registry says which enclaves there are. Without it, ghost goes by what it said before.""" listed = _found.get("enclaves") if listed is None: - return None, "the registry can't be read right now, so the one built into ghost is used", None + return None, "the registry can't be read right now, so one known from before is used", None return (True, f"{listed} in the registry", None) if listed else (False, "the registry lists none right now; try again later", None) diff --git a/privacy/enclaves.py b/privacy/enclaves.py index 9eb7aba..e3fb0d2 100644 --- a/privacy/enclaves.py +++ b/privacy/enclaves.py @@ -1,61 +1,123 @@ """Which enclaves a request may be sealed to: the ones the on-chain TEE registry lists. The chain it lives on has been down (25 November 2026), and a network that inspects TLS can't be believed about -it. When it can't be read, ghost uses the enclaves below instead; a registry that answers is always obeyed, also -when it lists none. Their keys are fixed here, as the registry's address is, so cutting ghost off from the registry -can't point it at an impostor. DreamFort's apps fall back to the same list (chat-app's lib/api/backupTees.ts, -chat-api's src/core/backup_tees.py): keep the three in step. +it. When it can't be read, ghost uses the enclaves it listed the last time, and the ones below; a registry that +answers is always obeyed, also when it lists none. Both are fixed on this machine, as the registry's address is, so +cutting ghost off from the registry can't point it at an impostor. An enclave gets new keys whenever it is deployed, +so those below go stale: CI says when (tests/check_enclaves.py), and prints what to put here. """ +import json +import os import random +import threading +import time +from pathlib import Path from cryptography.hazmat.primitives import serialization from eth_hash.auto import keccak from opengradient_ohttp import DEFAULT_RPC_URL as REGISTRY, RegistryError, TeeTarget from opengradient_ohttp._registry import TeeResolver, parse_active_tees +REMEMBERED = Path(os.environ.get("GHOST_HOME") or Path.home() / ".ghost") / "privacy" / "enclaves.json" +KEEP = 14 * 86400 +AVOID = 600.0 # seconds an enclave that just failed is left alone, while there is another -def _enclave(endpoint, signing_key_pem, hpke_public_key): + +def enclave(endpoint, signing_key_pem, hpke_public_key): der = serialization.load_pem_public_key(signing_key_pem.encode()).public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) return TeeTarget(tee_id="0x" + keccak(der).hex(), endpoint=endpoint, signing_key_pem=signing_key_pem, ohttp_public_key=bytes.fromhex(hpke_public_key), key_id=1) +# As the registry listed them on 25 November 2026, each attested by AWS Nitro. BUILT_IN = ( - _enclave("https://3.147.79.53", """\ + enclave("https://3.15.214.21", """\ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0R5wLaOc7+mNhbvq6Dng +rmn3guc4Ay70cOhOKU32ZiJDnRC5TZH2SOvGKlX/J/Xm7jCA5jE3KsMd0Z1QszUQ +8ZIc37OrXco2POvP4MWsG5aqSxJFVW8UPqVfzQsO0a+BPO3tp5hoREPxdcx3T34M +b3LGByKey7SBQEq1V6Eh/1q/zE69/+oQN7QcTr3peC9GM95RfqPV+koC74DrMFgc +TaP39hI7dZBAAG8R1hdau2EQSujwgaAhlkpnhncDhBS+ZTG2ArU8FfE6oT+qGlvE +lJ17ioC1ps1+RDwLx9yUbZXTtksbu/fX6+kCghyFacf4Ps/0FMSo4TRpFM62IMci +3QIDAQAB +-----END PUBLIC KEY----- +""", "c16340240ac449452a874eb46c3e20e50afc7a7a32f3014465f664bb00464d20"), + enclave("https://13.59.207.188", """\ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6exo/OGkZaGjciAS1W/F +Sy7gsxBclp9A/wQaL3TSmTTvORpgxh2dXt2XmcGJeo5TfTJdM2KZOgD6rv47EqI/ +2IU9XKJpQ/WHujKkr8CRTlCnoJgqUqmD4KuQlvWB0GEFXU4VioVbAazIlpWFeYhb +N4kDJKwPYOm8vcAhtQpZ+8Hlp1RUyAG2DoLajJsCOBHLTcbIG6WiVt9TPE/1chLN +zrfOB0K2qJ9/IzZE09LMDzlqEzrN6rsccSaaQH10f14FFO2rvC521Q+kiBBCHpSc +44oj44pafjUxBFuEPsgFX1w9i2NtLvTy9gjGpJFWL82uUIud+EMztqIq/YZ6BUKh +xwIDAQAB +-----END PUBLIC KEY----- +""", "592b5bc353f6114ef947771f1e0dd36fc21ef8f5279fe841369161a551697577"), + enclave("https://3.147.79.53", """\ -----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxTFaCi3JXAOp1LxpjZxT -KZPGMGNzjtRIaC73KnMZOIm/rJoM6x+kqLrocQKU2ATfGi7tuiB06AirJaM31CiQ -yBBc9/qCkQj6i+zudQZCFkPIDgn34hpgL6nc2jXJAlhV7zHdpg2ieSjtBh8D+tSH -MYmrg32WY4SGxPiRPo8FnYITkOl8ZWjDi85Yi21ztWgY70Ck5j+UfzNa96ceObR/ -YGxPGLwMuon/N1LmZ2q+H6sPbHI6Sxeb5b33Kpe4wRwqkUkRw49Do/1iwY5pPJIc -OzkyDBXXQXl9EOZAhP5ug423H2dcwobkq3QEV+fW2EIHouDNR1lei0RwNCPlWPnj -LwIDAQAB +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArkOOrPjjE+3RKnYRuisw +a+E6eY9d8A7/HCQ99gd3sobXx/6jVJ7e79CP5RsUc7jC5q6T2Nph3YiuyCjW4gBt +vHcTH5n3kZjRhPbHiAY93a79a3X1tRxH7A9NPvnSVBu7YRC66wA1GidRHDhfa4CP +gVUGCHTGX3zGfd/EZ5PeafODkgZtTo6y/37N6atwsBTNnDZsW252ea8YmZk0Y/E/ +KGW4VCYC53vleRJIM9IXRnbIlg5UvXNcyijWrV3hdwjDzTXk0qGz/bZ0MngoLRhf +wMcYIRxmp6tva63zdVqgGb9GsfhFnijd7RtEKoLep1nP1apyftK1DhaItyI+gjYG +6QIDAQAB -----END PUBLIC KEY----- -""", "ba5c847114ffc09e387b2b9946b1ab8e91528a308137fdb160f59ea9e1717112"), +""", "127ec8c4a543d98450d37e4c0a164e80d71d4f305e21e380b1ec07b919a0b563"), ) +def remember(found): + row = [[t.endpoint, t.signing_key_pem, t.ohttp_public_key.hex()] for t in found if t.key_id == 1] + try: + fd = os.open(REMEMBERED.with_suffix(".tmp"), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump({"at": time.time(), "enclaves": row}, fh) + os.replace(REMEMBERED.with_suffix(".tmp"), REMEMBERED) + except OSError: + pass + + +def remembered(): + try: + data = json.loads(REMEMBERED.read_text(encoding="utf-8")) + return [enclave(*row) for row in data["enclaves"]] if time.time() - data["at"] < KEEP else [] + except (OSError, ValueError, KeyError, TypeError): + return [] + + class Enclaves(TeeResolver): """Picks one, and keeps it for as long as a registry read is kept.""" def __init__(self, transport=None, log=lambda message: None): super().__init__(transport=transport) - self._log = log + self._log, self._avoid, self._guard = log, {}, threading.Lock() def get(self): with self._lock: if not self._cache.get(): try: found = self.listed() + remember(found) except RegistryError as e: - self._log(f"the TEE registry can't be read, using a built-in enclave: {e}") - found = BUILT_IN + known = {t.tee_id: t for t in (*BUILT_IN, *remembered())} + found = list(known.values()) + self._log(f"the TEE registry can't be read, using one of {len(found)} enclaves known from before: {e}") if not found: raise RegistryError("the TEE registry lists no active enclave, so there is nothing to seal this to; try again later") - self._cache.put(random.choice(found)) + with self._guard: + fresh = [t for t in found if time.monotonic() - self._avoid.get(t.tee_id, -AVOID) >= AVOID] + self._cache.put(random.choice(fresh or found)) return self._cache.get() + def invalidate(self, tee_id=None): + """The relay said it's gone, or unwell.""" + if tee_id: + with self._guard: + self._avoid[tee_id] = time.monotonic() + super().invalidate(tee_id) + def listed(self): """The enclaves the registry lists. Raises RegistryError when it can't be read.""" return parse_active_tees(self._fetch(), self._excluded) diff --git a/tests/check_enclaves.py b/tests/check_enclaves.py new file mode 100644 index 0000000..614d20b --- /dev/null +++ b/tests/check_enclaves.py @@ -0,0 +1,29 @@ +"""Are the enclaves built into ghost (privacy/enclaves.py) still the registry's? Fails when none of them is. + + python tests/check_enclaves.py +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "privacy")) +import enclaves # noqa: E402 + + +def main(): + try: + listed = enclaves.Enclaves().listed() + except enclaves.RegistryError as e: + print(f"the registry can't be read, so there is nothing to compare: {e}") + return 0 + ours, theirs = {t.tee_id for t in enclaves.BUILT_IN}, {t.tee_id for t in listed} + print(f"built in: {len(ours)}, listed: {len(theirs)}, in both: {len(ours & theirs)}") + if ours == theirs: + return 0 + print("\nThe registry's, for privacy/enclaves.py:\n") + for t in listed: + print(f' enclave("{t.endpoint}", """\\\n{t.signing_key_pem}""", "{t.ohttp_public_key.hex()}"),') + return 0 if ours & theirs or not theirs else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_bridge.py b/tests/test_bridge.py index 94a42b7..64952de 100644 --- a/tests/test_bridge.py +++ b/tests/test_bridge.py @@ -325,7 +325,7 @@ def slow(*args): # ── through the real sealing, against a stand-in DreamFort ──────────────────── @pytest.fixture -def dream(monkeypatch): +def dream(monkeypatch, tmp_path): service = fake_dreamfort.DreamFort() server = fake_dreamfort.serve(service) threading.Thread(target=server.serve_forever, daemon=True).start() @@ -334,6 +334,7 @@ def dream(monkeypatch): monkeypatch.setattr(sp.ghost_auth, "credentials", lambda refused=None: (url + sp.ghost_auth.API_KEY_RELAY, fake_dreamfort.API_KEY)) monkeypatch.setattr(sp.ghost_auth, "api_key", lambda: fake_dreamfort.API_KEY) monkeypatch.setattr(sp, "_clients", {}) + monkeypatch.setattr(enclaves, "REMEMBERED", tmp_path / "enclaves.json") yield service server.shutdown() server.server_close() @@ -371,17 +372,43 @@ def test_however_a_request_fails(dream, bridge, kind, statuses, billed, words): def test_when_the_registry_cannot_be_read(monkeypatch, dream, bridge): """Its chain has gone down; DreamFort's apps fall back to enclaves they know, and so does ghost.""" - ours = fake_dreamfort.Enclave() - pem = ours.rsa.public_key().public_bytes(fake_dreamfort.serialization.Encoding.PEM, fake_dreamfort.serialization.PublicFormat.SubjectPublicKeyInfo).decode() + ours, gone = fake_dreamfort.Enclave(), fake_dreamfort.Enclave() dream.registry_up, listed, dream.enclave = False, dream.enclave, ours - monkeypatch.setattr(enclaves, "BUILT_IN", (enclaves._enclave("https://ours.test", pem, ours.public.hex()),)) + monkeypatch.setattr(enclaves, "BUILT_IN", tuple(as_built_in(e) for e in (gone, ours))) # (the relay knows one of them) assert bridge(**says("[[say one]]"))[0] == bridge(**says("[[say two]]"))[0] == 200 with open(sp.LOG) as fh: - assert fh.read().count("the TEE registry can't be read") == 1 # and it isn't asked again each time + assert fh.read().count("the TEE registry can't be read") <= 2 # and it isn't asked again each time dream.registry_up, dream.enclave = True, listed # back, and the built-in one retired: the registry decides again assert bridge(**says("[[say three]]"))[0] == 200 and len(dream.billed) == 3 +def as_built_in(e): + pem = e.rsa.public_key().public_bytes(fake_dreamfort.serialization.Encoding.PEM, fake_dreamfort.serialization.PublicFormat.SubjectPublicKeyInfo).decode() + return enclaves.enclave("https://enclave.test", pem, e.public.hex()) + + +def test_the_enclaves_it_last_listed_are_remembered(monkeypatch, dream, bridge): + monkeypatch.setattr(enclaves, "BUILT_IN", ()) + assert bridge(**says("[[say one]]"))[0] == 200 and os.path.exists(enclaves.REMEMBERED) + monkeypatch.setattr(sp, "_clients", {}) # (the bridge was restarted) + dream.registry_up = False + assert bridge(**says("[[say two]]"))[0] == 200 + monkeypatch.setattr(enclaves, "KEEP", 0) # two weeks later they're not + monkeypatch.setattr(sp, "_clients", {}) + assert bridge(**says("[[say three]]"))[0] == 503 + + +def test_an_enclave_that_is_unwell_is_avoided(monkeypatch): + known = [as_built_in(fake_dreamfort.Enclave()) for _ in range(3)] + monkeypatch.setattr(enclaves.Enclaves, "listed", lambda self: known) + monkeypatch.setattr(enclaves, "remember", lambda found: None) + resolver, used = enclaves.Enclaves(), [] + for _ in range(3): + used.append(resolver.get().tee_id) + resolver.invalidate(used[-1]) + assert len(set(used)) == 3 and resolver.get().tee_id in used # all three were; one is better than none + + def test_a_registry_that_lists_none_is_obeyed(monkeypatch, dream, bridge): """All of them revoked, say. That is an answer, and no reason to use one it doesn't list.""" monkeypatch.setattr(enclaves.Enclaves, "listed", lambda self: []) @@ -389,10 +416,9 @@ def test_a_registry_that_lists_none_is_obeyed(monkeypatch, dream, bridge): assert status == 503 and "lists no active enclave" in message and dream.accepted == [] -def test_the_built_in_enclaves_are_the_apps_own(): - """chat-app's lib/api/backupTees.ts and chat-api's src/core/backup_tees.py list the same one.""" - assert [t.tee_id for t in enclaves.BUILT_IN] == ["0xe1443d7ed558fbd19117c4dc70e6245fc71d6063d64af3bc3f790081bc94e9aa"] - assert all(len(t.ohttp_public_key) == 32 for t in enclaves.BUILT_IN) +def test_the_built_in_enclaves_are_what_they_say(): + assert len({t.tee_id for t in enclaves.BUILT_IN}) == len(enclaves.BUILT_IN) and all(len(t.ohttp_public_key) == 32 for t in enclaves.BUILT_IN) + assert "0x5fb75e8d657ecfa7fd46424cfb66753830d70a8c68a681b967d9eb9f29a8edf9" in {t.tee_id for t in enclaves.BUILT_IN} # (derived from its key) # ── what else the bridge answers ────────────────────────────────────────────── diff --git a/tests/test_login.py b/tests/test_login.py index 30b1cf3..0262dec 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -307,6 +307,7 @@ def machine(dream, tmp_path, monkeypatch): import bridge import enclaves monkeypatch.setattr("enclaves.Enclaves.listed", lambda self: [1, 2, 3]) + monkeypatch.setattr("enclaves.REMEMBERED", tmp_path / "enclaves.json") monkeypatch.setattr(ghost_auth, "BRIDGE_KEY_FILE", tmp_path / "bridge.key") monkeypatch.setattr(bridge, "LOG", str(tmp_path / "bridge.log")) server = bridge.LocalServer(("127.0.0.1", 0), bridge.Handler) From 87895aa8439d4238a72c602a62c46b747ab89341 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 19:17:47 +0000 Subject: [PATCH 14/15] The gateway you set up takes over from a chat's own, and comes back after an update --- .github/workflows/test.yml | 2 ++ privacy/launch.py | 17 +++++++++++++++++ scripts/fork-engine.sh | 17 +++++++++++++---- tests/test_fork_engine.py | 29 +++++++++++++++++------------ tests/test_launch.py | 33 +++++++++++++++++++++++++++++++++ 5 files changed, 82 insertions(+), 16 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 269f0c5..0b67ec0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -74,11 +74,13 @@ jobs: profile="$HOME/.ghost/profiles/uncensored"; echo "# mine" >> "$profile/SOUL.md"; "$ghost" config set display.show_reasoning true "$ghost" gateway install --start-now --start-on-login sleep 15; "$ghost" gateway status; before="$(pid)"; kill -0 "$before" + if ps -o command= -p "$before" | grep -e --idle-exit; then exit 1; fi # it's not the one the chat left running started=$SECONDS; ./install.sh # nothing new: the engine isn't built again, and the gateway is left alone grep -q "already this build" "$HOME/.ghost/install.log"; echo "took $((SECONDS - started))s"; test $((SECONDS - started)) -lt 30 test "$(pid)" = "$before"; kill -0 "$before" GHOST_FORCE=1 GHOST_VERBOSE=1 ./install.sh sleep 15; "$ghost" gateway status; after="$(pid)"; kill -0 "$after" + if ps -o command= -p "$after" | grep -e --idle-exit; then exit 1; fi test "$before" != "$after"; if kill -0 "$before" 2>/dev/null; then exit 1; fi test ! -e "$HOME/.ghost/.restart-gateway" grep -q "# mine" "$profile/SOUL.md"; grep -q "show_reasoning: true" "$profile/config.yaml"; if ls "$profile"/*.prev*; then exit 1; fi diff --git a/privacy/launch.py b/privacy/launch.py index 877071a..70d973b 100644 --- a/privacy/launch.py +++ b/privacy/launch.py @@ -265,6 +265,22 @@ def run_engine(args, provider="opengradient"): return subprocess.call(command) +def make_way(args): + """A chat's own gateway outlives it by ten minutes, and the one that's to stay can't start beside it.""" + if args[:1] != ["gateway"] or args[1:2] not in (["install"], ["start"], ["restart"], ["setup"]) or {"--no-start-now", "-h", "--help"} & set(args): + return + try: + if "--idle-exit" not in json.loads((PROFILE / "gateway.pid").read_text(encoding="utf-8"))["argv"]: + return + except (OSError, ValueError, KeyError, TypeError): + return + engine = engine_binary() + stop = [str(engine), "-p", "uncensored", "gateway", "stop"] # (which it won't, in the middle of something) + if engine and subprocess.run(stop, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode \ + and (PROFILE / "gateway.pid").exists(): + say("a chat is busy, and the background gateway can't start beside it. Run this again when it's done.") + + def run_local(args, config): model = local_model(config) ollama = shutil.which("ollama") or "/opt/homebrew/bin/ollama" @@ -336,6 +352,7 @@ def main(argv): if local: return run_local(args, config) if not starts_a_chat(args): + make_way(args) return run_engine(args) if not default_model(config) or "\n opengradient:\n" not in config: say(f"ghost's settings ({PROFILE / 'config.yaml'}) are missing or damaged. Put them back with: ghost update") diff --git a/scripts/fork-engine.sh b/scripts/fork-engine.sh index c67011f..6ce12f9 100755 --- a/scripts/fork-engine.sh +++ b/scripts/fork-engine.sh @@ -29,12 +29,21 @@ NEW="$ENG.new"; OLD="$ENG.old" LAUNCH="$ENG/.hermes/bin/hermes" RESTART="$GHOST_HOME/.restart-gateway" # present while a gateway this script stopped is owed a start REFRESH="$GHOST_HOME/.refresh-gateway" # present while an installed gateway still points at the previous engine -# The background gateway, when it's installed as a service. +# The background gateway, when it's installed as a service. It's wanted when it runs, and when it's waiting to: it keeps +# trying for as long as a chat's own gateway is in its way. case "$(uname -s)" in Darwin) UNIT="$HOME/Library/LaunchAgents/ai.hermes.gateway-uncensored.plist" - service_running() { case "$(launchctl list ai.hermes.gateway-uncensored 2>/dev/null)" in *'"PID" = '*) ;; *) false ;; esac; } ;; + service_wanted() { + case "$(launchctl list ai.hermes.gateway-uncensored 2>/dev/null || true)" in + *'"PID" = '*) ;; *'"LastExitStatus" = 0;'*) false ;; *'"LastExitStatus" = '*) ;; *) false ;; + esac + } ;; *) UNIT="$HOME/.config/systemd/user/hermes-gateway-uncensored.service" - service_running() { systemctl --user is-active --quiet hermes-gateway-uncensored.service 2>/dev/null; } ;; + service_wanted() { + case "$(systemctl --user is-active hermes-gateway-uncensored.service 2>/dev/null || true)" in + active|activating|reloading) ;; *) false ;; + esac + } ;; esac # Ours, whichever engine it runs: an old ghost on Linux ran its gateway from ~/.hermes, with ghost's state. service_installed() { [ -f "$UNIT" ] && grep -qF -e "$ENG/" -e "$GHOST_HOME/" "$UNIT"; } @@ -170,7 +179,7 @@ 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; } -if service_installed && service_running; then : > "$RESTART"; fi +if service_installed && service_wanted; then : > "$RESTART"; fi # (--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 diff --git a/tests/test_fork_engine.py b/tests/test_fork_engine.py index 60ec05c..d5b951c 100644 --- a/tests/test_fork_engine.py +++ b/tests/test_fork_engine.py @@ -30,8 +30,13 @@ # Stand in for the service managers, which would otherwise answer for this machine's own ghost. SERVICE_MANAGERS = { - "launchctl": '#!/bin/sh\n[ -e "$HOME/gateway-on" ] && echo \'"PID" = 123;\' || echo \'"LastExitStatus" = 0;\'\n', - "systemctl": '#!/bin/sh\n[ -e "$HOME/gateway-on" ]\n', + "launchctl": """#!/bin/sh +case "$(cat "$HOME/gateway" 2>/dev/null)" in running) echo '"PID" = 123; "LastExitStatus" = 0;' ;; waiting) echo '"LastExitStatus" = 19200;' ;; +*) echo '"LastExitStatus" = 0;' ;; esac +""", + "systemctl": """#!/bin/sh +case "$(cat "$HOME/gateway" 2>/dev/null)" in running) echo active ;; waiting) echo activating; exit 3 ;; *) echo inactive; exit 3 ;; esac +""", } @@ -85,9 +90,8 @@ def process(self, shape, *args): time.sleep(0.05) return proc - def service(self, running, runs=None): - if running: - (self.home / "gateway-on").touch() + def service(self, state, runs=None): + (self.home / "gateway").write_text(state) rel = ("Library/LaunchAgents/ai.hermes.gateway-uncensored.plist" if platform.system() == "Darwin" else ".config/systemd/user/hermes-gateway-uncensored.service") unit = self.home / rel @@ -252,16 +256,17 @@ def test_anything_else_is(released, change): def test_a_current_engine_leaves_the_gateway_alone(released): assert released.run().returncode == 0 - released.service(running=True) + released.service("running") assert released.run("--refresh-gateway").returncode == 0 # for the build just made before = released.calls() assert released.run().returncode == 0 and released.run("--refresh-gateway").returncode == 0 assert [c for c in released.calls()[len(before):] if c != "--version"] == [] -def test_running_gateway_is_stopped_then_restarted_on_the_new_engine(box): +@pytest.mark.parametrize("state", ["running", "waiting"]) # for a chat's own gateway to go +def test_running_gateway_is_stopped_then_restarted_on_the_new_engine(box, state): assert box.run(src=box.source("one")).returncode == 0 - box.service(running=True) + box.service(state) assert box.run(src=box.source("two")).returncode == 0 assert "-p uncensored gateway stop --yes" in box.calls() and box.restart.exists() assert box.run("--refresh-gateway").returncode == 0 @@ -272,7 +277,7 @@ def test_running_gateway_is_stopped_then_restarted_on_the_new_engine(box): def test_a_gateway_an_old_ghost_ran_from_elsewhere_is_moved_too(box): """On Linux it ran from ~/.hermes/hermes-agent, with ghost's state. Left alone it stayed stopped.""" assert box.run(src=box.source("one")).returncode == 0 - box.service(running=True, runs=f"HERMES_HOME={box.state}/profiles/uncensored\n{box.home}/.hermes/hermes-agent/venv/bin/python -m hermes_cli.main") + box.service("running", runs=f"HERMES_HOME={box.state}/profiles/uncensored\n{box.home}/.hermes/hermes-agent/venv/bin/python -m hermes_cli.main") assert box.run(src=box.source("two")).returncode == 0 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" @@ -280,21 +285,21 @@ def test_a_gateway_an_old_ghost_ran_from_elsewhere_is_moved_too(box): def test_someone_elses_gateway_is_not_touched(box): assert box.run(src=box.source("one")).returncode == 0 - box.service(running=True, runs=f"HERMES_HOME={box.home}/.hermes/profiles/uncensored\n{box.home}/.hermes/hermes-agent/venv/bin/python") + box.service("running", runs=f"HERMES_HOME={box.home}/.hermes/profiles/uncensored\n{box.home}/.hermes/hermes-agent/venv/bin/python") assert box.run(src=box.source("two")).returncode == 0 and not box.restart.exists() assert box.run("--refresh-gateway").returncode == 0 and not [c for c in box.calls() if "gateway install" in c] def test_gateway_is_started_again_when_the_build_fails(box): assert box.run(src=box.source("one")).returncode == 0 - box.service(running=True) + box.service("running") assert box.run(src=box.source("two", broken=True)).returncode != 0 assert box.calls()[-1] == "-p uncensored gateway start" and not box.restart.exists() def test_stopped_gateway_stays_stopped(box): assert box.run(src=box.source("one")).returncode == 0 - box.service(running=False) + box.service("stopped") assert box.run(src=box.source("two")).returncode == 0 assert box.run("--refresh-gateway").returncode == 0 assert box.calls()[-1] == "-p uncensored gateway install --force --no-start-now --start-on-login" diff --git a/tests/test_launch.py b/tests/test_launch.py index c7786a4..8c50a12 100644 --- a/tests/test_launch.py +++ b/tests/test_launch.py @@ -1,4 +1,5 @@ """The launcher: what runs the engine, what asks for a login first, and what must contact nobody.""" +import json import os import socket import subprocess @@ -92,6 +93,38 @@ def test_everything_else_works_without_one(box, args): assert (box.ran, box.started) == ([args], []) # and contacts nobody, not even the bridge +@pytest.mark.parametrize("argv, args, stops", [ + (["gateway", "run", "--quiet", "--idle-exit"], ["gateway", "install", "--start-now"], True), + (["gateway", "run", "--quiet", "--idle-exit"], ["gateway", "start"], True), + (["gateway", "run", "--quiet", "--idle-exit"], ["gateway", "setup"], True), + (["gateway", "run", "--quiet", "--idle-exit"], ["gateway", "install", "--no-start-now"], False), + (["gateway", "run", "--quiet", "--idle-exit"], ["gateway", "install", "--help"], False), + (["gateway", "run", "--quiet", "--idle-exit"], ["gateway", "status"], False), + (["gateway", "run", "--quiet", "--idle-exit"], ["gateway", "stop"], False), + (["gateway", "run"], ["gateway", "install"], False), # the one that's to stay + (None, ["gateway", "install"], False), +]) +def test_a_chats_own_gateway_makes_way_for_the_one_you_set_up(box, monkeypatch, capsys, argv, args, stops): + """It idles on for ten minutes, or for good with Telegram in it, and the service couldn't start until it left.""" + record, calls, busy = box.profile / "gateway.pid", [], [] + if argv: + record.write_text(json.dumps({"pid": 1, "argv": argv})) + + def run(command, **how): + calls.append(command[1:]) + if not busy: + record.unlink() + return SimpleNamespace(returncode=1 if busy else 0) + monkeypatch.setattr(launch, "engine_binary", lambda: Path("engine")) + monkeypatch.setattr(launch.subprocess, "run", run) + assert launch.main(args) == 0 and box.ran == [args] + assert calls == ([["-p", "uncensored", "gateway", "stop"]] if stops else []) + if stops: + busy.append(1) # in the middle of something + record.write_text(json.dumps({"pid": 1, "argv": argv})) + assert launch.main(args) == 0 and "Run this again when it's done" in capsys.readouterr().err + + def test_a_terminal_is_asked_to_log_in_first(box, monkeypatch): calls = terminal(monkeypatch, answer=0) assert launch.main(["-z", "hi"]) == 0 From 89b5ea1cbeda391f09a852329f1d76f4a6e7b944 Mon Sep 17 00:00:00 2001 From: Advait Date: Wed, 25 Nov 2026 19:19:04 +0000 Subject: [PATCH 15/15] README: what an intercepted registry means --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2520cef..702f23e 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ On Windows, from a clone: `powershell -ExecutionPolicy Bypass -File .\install.ps An update keeps the settings you changed in `~/.ghost/profiles/uncensored/config.yaml`, and a `SOUL.md` of your own (the release's is then beside it, as `SOUL.md.new`). -**On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`, which a Mac with a proxy script needs) and the certificates the system trusts. It needs to reach `chat-api.memchat.io`, and `ogevmdevnet.opengradient.ai`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection, and has only the enclaves it knew when it was released to go by, which change every few weeks. Installing also needs `github.com`, `*.githubusercontent.com`, `astral.sh`, `*.astral.sh`, `pypi.org`, `files.pythonhosted.org`, `nodejs.org`, `registry.npmjs.org` and, for the browser, `cdn.playwright.dev` and `storage.googleapis.com`. +**On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`, which a Mac with a proxy script needs) and the certificates the system trusts. It needs to reach `chat-api.memchat.io`, and `ogevmdevnet.opengradient.ai`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection. Without it, ghost goes by the enclaves it knew when it was released, and those change whenever OpenGradient deploys. Installing also needs `github.com`, `*.githubusercontent.com`, `astral.sh`, `*.astral.sh`, `pypi.org`, `files.pythonhosted.org`, `nodejs.org`, `registry.npmjs.org` and, for the browser, `cdn.playwright.dev` and `storage.googleapis.com`.