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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ The agent's own web searches, page fetches and browser go out from your machine

## 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.
- **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. Leaving a chat stops it: close the window, press Ctrl-C or kill ghost mid-task, and nothing more is sent or paid for.
- **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.
Expand Down
76 changes: 76 additions & 0 deletions scripts/debrand.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,64 @@
[#CD7F32] ██▀██▀██▀██▀██[/]"""
ART_CONSTS = [("HERMES_AGENT_LOGO", GHOST_LOGO), ("HERMES_CADUCEUS", GHOST_ART)]

# What the gateway does when the last viewer leaves a chat a person started (the patches below wire it in).
STOP_UNWATCHED = '''


# The chats a person types into here: a window, or `ghost -z`. Bots, cron, kanban and editors keep upstream's way.
_TYPED_INTO = frozenset({'cli', 'tui', 'oneshot'})


def _typed_into(authority, session_id):
"""Blocking: *session_id* was opened by a person at this machine (its frozen launch source)."""
store = authority_persistence(authority)
try:
receipt = store.bindings.receipt(session_id)
row = store.sessions.get(receipt.current_target)
except (AuthorityRefusal, KeyError, TypeError):
return False
return ((receipt.policy or {}).get('source') or getattr(row, 'source', None)) in _TYPED_INTO


async def stop_unwatched(authority, actor, session_id, *, orphaned=False): @NOTE
"""The last viewer left a chat a person started: it closed, was killed, or lost its terminal. Its
queued input is withdrawn and its turn stopped, so nothing more is sent or paid for with nobody
there; one that vanished without closing also ends the delegations a close would have ended.
The chat itself stays, and resumes."""
try:
await _stop_unwatched(authority, actor, session_id, orphaned)
except Exception: # health: allow BLE001 -- the viewer's detach must still go through
logger.warning('Could not stop the work of %s after its last viewer left', session_id, exc_info=True)


async def _stop_unwatched(authority, actor, session_id, orphaned):
live = authority.sessions.get(session_id)
if live is None or live.subscribers or is_history_mount(live):
return
if not await asyncio.to_thread(_typed_into, authority, session_id):
return
from gateway.session_contract import SessionRef
ref = SessionRef(authority.profile_id, session_id)
if orphaned:
from tools.async_delegation import interrupt_for_session, refuse_for_session
parents = tuple(dict.fromkeys((session_id, _physical_target(authority, session_id))))
refuse_for_session((authority.profile_id, session_id), session_key=live.route, parent_session_ids=parents)
for parent in parents:
interrupt_for_session(session_key=live.route, parent_session_id=parent, reason='viewer_gone')
with live.event_stream.lock:
queued = [row['admission_id'] for row in authority._pending_rows(ref) if row.get('status') == 'queued']
for admission_id in queued:
with contextlib.suppress(AuthorityRefusal, KeyError):
await authority.cancel_or_claimed(actor, ref, admission_id)
if live.subscribers:
return
with contextlib.suppress(AuthorityRefusal, KeyError):
handle = authority._handle(ref)
if handle.execution_state == 'running':
from gateway.session_managed_worker import interrupt_managed
if not interrupt_managed(authority, actor, ref, handle.execution_generation):
await authority.interrupt(actor, ref, handle.execution_generation)'''

# Incognito code patches: (path, find-regex, replacement, note). @NOTE in the replacement becomes the
# comment `# ghost: <note>`, unique within its file, which is how a second run knows a patch is in.
MARK = "# ghost:"
Expand Down Expand Up @@ -235,6 +293,24 @@
' _skip = _re.compile(r"nous|portal|subscription|sonnet|opus|claude|gpt-|gemini|grok|openrouter", _re.I)\n'
" keys = [k for k in tip_keys() if not _skip.search(t(k, lang=DEFAULT_LANGUAGE))] @NOTE\n",
"open-weight only"),
# -- leaving a chat stops it. Upstream lets a turn run on for a viewer that closed, was killed or lost its terminal,
# and finishes it at your expense with nobody there; `ghost -z` even says so on Ctrl-C. Here the last viewer
# leaving a chat you started withdraws what it queued and stops the turn. The chat stays, and resumes.
("gateway/session_viewer_close.py",
r"(\n\n\nasync def close_viewer_session\(authority, session_id, reason\):\n)",
STOP_UNWATCHED + r"\1",
"leaving a chat stops it"),
("gateway/session_authority.py",
r"( await asyncio\.to_thread\(release_editor_mcp, self, \[session_id\]\)\n)",
r"\1"
" if end_reason or orphaned: @NOTE\n"
" from gateway.session_viewer_close import stop_unwatched\n"
" await stop_unwatched(self, actor, session_id, orphaned=orphaned)\n",
"nobody is left in the chat"),
("hermes_cli/gateway_chat.py",
r'print\("Detached; accepted work continues at the gateway\.", file=sys\.stderr\)',
'print("Stopped.", file=sys.stderr) @NOTE',
"the gateway stops what this chat started"),
]

# Upstream defaults ghost flips off for EVERY profile. The shipped profile sets these too; baking them
Expand Down
23 changes: 23 additions & 0 deletions tests/e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import json
import os
import platform
import signal
import subprocess
import sys
import time
Expand All @@ -31,6 +32,26 @@ def requests():
return rows


def leave_mid_turn():
"""A chat that runs a command for 20 seconds, killed a few seconds in: the requests made for it, once the command
would have ended. One, unless the turn went on with nobody there."""
ping = f"ping {'-n' if WINDOWS else '-c'} 20 127.0.0.1"
chat = subprocess.Popen([str(BIN / ("ghost.cmd" if WINDOWS else "ghost")), "-z", f"[[run {ping}]]", "--yolo"], env=ENV,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
**({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if WINDOWS else {"start_new_session": True}))
deadline = time.time() + 120
while not LOG.read_text(encoding="utf-8").strip() and time.time() < deadline:
time.sleep(0.5)
time.sleep(5) # the command is running
if WINDOWS:
subprocess.run(["taskkill", "/f", "/t", "/pid", str(chat.pid)], capture_output=True)
else:
os.killpg(chat.pid, signal.SIGKILL)
chat.wait()
time.sleep(30) # it would end in about 15 seconds, and a turn still going asks the model again then
return requests()


def up():
try:
with urllib.request.urlopen("http://127.0.0.1:8788/healthz", timeout=2) as resp:
Expand Down Expand Up @@ -90,6 +111,8 @@ def main():
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()
asked = leave_mid_turn()
good &= check("a chat you leave stops, and nothing more is sent", len([r for r in asked if r.get("tools")]) == 1, asked)
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]]")
Expand Down
34 changes: 34 additions & 0 deletions tests/test_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,40 @@ 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_leaving_a_chat_stops_it(engine):
"""The last viewer leaving a chat a person started withdraws what it queued and stops its turn. A bot's or a cron
job's turn, and a chat somebody is still in, are left alone. (tests/e2e.py leaves one for real.)"""
did = engine('''
import asyncio, threading, types
from gateway.session_viewer_close import stop_unwatched
class Authority:
profile_id = "default"
def __init__(self, source, watched):
receipt = types.SimpleNamespace(policy={"source": source}, current_target="s1")
self.persistence = types.SimpleNamespace(bindings=types.SimpleNamespace(receipt=lambda sid: receipt),
sessions=types.SimpleNamespace(get=lambda sid: None))
self.sessions = {"s1": types.SimpleNamespace(subscribers={"v": 1} if watched else {}, source=object(), route="r",
event_stream=types.SimpleNamespace(lock=threading.Lock()))}
self.did = []
def _pending_rows(self, ref):
return [{"admission_id": "queued-1", "status": "queued"}, {"admission_id": "running-1", "status": "started"}]
async def cancel_or_claimed(self, actor, ref, admission_id):
self.did.append("withdrew " + admission_id)
def _handle(self, ref):
return types.SimpleNamespace(execution_state="running", execution_generation=3)
async def interrupt(self, actor, ref, generation):
self.did.append("stopped %d" % generation)
out = {}
for source, watched, orphaned in [("cli", False, False), ("oneshot", False, True), ("telegram", False, True),
("cron", False, False), ("cli", True, True)]:
authority = Authority(source, watched)
asyncio.run(stop_unwatched(authority, None, "s1", orphaned=orphaned))
out["%s%s" % (source, " (watched)" if watched else "")] = authority.did
''')
stopped = ["withdrew queued-1", "stopped 3"]
assert did == {"cli": stopped, "oneshot": stopped, "telegram": [], "cron": [], "cli (watched)": []}


def test_searches_ask_one_engine_at_a_time(engine):
asked = engine("""
import sys, types
Expand Down
Loading