Files
ai-agent/backend/workers/terminal.py
gabrielvidal b000f4f8e0 fix(guests): push endpoints are push services, a ceiling on wrong sign-in codes, a Bash switch for No-project chats
Any https endpoint was accepted and a 307 from it re-POSTed to the hub's own
loopback as the owner. Sign-in codes: 10 wrong per address a day, 20 per IP in
10 min, 4 mails per address an hour, sent off the request thread. `scratchBash`
per guest (on by default) sets scope.noBash when off. Caps on guest ui-state
and drafts; the host-file secret filter follows links; enroll and terminal
claims re-checked.
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 15:23:05 +01:00

195 lines
8.6 KiB
Python

"""
A guest computer's terminal sessions — the ones its hub mirrors.
A guest's computer is mirrored for its hub-started runs only
(``guests.may_mirror``), unless the guest shares a session typed in its own
terminal (the computer's side is ``sidecar/terminal.py``). Either of two
things claims such a session:
* **ai-agent Claude** — the computer's ``claude`` launcher sent it through the
proxy (the guest picked *ai-agent Claude* at start). Every call carries its
session id in ``X-Claude-Code-Session-Id``; the proxy claims it on first
sight (``how="proxy"``). Nothing the computer *says* is needed — the call
itself is the proof, and it bills the owner's plan within the guest's limits.
* **synced** — the guest synced a session that ran on their own login (the
mod's ``/ai-agent sync``, ``ai-agent-worker sync``, or *Sync* on their
portal's list): its ``/feed`` lists the id under ``synced``
(``how="local"``). Its spend is theirs: ``accountSource`` is their own
Claude (``guest-<uid>``, out of the totals).
A claim stamps ``workerSource`` + ``owner`` like any mirrored session, so
``guests.session_belongs`` accepts it from then on, and ``terminal`` (``proxy``
| ``local``) — what the app shows on the card. It is refused for a session the
hub knows from anywhere else (another runner, person, a transcript in any
other source, or any meta that doesn't place it on this computer — an
owner's run launched a second ago has only that): a computer could otherwise
name an id it saw and have it stamped as the guest's.
"""
from __future__ import annotations
import re
import threading
SID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
HOWS = ("proxy", "local")
# (worker id, sid) → what it is: "run" (the hub started it), "proxy" /
# "local" (claimed), False (refused). The proxy asks on every call; only a
# local claim turning proxy changes an answer.
_seen: dict[tuple[str, str], str | bool] = {}
_lock = threading.Lock()
def _known_elsewhere(sid: str) -> bool:
"""A transcript of ``sid`` in any source but the workers' mirror."""
from core.config import ARCHIVE_DIR, SOURCE_DIRS, WORKERS_SOURCE_DIR
for d in (*SOURCE_DIRS, ARCHIVE_DIR):
if not d or d == WORKERS_SOURCE_DIR or not d.is_dir():
continue
if next(d.glob(f"*/{sid}.jsonl"), None) is not None:
return True
return False
def expect_run(wid: str, sid: str) -> None:
"""A run the hub is about to start on guest computer ``wid``. Its first
proxied call can beat the spawn's own ``meta.worker`` stamp — the spawn's
reply crosses the worker link after the CLI is already talking — and
must not be claimed as a terminal session (the card would say "Terminal ·
the host's Claude" on a conversation started from the app)."""
with _lock:
_seen[(wid, sid.strip().lower())] = "run"
def claim(deps, w: dict, sid: str | None, how: str) -> bool:
"""Make terminal session ``sid`` on guest computer ``w`` one the hub
mirrors; True when it is (now, or already)."""
from . import guests
sid = (sid or "").strip().lower()
if not guests.is_guest(w) or how not in HOWS or not SID_RE.match(sid):
return False
key = (w["id"], sid)
hit = _seen.get(key)
if hit is False or hit in ("run", "proxy") or (hit == "local" and how == "local"):
return hit is not False
meta = deps.meta_store.peek(sid) or {}
if guests._elsewhere(meta, w):
_seen[key] = False
return False
if meta.get("worker") == w["id"]:
_seen[key] = "run" # a run the hub started there: already its own
return True
mine = meta.get("workerSource") == w["id"]
if not mine and (meta or _known_elsewhere(sid)):
# Any meta at all means the hub already knows this id — a run it
# launched (``runAs``, before its transcript is on disk), a card
# someone titled — and nothing in it says this computer. A terminal
# session is new to the hub by nature (there is no ``expect_run`` for
# what a guest types in their own terminal), so "new to the hub" is
# the one provenance a claim can show.
_seen[key] = False
return False
with _lock:
# ai-agent Claude wins: a synced local session the guest then resumed
# on the proxy bills the owner from there on.
prev = meta.get("terminal")
term = "proxy" if "proxy" in (how, prev) else "local"
patch = {"workerSource": w["id"], **guests.stamp(w), "terminal": term}
if term == "local" and not meta.get("account"):
from accounts.profiles import guest_account
patch["accountSource"] = guest_account(guests.owner_of(w))
changed = deps.meta_store.stamp_many({sid: patch})
_seen[key] = term
if changed:
if deps.feed_mirror is not None and not mine:
# Its transcript may have been listed (and refused) already: the
# next pass lists the whole feed again.
deps.feed_mirror.rewind(w["id"])
deps.hub.publish({"type": "meta"})
return True
def claim_synced(deps, w: dict, sids) -> None:
"""The ids a guest computer's ``/feed`` lists as synced."""
for sid in (sids or [])[:500] if isinstance(sids, list) else []:
if isinstance(sid, str):
claim(deps, w, sid, "local")
def forget(wid: str | None = None) -> None:
"""Drop the cache (a computer removed, or tests)."""
with _lock:
for k in [k for k in _seen if wid is None or k[0] == wid]:
_seen.pop(k, None)
# ── stop syncing ─────────────────────────────────────────────────────────────
def still_synced(deps, w: dict, sid: str) -> bool:
"""A session synced off the guest's own login keeps coming while the
computer still lists it; unsynced there (the mod's ``/ai-agent unsync``,
``ai-agent-worker unsync``, the portal), the hub keeps the copy it has and
takes no more of it. An ai-agent Claude session always comes."""
meta = deps.meta_store.peek(sid) or {}
if meta.get("terminal") != "local":
return True
listed = deps.feed_mirror.synced_of(w["id"]) if deps.feed_mirror is not None else None
return listed is None or sid in listed
# ── what the computer's picker and mod show (pushed on the probe) ────────────
def desired_status(deps, w: dict) -> dict:
"""The figures ``terminal-status.json`` holds on a guest's computer: their
month's budget left (lab + computers — the proxy's own sum), paused, why
it waits, the guest host and the owner's name. Money to the cent, so a
call's spend moves it once, not on every probe."""
from users import computers, runs as guest_runs
from users.caller import OWNER_NAME
from users.deliver import GUEST_PUBLIC_URL
from . import guests
uid = guests.owner_of(w)
u = deps.users.get(uid) or {}
budget = u.get("budgetUsd")
left = None
if budget is not None:
left = round(float(budget) - guest_runs.month_spend_all(deps, uid), 2)
wait = computers.waiting(deps, uid)
return {"hubUrl": GUEST_PUBLIC_URL, "ownerName": OWNER_NAME,
"budgetUsd": budget, "leftUsd": left,
"paused": bool(w.get("paused")), "waiting": (wait or {}).get("kind"),
"computer": w.get("name") or w.get("hostname")}
def status_hash(d: dict) -> str:
"""``sidecar/terminal.status_hash``'s twin: equal ⇒ nothing to push."""
import hashlib
import json
raw = json.dumps(d, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(raw.encode()).hexdigest()[:16]
_pushed: dict[str, tuple[str, float]] = {}
RETRY_S = 300
def maybe_push_status(deps, w: dict, held: dict | None) -> bool:
"""After a guest computer's probe: send the figures when ``/health``'s
``terminal.statusHash`` differs (an older sidecar has no ``terminal`` —
nothing to push to). The same figures are retried after ``RETRY_S``."""
import time
from . import guests
from .store import sidecar_request
if not guests.is_guest(w) or not isinstance(held, dict):
return False
d = desired_status(deps, w)
h = status_hash(d)
if held.get("statusHash") == h:
return False
last = _pushed.get(w["id"])
if last and last[0] == h and time.time() - last[1] < RETRY_S:
return False
_pushed[w["id"]] = (h, time.time())
sidecar_request(w["url"], w["token"], "/terminal/status", {"status": d}, timeout=10,
label=f"computer {w.get('name') or w['id']}", method="PUT")
return True