Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ On Windows, from a clone: `.\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`.

**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`. If the network inspects TLS, the second one has to be exempt: that's where ghost reads which enclaves to trust, and it won't take that from an intercepted connection.
**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.

</details>

Expand Down Expand Up @@ -143,7 +143,7 @@ The model's host is NEAR AI for DeepSeek V4.1 Flash Abliterated (served from TEE

## 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`. A reply is never paid for twice: what comes back unusable is reported, not retried.
- **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.
- **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 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`.
Expand Down
78 changes: 51 additions & 27 deletions privacy/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import json
import os
import random
import re
import threading
import time
import warnings
Expand All @@ -25,6 +26,7 @@
import ghost_auth
import outbound
import spend
from enclaves import REGISTRY, Enclaves
from ghost_auth import AuthError
from localhttp import LocalServer

Expand Down Expand Up @@ -155,7 +157,7 @@ def _apply_model_steer(obj):
def _apply_limits(obj):
asked = obj.get("max_tokens") or obj.get("max_completion_tokens")
obj.pop("max_completion_tokens", None)
obj["max_tokens"] = min(int(asked), MAX_TOKENS) if asked else MAX_TOKENS
obj["max_tokens"] = min(asked, MAX_TOKENS) if isinstance(asked, int) and asked > 0 else MAX_TOKENS
effort = str(obj.get("reasoning_effort") or DEFAULT_EFFORT).lower()
effort = _EFFORT_ALIASES.get(effort, effort)
obj["reasoning_effort"] = effort if effort in _EFFORTS else DEFAULT_EFFORT
Expand All @@ -169,10 +171,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
REGISTRY = "https://ogevmdevnet.opengradient.ai" # only to look up its proxy; the transport has its own
# 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, 504})
_RETRY_STATUS = frozenset({500, 502, 503}) # (a 504 is a load balancer giving up on a request that goes on running)
_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
_BREAK_WINDOW = 300.0
Expand Down Expand Up @@ -200,8 +202,8 @@ def _upstream():
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),
registry_transport=outbound.transport(REGISTRY, public_only=True))
transport = OHTTPTransport(relay_url=relay, verify_before_release=True, timeout=TIMEOUT, transport=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}"}

Expand All @@ -221,19 +223,22 @@ def _open(obj):
client, headers = _upstream()
try:
resp = client.send(client.build_request("POST", UPSTREAM, json=obj, headers=headers), stream=True)
except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout) as e:
except _NEVER_ARRIVED as e:
tries += 1
if tries == _MAX_TRIES:
raise Refused(502, f"couldn't reach DreamFort ({type(e).__name__}); check your connection and try again") from e
why = f"your proxy said: {e}" if isinstance(e, httpx.ProxyError) else type(e).__name__
raise Refused(502, f"couldn't reach DreamFort ({why}); check your connection and try again") from e
log(f"relay unreachable (try {tries}): {e}; retrying")
_backoff(tries - 1)
continue
if resp.status_code < 400:
return resp
try:
message = _decode_error(resp.read())
message = _decode_error(resp.read(), resp.status_code)
finally:
resp.close()
if resp.status_code == 504:
raise httpx.ReadTimeout(message)
if resp.status_code == 429 and waits:
log(f"too many requests this minute; waiting {waits[0]}s")
_wait(waits.pop(0))
Expand Down Expand Up @@ -318,17 +323,25 @@ def completion(self):
return body


def _host_failed(error):
"""What the enclave says when the model's host failed it. Nothing is billed: it settles a finished reply."""
message = str(error.get("message") or error) if isinstance(error, dict) else str(error)
status = int(next(iter(re.findall(r"Error code: (\d{3})", message)), 502))
if status not in (400, 404, 413, 422): # those are about the request (too long, say), which the engine can act on
status = 502
return Refused(status, f"the model's host answered: {message[:600]}")


def _generate(obj):
"""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)
reply = Reply(obj["max_tokens"])
resp = _open({**obj, "stream": True})
ended = False
reply, resp, ended = Reply(obj["max_tokens"]), None, False
try:
resp = _open({**obj, "stream": True})
for line in resp.iter_lines():
if not line.startswith("data:"):
continue
Expand All @@ -338,23 +351,28 @@ def _generate(obj):
break
event = json.loads(data)
if event.get("error"):
raise httpx.RemoteProtocolError(str(event["error"])[:200])
raise _host_failed(event["error"])
reply.feed(event)
ended = ended or reply.finish is not None
if not ended:
raise httpx.RemoteProtocolError("the reply stopped early")
except (httpx.HTTPError, TeeVerificationError, ValueError) as e:
# Accepted, so billed, but we never got it. One engine retry is fair; a second break in a row is not.
except (AuthError, Refused): # never accepted, or never billed
raise
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()
log(f"reply lost after it was accepted: {type(e).__name__}: {e}")
message = f"the connection to the enclave broke before the reply arrived ({type(e).__name__})"
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__})")
if again:
raise Unusable(message + " twice in a row; each attempt is billed, so ghost stopped retrying. Try again in a moment.") from e
raise Unusable(message + ", twice in a row; each attempt is billed, so ghost stopped retrying. Try again in a moment.") from e
raise Refused(502, message) from e
finally:
resp.close()
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)
spend.record(obj.get("model"), tokens_in, reply.tokens_out, cost)
Expand All @@ -363,17 +381,21 @@ def _generate(obj):
return reply


def _decode_error(raw: bytes) -> str:
def _decode_error(raw: bytes, status) -> str:
"""What an error reply says, in a line for people."""
try:
data = json.loads(raw)
if isinstance(data, dict):
err = data.get("error")
if isinstance(err, dict):
return str(err.get("message") or err)
return str(err or data.get("detail") or "the relay returned an error")
except Exception:
pass
return raw.decode("utf-8", errors="ignore")[:300] or "the relay returned an error"
error = data.get("error") if isinstance(data, dict) else None
if isinstance(error, dict) and error.get("code") == "tee_not_active":
return "the enclave ghost picked isn't active any more; if this keeps happening, run `ghost update`"
message = str((error.get("message") or error) if isinstance(error, dict) else error or data.get("detail") or "")
except (ValueError, AttributeError):
message = raw.decode("utf-8", errors="ignore")
quoted = re.search(r"\(relay: (.*)\)\s*$", message, re.S) # opengradient-ohttp's own words are about API keys
message = (quoted.group(1) if quoted else message).strip()
if not message or message.startswith("<"): # some proxy's page
return f"DreamFort isn't answering properly ({status}); try again in a moment"
return message[:600]


class Handler(BaseHTTPRequestHandler):
Expand Down Expand Up @@ -457,7 +479,9 @@ def do_POST(self):
return
try:
obj = json.loads(raw)
except Exception as e:
if not isinstance(obj, dict):
raise ValueError("not an object")
except ValueError as e:
self._error(400, f"invalid JSON body: {e}")
return

Expand Down
14 changes: 12 additions & 2 deletions privacy/doctor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""ghost doctor: is everything between you and a model in order? Contacts DreamFort only, and no model."""
"""ghost doctor: is everything between you and a model in order? Contacts DreamFort and the TEE registry, and no model."""
import subprocess
import sys
import time
Expand Down Expand Up @@ -52,6 +52,16 @@ def relay():
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


def credits():
if ghost_auth.api_key():
return True, "see https://api.dreamfort.ai", None
Expand All @@ -77,7 +87,7 @@ def style(text, code):
failed = False
checks = [("Engine", engine), ("Login", login), ("Bridge", bridge)]
if ghost_auth.mode(): # nothing is contacted before you log in
checks += [("DreamFort", relay), ("Credits", credits)]
checks += [("DreamFort", relay), ("Enclaves", enclaves), ("Credits", credits)]
print()
for name, check in (*checks, ("Spending", spending)):
ok, detail, fix = check()
Expand Down
59 changes: 59 additions & 0 deletions privacy/enclaves.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""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.
"""
import random

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


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)


BUILT_IN = (
_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
-----END PUBLIC KEY-----
""", "ba5c847114ffc09e387b2b9946b1ab8e91528a308137fdb160f59ea9e1717112"),
)


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

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()

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
7 changes: 7 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""Tests run on people's own machines: whatever one forgets to replace must not be their ghost."""
import os
import tempfile

_home = tempfile.mkdtemp(prefix="ghost-tests-")
for name in ("GHOST_HOME", "OG_VEIL_HOME"): # (CI points them at the ghost it has just installed)
os.environ.setdefault(name, _home)
Loading
Loading