Files
gabrielvidalandClaude Opus 5.5 effaa3b532 feat(guests): guests' own computers as workers, held to the owner's limits
- workers/link.py: the hub's half of the worker link — enroll codes, long-poll
  relay, pairing through the link; a tunnelled worker's url is the backend's
  own loopback /_tunnel/<id>, so every existing caller works unchanged.
- users/computers.py: Settings → My computers API (list, add, rename, pause,
  remove) and the owner's per-guest switch + max (computers) and global
  guestDefaults.computerLimits.
- claudeproxy/limits.py: every proxied call is metered into a monthly ledger;
  a guest computer's calls are refused past their budget, outside their
  models, while the owner's plan is past 80 % (5 h) / 85 % (week), past 10 in
  flight or 60 a minute, for fast mode, the 1M beta or any path but
  v1/messages(+count_tokens). The public host takes guest tokens only.
- workers/guests.py: a guest computer mirrors only sessions the hub started
  there, posts only into its own sessions, gets only the guests' shared
  skills, rotates its tokens weekly, has a 500 MB/month mirror quota; an IP
  presenting bad tokens is locked for an hour.
- runs: a guest runs on their own computer (confined to its start folder,
  owner's default account, their models and budget); nobody else does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 19:59:09 +01:00

355 lines
14 KiB
Python

"""
What the Claude proxy meters and refuses — the owner's limits on a guest's
machine.
A guest worker's proxy token sits on the guest's own disk, so it is an API key
in all but name: anything the owner wants limited has to be enforced here,
where every model call passes. (The owner's own workers go through the same
meter — it is the per-worker spend on their page — but none of the refusals.)
* **The meter** (``UsageTap``): the reply streams through untouched while a
tap reads its ``usage`` — the SSE ``message_start`` / ``message_delta``
events of a streamed reply (cumulative, so the largest value wins), the body
of a plain one — and prices it at list price (``conversations/pricing``).
The upstream request asks for ``identity`` encoding so the tap reads text.
* **The ledger** (``Ledger``): one JSON line per metered call in
``PROXY_LEDGER_DIR/<YYYY-MM>.jsonl`` (worker, its guest, account, model,
usage, $), summed in memory per month and guest. A guest's budget is the
same monthly budget their lab runs count against: the lab's from the
conversation cards (``users/runs.spend_by_user``, which leaves a guest
worker's conversations out), the machine's from here.
* **The guards** (``refusal``) before a guest worker's call goes upstream —
each refusal is an error in the API's own shape, so Claude Code shows it:
its guest disabled or *Lock guests* on, a model outside their families, the
month's budget spent, the owner's own plan window past the guest ceiling
(5 h / 7 d utilization off the account's freshest reading), too many calls
in flight from that machine.
"""
from __future__ import annotations
import datetime
import json
import os
import pathlib
import re
import threading
import time
from conversations import pricing
LEDGER_DIR = pathlib.Path(os.environ.get("PROXY_LEDGER_DIR", "/data/proxy-ledger"))
# A reply body kept for the tap past this is not a usage-bearing reply.
_MAX_BODY = 8 * 1024 * 1024
_MAX_LINE = 1024 * 1024
def _month(ts: float | None = None) -> str:
return datetime.datetime.fromtimestamp(ts if ts is not None else time.time(),
datetime.timezone.utc).strftime("%Y-%m")
# ── the meter ────────────────────────────────────────────────────────────────
class UsageTap:
"""Reads ``model`` + ``usage`` off a reply as it streams past."""
def __init__(self, content_type: str | None):
self.sse = "text/event-stream" in (content_type or "")
self.buf = bytearray()
self.model: str | None = None
self.speed: str | None = None
self.usage: dict = {}
def feed(self, chunk: bytes) -> None:
if not self.sse:
if len(self.buf) + len(chunk) <= _MAX_BODY:
self.buf += chunk
return
self.buf += chunk
while True:
i = self.buf.find(b"\n")
if i < 0:
break
line = bytes(self.buf[:i]).rstrip(b"\r")
del self.buf[:i + 1]
if line.startswith(b"data:") and b'"usage"' in line:
self._event(line[5:].strip())
if len(self.buf) > _MAX_LINE:
self.buf.clear()
def _event(self, raw: bytes) -> None:
try:
d = json.loads(raw)
except ValueError:
return
if d.get("type") == "message_start":
m = d.get("message") or {}
self.model = m.get("model") or self.model
self._merge(m.get("usage"))
elif d.get("type") == "message_delta":
self._merge(d.get("usage"))
def _merge(self, u) -> None:
if not isinstance(u, dict):
return
for k, v in u.items():
if isinstance(v, bool):
continue
if isinstance(v, (int, float)):
self.usage[k] = max(self.usage.get(k) or 0, v)
elif k == "cache_creation" and isinstance(v, dict):
self.usage[k] = {**(self.usage.get(k) or {}), **v}
elif k == "speed" and isinstance(v, str):
self.speed = v
def finish(self) -> None:
if self.sse or not self.buf:
return
try:
d = json.loads(bytes(self.buf))
except ValueError:
return
if isinstance(d, dict) and d.get("type") == "message":
self.model = d.get("model") or self.model
self._merge(d.get("usage"))
def cost(self) -> float:
if not self.model or not self.usage:
return 0.0
try:
return float(pricing.usage_cost(pricing.norm_usage(self.usage), self.model,
self.speed))
except Exception:
return 0.0
# ── the ledger ───────────────────────────────────────────────────────────────
class Ledger:
"""Metered calls, one file a month; sums per (month, guest) and per
(month, worker) kept in memory, rebuilt from the files on first use."""
def __init__(self, root: pathlib.Path = LEDGER_DIR):
self.root = pathlib.Path(root)
self._lock = threading.Lock()
self._sums: dict[tuple[str, str, str], dict] = {}
self._loaded: set[str] = set()
def _load(self, month: str) -> None:
if month in self._loaded:
return
self._loaded.add(month)
try:
lines = (self.root / f"{month}.jsonl").read_text(encoding="utf-8").splitlines()
except OSError:
return
for line in lines:
try:
self._add(month, json.loads(line))
except (ValueError, TypeError):
continue
def _add(self, month: str, e: dict) -> None:
for kind, key in (("guest", e.get("guest")), ("worker", e.get("worker"))):
if not key:
continue
s = self._sums.setdefault((month, kind, key), {"usd": 0.0, "calls": 0,
"byAccount": {}})
s["usd"] += float(e.get("usd") or 0)
s["calls"] += 1
acct = e.get("account") or ""
s["byAccount"][acct] = s["byAccount"].get(acct, 0.0) + float(e.get("usd") or 0)
def record(self, entry: dict) -> None:
month = _month(entry.get("t"))
line = json.dumps(entry, separators=(",", ":"))
with self._lock:
self._load(month)
self.root.mkdir(parents=True, exist_ok=True)
with open(self.root / f"{month}.jsonl", "a", encoding="utf-8") as f:
f.write(line + "\n")
self._add(month, entry)
def spent(self, kind: str, key: str, account: str | None = None,
month: str | None = None) -> float:
"""This month's metered $ of a guest or a worker (on ``account`` only,
when given)."""
month = month or _month()
with self._lock:
self._load(month)
s = self._sums.get((month, kind, key))
if not s:
return 0.0
return float(s["byAccount"].get(account, 0.0) if account else s["usd"])
def summary(self, kind: str, key: str, month: str | None = None) -> dict:
month = month or _month()
with self._lock:
self._load(month)
s = self._sums.get((month, kind, key)) or {"usd": 0.0, "calls": 0, "byAccount": {}}
return {"month": month, "usd": round(s["usd"], 4), "calls": s["calls"],
"byAccount": {k: round(v, 4) for k, v in s["byAccount"].items()}}
LEDGER = Ledger()
# ── in flight ────────────────────────────────────────────────────────────────
_inflight: dict[str, int] = {}
_inflight_lock = threading.Lock()
def enter(wid: str) -> int:
with _inflight_lock:
_inflight[wid] = _inflight.get(wid, 0) + 1
return _inflight[wid]
def leave(wid: str) -> None:
with _inflight_lock:
n = _inflight.get(wid, 0) - 1
if n > 0:
_inflight[wid] = n
else:
_inflight.pop(wid, None)
def inflight(wid: str) -> int:
with _inflight_lock:
return _inflight.get(wid, 0)
# ── the guards ───────────────────────────────────────────────────────────────
def request_model(body: bytes) -> str | None:
"""The ``model`` a Messages request names (None: not a JSON body)."""
if not body or body[:1] != b"{":
return None
try:
d = json.loads(body)
except ValueError:
return None
m = d.get("model") if isinstance(d, dict) else None
return m if isinstance(m, str) else None
def model_allowed(model: str | None, families: list[str] | tuple) -> bool:
"""Is ``model`` one of these families (``sonnet`` ⇒ any ``claude-sonnet-*``)?
The same rule as a guest's lab runs (``users/runs.check_model``)."""
if not model:
return True
allowed = [f.lower() for f in families or ()] or ["sonnet"]
m = model.lower()
return m in allowed or any(re.search(rf"(^|-){re.escape(a)}(-|$)", m) for a in allowed)
def window_pct(usage_poller, account: str) -> dict[str, float]:
"""The account's freshest plan utilization, ``{five_hour: pct, seven_day:
pct}`` (what is known): its last poll or its last proxied reply."""
got = []
for src in (getattr(usage_poller, "latest", {}), getattr(usage_poller, "_observed", {})):
snap = (src or {}).get(account)
if snap and snap.get("updatedAt"):
got.append(snap)
if not got:
return {}
snap = max(got, key=lambda s: float(s["updatedAt"]))
return {k: float((w or {}).get("pct") or 0) for k, w in (snap.get("windows") or {}).items()
if k in ("five_hour", "seven_day")}
# The only API paths a guest's computer may call.
GUEST_PATHS = ("v1/messages", "v1/messages/count_tokens")
# Betas a guest's computer may not ask for: the 1M-token context (a premium
# long-context tier).
_REFUSED_BETAS = ("context-1m",)
class PerMinute:
"""Calls in the last minute, per guest (all their computers)."""
def __init__(self):
self._lock = threading.Lock()
self._hits: dict[str, list[float]] = {}
def take(self, key: str, limit: int) -> bool:
"""Count one call; False (not counted) when ``limit`` are already in
the last 60 s."""
now = time.time()
with self._lock:
hits = [t for t in self._hits.get(key, []) if now - t < 60]
if len(hits) >= limit:
self._hits[key] = hits
return False
hits.append(now)
self._hits[key] = hits
return True
PER_MINUTE = PerMinute()
def _request(body: bytes) -> dict:
if not body or body[:1] != b"{":
return {}
try:
d = json.loads(body)
except ValueError:
return {}
return d if isinstance(d, dict) else {}
def refusal(deps, w: dict, account: str, body: bytes, path: str,
beta: str | None = None) -> tuple[int, str, str, str] | None:
"""Why a guest's computer may not make this call now — ``(status, API
error type, message, kind)`` — else None. The owner's own workers: never.
``kind`` (``budget``, ``plan``, ``rate``…) is for the Security log and the
owner's push, not the wire."""
from users import runs as guest_runs
from workers import guests
uid = guests.owner_of(w)
if not uid:
return None
u = deps.users.active(uid)
if not u:
return 403, "permission_error", "this computer's guest account is disabled", "disabled"
if deps.security_state.guests_locked():
return 403, "permission_error", "guest access is paused for now", "locked"
if w.get("paused"):
return 403, "permission_error", ("this computer is paused — switch it back on in "
"your portal (Settings → My computers)"), "paused"
if path not in GUEST_PATHS:
return 404, "not_found_error", "not an API path a guest computer may call", "path"
if any(b in (beta or "") for b in _REFUSED_BETAS):
return 403, "permission_error", "the 1M-token context isn't open to guests", "beta"
req = _request(body)
if path == "v1/messages/count_tokens":
return None
if req.get("speed") == "fast":
return 403, "permission_error", "fast mode isn't open to guests", "fast"
lim = deps.users.defaults()["computerLimits"]
model = req.get("model") if isinstance(req.get("model"), str) else None
families = u.get("models") or []
if not model_allowed(model, families):
return 403, "permission_error", (f"the model {model!r} isn't enabled for you — "
f"use {', '.join(families) or 'sonnet'}"), "model"
budget = u.get("budgetUsd")
if budget is not None:
spent = guest_runs.month_spend_all(deps, uid)
if spent >= float(budget):
return 429, "rate_limit_error", (f"your monthly budget is spent (${spent:.2f} of "
f"${float(budget):.0f}) — it resets on the 1st"),\
"budget"
pct = window_pct(deps.usage_poller, account)
for key, cap, label in (("five_hour", lim["fiveHourPct"], "5-hour"),
("seven_day", lim["sevenDayPct"], "weekly")):
if pct.get(key, 0) >= cap:
return 429, "rate_limit_error", (f"the owner's {label} Claude usage is past "
f"{cap} % — guests' computers wait until it "
"goes back down"), "plan"
if inflight(w["id"]) >= lim["inFlight"]:
return 429, "rate_limit_error", (f"{lim['inFlight']} calls are already running on "
"this computer — wait for one to finish"), "inflight"
if not PER_MINUTE.take(uid, lim["perMinute"]):
return 429, "rate_limit_error", (f"more than {lim['perMinute']} calls in a minute — "
"slow down"), "rate"
return None