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/.github/workflows/test.yml b/.github/workflows/test.yml index 21492bf..0b67ec0 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 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 uv httpx 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" @@ -56,25 +56,34 @@ 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: | 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" + 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" - 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 efba9f2..702f23e 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`. @@ -46,13 +46,13 @@ 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 -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. | | `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. @@ -64,14 +64,14 @@ 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`. +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. +**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`. @@ -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. +- **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`). 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/bin/ghost-uninstall b/bin/ghost-uninstall index b7f68ce..776ae3f 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/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 8cb9517..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\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/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 748d1b3..59e2557 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,46 @@ 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 ghost_auth.Unavailable as e: + found["unreachable"] = str(e) + 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 +530,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 +579,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 +607,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..d9c1cd1 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,53 @@ 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: + 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" - 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: - return None, "the registry can't be read right now, so the one built into ghost is used", None + """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 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) def credits(): diff --git a/privacy/enclaves.py b/privacy/enclaves.py index 53e7ffd..e3fb0d2 100644 --- a/privacy/enclaves.py +++ b/privacy/enclaves.py @@ -1,59 +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. 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): - 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() + remember(found) + except RegistryError as e: + 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") + 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): - """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..70d973b 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() or os.name == "nt": + 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(): @@ -195,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()] @@ -202,13 +247,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() @@ -218,6 +265,22 @@ def run_engine(args): 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" @@ -229,8 +292,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): @@ -287,7 +352,12 @@ 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") + return 1 + forget_typed(config) if ghost_auth.mode() is None: stop = log_in_first(config) if stop == "local": @@ -295,6 +365,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..f9e35e8 100644 --- a/privacy/outbound.py +++ b/privacy/outbound.py @@ -1,12 +1,20 @@ """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, 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. """ +import json +import os +import socket import ssl +import subprocess import sys import urllib.request +from pathlib import Path from urllib.parse import urlsplit import certifi @@ -22,22 +30,93 @@ def trust(): return context +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) + 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..6c7a64c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,10 +13,12 @@ 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", + # 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/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/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/scripts/write_profile.py b/scripts/write_profile.py index c82c647..c9ecc78 100644 --- a/scripts/write_profile.py +++ b/scripts/write_profile.py @@ -1,41 +1,119 @@ #!/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 from pathlib import Path SOURCE = Path(__file__).resolve().parent.parent / "profile" SIDE_TASKS = "abliteration/deepseek-v4.1-flash-abliterated" -FALLBACK = "nous/hermes-4-405b" +# 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): + 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 -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): @@ -45,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/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/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 e4aadd3..38e704b 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, @@ -105,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: @@ -189,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 diff --git a/tests/test_bridge.py b/tests/test_bridge.py index 6ca99f7..64952de 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 @@ -246,15 +325,16 @@ 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() 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", {}) + monkeypatch.setattr(enclaves, "REMEMBERED", tmp_path / "enclaves.json") yield service server.shutdown() server.server_close() @@ -267,7 +347,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 +355,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 +364,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 @@ -291,27 +372,59 @@ 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 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 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: []) + 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_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 ────────────────────────────────────────────── @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 +448,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 +498,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_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_install.py b/tests/test_install.py index 9dda1c9..8d0903e 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" @@ -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() @@ -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]] @@ -226,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"]) @@ -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): diff --git a/tests/test_launch.py b/tests/test_launch.py index 8255fa8..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 @@ -44,7 +45,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") @@ -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 @@ -132,6 +165,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 +215,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 +232,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 +327,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..0262dec 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -304,8 +304,18 @@ 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("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) + 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 +342,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/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 1102582..b9d158c 100644 --- a/uv.lock +++ b/uv.lock @@ -373,16 +373,18 @@ version = "0.1.0" source = { virtual = "." } dependencies = [ { name = "certifi" }, - { name = "httpx" }, + { name = "httpx", extra = ["socks"] }, { name = "opengradient-ohttp" }, + { name = "ruamel-yaml" }, { name = "truststore" }, ] [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 = "ruamel-yaml", specifier = ">=0.18" }, { name = "truststore", specifier = ">=0.10" }, ] @@ -423,6 +425,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 +739,24 @@ 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" +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"