The core speaks English only; every other language is a kind: "translation" plugin
(translation-<lang>; the French one is translation-fr in ai-agent-plugins, seeded once at start).
- plugins: kind translation (typed_manifest.parse_translation: lang, name, englishName, flag,
locale, promptLine, ui/backend JSON dictionaries — strict, operator-only, in the fingerprint);
a top-level "languages" field on any plugin (default ["en"]) shown on its page; seeding takes
translation-*; plugins/translations.py reads the enabled ones (first by id wins a code).
- core/i18n: tr / langs / localized / clean_pref / effective_lang read the installed
translations; a pick whose translation is gone reads English and is kept; browserLang records
any base code. core/i18n_fr.py and FRENCH_LINE are gone (language_line = the plugin's promptLine).
- The owner picks a language too (users.json ownerLang, PUT /api/me {lang}; English by default).
- Public GET /api/i18n/languages and /api/i18n/{lang} (ETag/304), guest host and sign-in included.
- Coverage: backend/core/i18n_keys/{ui,backend}.json (kept by the two i18n tests,
UPDATE_I18N_KEYS=1); a translation's page shows translated / missing / stale / placeholder
mismatches.
- Frontend: frontend/src/i18n/fr removed; the dictionary comes from the hub, cached in
localStorage and revalidated in the background (first boot in a language waits <= 4 s, any
failure is English); Lang is a string; number/currency style from the translation's locale;
LanguageSelect lists English + installed translations (hidden when none); Settings → Plugins
has a Translations kind (tab, catalog filter, group) and a Translation section with the
missing-strings count; mock is English only.
- Tests: test_i18n.py rewritten on a made-up translation; i18n_testkit.speaking() for the
tests that need a second language. authz golden, openapi.json + src/generated regenerated;
docs/plugins.md (Translations), CLAUDE.md, i18n README, docs/settings.md.
Changelog
- Added: languages are plugins — Settings → Plugins → Translations; the owner can pick a language.
- Changed: French moved to the translation-fr plugin (seeded at start: nothing changes for guests).
- Removed: the core's built-in French dictionaries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1085 lines
52 KiB
Python
1085 lines
52 KiB
Python
"""
|
||
What changes when a guest starts or continues a run.
|
||
|
||
The trust model is **prompt-level** (the owner's call: "I trust my guests")
|
||
with one hard edge — the session's *write* permissions:
|
||
|
||
* the run starts in the granted project's directory, on the owner's default
|
||
account, on the host sidecar, with the claude harness — whatever the client
|
||
sent (the composer's account / worker / harness / cwd are ignored);
|
||
* the sidecar launches it with a **scope**: ``--permission-mode dontAsk`` and
|
||
Claude Code permission rules that only allow edits under the project dir
|
||
(and /tmp), deny reads of credentials, plus an appended system prompt saying
|
||
whose session this is and what the level allows (see sidecar ``scope``);
|
||
* the model must be one of the guest's allowed families, and the month's
|
||
spend must be under the guest's budget;
|
||
* every message is tagged with its author (:func:`author_tag`), so a shared
|
||
thread shows — and the model knows — who said what.
|
||
|
||
Bash is not confined by the scope: that needs Claude Code's sandbox
|
||
(bubblewrap + socat on the host), which ``GUEST_SANDBOX=1`` turns on.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import datetime
|
||
import os
|
||
import re
|
||
import time
|
||
|
||
from fastapi import HTTPException
|
||
|
||
import accounts as accounts_mod
|
||
from core.i18n import tr
|
||
from projects.catalog import PROJECTS_DIR, PROJECTS_PROMPT_DIR, ROOT_SLUG, project_dir
|
||
from users.caller import OWNER_NAME, Caller
|
||
|
||
GUEST_SANDBOX = os.environ.get("GUEST_SANDBOX", "0") == "1"
|
||
# Reads no guest run gets, whatever the project (Claude Code Read rules; they
|
||
# also cover cat/head/sed… in Bash).
|
||
DENY_READ = (
|
||
"~/.ssh/**", "~/.gnupg/**", "~/.aws/**",
|
||
"~/.claude/.credentials.json", "~/.claude/projects/**",
|
||
"~/.claude-work/**", "~/.claude-guests/**", "~/.config/**",
|
||
"~/homelab/.env*", "~/homelab/services/**/.env*", "~/homelab/data/**",
|
||
)
|
||
|
||
_FORGED_TAG_RE = re.compile(r"<\s*ai-agent-from", re.IGNORECASE)
|
||
_TAG_RE = re.compile(
|
||
r'^<ai-agent-from user="([^"]*)" name="([^"]*)" role="([^"]*)"\s*/>\s*\n?')
|
||
|
||
|
||
def _attr(s: str) -> str:
|
||
return (s or "").replace('"', "'").replace("\n", " ").strip()[:80]
|
||
|
||
|
||
def author_tag(caller: Caller) -> str:
|
||
return (f'<ai-agent-from user="{_attr(caller.id)}" name="{_attr(caller.name)}" '
|
||
f'role="{caller.role}"/>')
|
||
|
||
|
||
def tag_prompt(caller: Caller, prompt: str) -> str:
|
||
"""``prompt`` headed by its author's tag. A guest's own text can't carry
|
||
one: a line of theirs saying ``<ai-agent-from user="owner" …/>`` would
|
||
read to the model as the owner speaking."""
|
||
if not caller.is_owner:
|
||
prompt = _FORGED_TAG_RE.sub("‹ai-agent-from", prompt)
|
||
return f"{author_tag(caller)}\n{prompt}"
|
||
|
||
|
||
def split_author(text: str) -> tuple[dict | None, str]:
|
||
"""``(author, text without the tag)`` — the parser's half of the tag."""
|
||
m = _TAG_RE.match(text or "")
|
||
if not m:
|
||
return None, text
|
||
return {"id": m.group(1), "name": m.group(2), "role": m.group(3)}, text[m.end():]
|
||
|
||
|
||
def language_line(caller: Caller) -> str | None:
|
||
"""The system-prompt line about the guest's language, if not English:
|
||
the installed translation's ``promptLine`` (``translation-<lang>``; the
|
||
rest of the system prompt stays English: it's for Claude)."""
|
||
from core.i18n import prompt_line
|
||
return prompt_line(caller.lang, caller.name)
|
||
|
||
|
||
def project_cwd(slug: str) -> str:
|
||
"""The host path a guest run starts in (``~/projects/<slug>``)."""
|
||
return f"{PROJECTS_PROMPT_DIR}/{slug}"
|
||
|
||
|
||
# ── New project: the ``new-project`` live plugin's composer mode ────────────
|
||
# The plugin (ai-agent-plugins/plugins/new-project) owns the form, the policy,
|
||
# the quota and the scaffold; the core keeps the spawn: the run starts in an
|
||
# empty staging dir (a dot-dir, so the projects catalog skips it) and the
|
||
# plugin moves the session into the project once it exists.
|
||
NEW_PROJECT_MODE = "new-project"
|
||
STAGING_DIR = ".new-project"
|
||
|
||
|
||
def new_project_mode(deps, caller: Caller) -> dict | None:
|
||
"""The ``new-project`` plugin's composer mode for ``caller`` (``{allowed,
|
||
reason, remaining, bucket, domain, stagingNote, …}``) — None when the
|
||
plugin isn't installed, enabled or granted to them."""
|
||
from plugins import waiting
|
||
try:
|
||
modes = waiting.composer_modes_for(deps, caller)
|
||
except Exception:
|
||
return None
|
||
return next((m for m in modes if m.get("id") == NEW_PROJECT_MODE), None)
|
||
|
||
|
||
def new_project_access(deps, caller: Caller, mode: dict | None = None) -> dict | None:
|
||
"""``/api/me``'s ``newProjects`` (``{allowed, reason, remaining, bucket,
|
||
domain}``), read off the plugin's mode — None without one."""
|
||
m = mode if mode is not None else new_project_mode(deps, caller)
|
||
if not m:
|
||
return None
|
||
from users import domains as user_domains
|
||
return {"allowed": bool(m.get("allowed")), "reason": m.get("reason") or None,
|
||
"remaining": m.get("remaining"), "bucket": m.get("bucket") or None,
|
||
"domain": m.get("domain") or user_domains.default_domain(deps)}
|
||
|
||
|
||
def new_project_line(deps, caller: Caller) -> str:
|
||
"""A guest run's system-prompt line about starting projects."""
|
||
a = new_project_access(deps, caller)
|
||
if a is None:
|
||
return ("- They can't start new projects: if they ask for one, say "
|
||
f"{OWNER_NAME} can enable it for them.")
|
||
if a["allowed"]:
|
||
left = f" ({a['remaining']} left)" if a.get("remaining") is not None else ""
|
||
return (f"- They may start new projects{left}: when they ask for one, follow "
|
||
"the `shared:new-frontend-project` skill — it opens the *New project* "
|
||
"form; never scaffold or deploy a new project by hand.")
|
||
return f"- They can't start a new project right now: {a['reason']}."
|
||
|
||
|
||
def staging_cwd(uid: str) -> str:
|
||
"""The host directory a guest's New project run starts in — created here
|
||
(the backend mounts the projects dir) so the sidecar finds it."""
|
||
d = PROJECTS_DIR / STAGING_DIR / uid
|
||
if not d.is_dir():
|
||
d.mkdir(parents=True, exist_ok=True)
|
||
st = PROJECTS_DIR.stat()
|
||
for q in (d.parent, d):
|
||
try: # the container may run as root; runs are the host user
|
||
os.chown(q, st.st_uid, st.st_gid)
|
||
except OSError:
|
||
pass
|
||
return f"{PROJECTS_PROMPT_DIR}/{STAGING_DIR}/{uid}"
|
||
|
||
|
||
def staging_note(caller: Caller, mode: dict | None = None) -> str:
|
||
"""What a New project spawn's prompt gets appended: the plugin's own
|
||
``stagingNote`` when its mode gives one."""
|
||
note = str((mode or {}).get("stagingNote") or "").strip()
|
||
if note:
|
||
return "\n\n---\n" + note
|
||
who = "they" if not caller.is_owner else "you"
|
||
return ("\n\n---\n**New project.** This conversation starts a new project from one of "
|
||
f"{OWNER_NAME}'s templates. Follow the `new-frontend-project` skill"
|
||
+ ("" if caller.is_owner else " (`shared:new-frontend-project`)")
|
||
+ ": read the request, then open the *New project* form with your best "
|
||
"guesses and end your turn — the app creates the project when "
|
||
f"{who} submit it and this conversation carries on inside it.")
|
||
|
||
|
||
def staging_scope(caller: Caller, skills: list[str] | tuple, new_projects: str,
|
||
deps=None) -> dict:
|
||
"""The scope of a guest's *New project* run: no project yet, so nothing to
|
||
write but /tmp — the ``new-project`` plugin moves the session into the
|
||
project once it exists, with that project's scope. It gets the guest's
|
||
tool proxy (their live plugins, ``new-project``'s skill among them)."""
|
||
lines = [
|
||
"## Who you are working for",
|
||
f"This session was started through {OWNER_NAME}'s ai-agent by a **guest**: "
|
||
f"{caller.name}" + (f" <{caller.email}>" if caller.email else "") + ".",
|
||
"It starts a **new project** for them: there is no project yet, so don't "
|
||
"write anywhere but /tmp, and don't read other projects, the homelab "
|
||
"repo, `~/.claude`, credentials or other conversations.",
|
||
"",
|
||
new_projects,
|
||
"- Questions for them go through `ask-form` / `notify ask` — those reach "
|
||
f"**them**, not {OWNER_NAME}.",
|
||
"- Messages start with an `<ai-agent-from …/>` tag naming who wrote them; "
|
||
"`role=\"app\"` turns come from the app itself (the project was made, "
|
||
"an approval came back…).",
|
||
]
|
||
tools = tool_scope(caller, deps=deps) if deps is not None else None
|
||
if tools:
|
||
skills = [*tools["skills"], *(s for s in skills if s not in tools["skills"])]
|
||
if skills:
|
||
names = ", ".join(f"`shared:{r.rsplit('/', 1)[-1].lstrip('@')}`" for r in skills)
|
||
lines.append(f"- {OWNER_NAME} shares these skills with guests: {names}.")
|
||
if language_line(caller):
|
||
lines.append(language_line(caller))
|
||
out = {"writeDirs": ["/tmp"], "denyRead": list(DENY_READ),
|
||
"systemPrompt": "\n".join(lines), "remoteControl": False,
|
||
"sandbox": GUEST_SANDBOX, "gitAuthor": git_author(caller),
|
||
"git": {"user": caller.id, "email": caller.email or "", "push": []}}
|
||
if skills:
|
||
out["skills"] = list(skills)
|
||
if tools:
|
||
out["tools"] = {"url": tools["url"], "token": tools["token"]}
|
||
return out
|
||
|
||
|
||
# A guest with no project they can chat in still gets to talk to Claude: their
|
||
# run starts in a private folder of theirs (``~/projects/.guest-scratch/<uid>``),
|
||
# the only place it may write besides /tmp, and the composer sends it with the
|
||
# "no changes" guideline instead of the Changes chip.
|
||
SCRATCH_DIR = ".guest-scratch"
|
||
|
||
|
||
def chat_projects(caller: Caller) -> list[str]:
|
||
"""The granted projects ``caller`` may start a run in (``chat`` or more)."""
|
||
return [s for s in caller.projects if s != ROOT_SLUG and caller.can(s, "chat")
|
||
and project_dir(s) is not None]
|
||
|
||
|
||
def is_scratch_spawn(caller: Caller, projects: list[str] | None) -> bool:
|
||
"""A guest spawn with no project because they have none to pick: the
|
||
*No project* run (:func:`scratch_scope`). Holding a chat project, a
|
||
project-less spawn is still the composer's missing pick (400)."""
|
||
return (not caller.is_owner and not any(projects or ())
|
||
and not chat_projects(caller))
|
||
|
||
|
||
def scratch_cwd(uid: str) -> str:
|
||
"""The host directory a guest's *No project* run starts in — created here
|
||
(the backend mounts the projects dir) so the sidecar finds it."""
|
||
d = PROJECTS_DIR / SCRATCH_DIR / uid
|
||
if not d.is_dir():
|
||
d.mkdir(parents=True, exist_ok=True)
|
||
st = PROJECTS_DIR.stat()
|
||
for q in (d.parent, d):
|
||
try: # the container may run as root; runs are the host user
|
||
os.chown(q, st.st_uid, st.st_gid)
|
||
except OSError:
|
||
pass
|
||
return f"{PROJECTS_PROMPT_DIR}/{SCRATCH_DIR}/{uid}"
|
||
|
||
|
||
def scratch_scope(caller: Caller, skills: list[str] | tuple = (),
|
||
new_projects: str | None = None, bash: bool = True,
|
||
deps=None) -> dict:
|
||
"""The scope of a guest's *No project* run: their scratch folder (and
|
||
/tmp) to write in, nothing else — no project, no git pushes. With
|
||
``bash`` off (the owner's per-guest switch, ``users.store.scratch_bash``)
|
||
the run gets no shell either: ``noBash`` makes the sidecar drop Bash and
|
||
Monitor, and with them everything that is a command — the shared skills,
|
||
the plugin tools, the ``ai-agent`` CLI, ``notify`` and ``ask-form``."""
|
||
cwd = scratch_cwd(caller.id)
|
||
lines = [
|
||
"## Who you are working for",
|
||
f"This session was started through {OWNER_NAME}'s ai-agent by a **guest**: "
|
||
f"{caller.name}" + (f" <{caller.email}>" if caller.email else "") + ".",
|
||
f"They have **no project** here: this is a conversation — answer their "
|
||
f"questions, explain, research, draft. `{cwd}` is their private scratch "
|
||
"folder, the only place (with /tmp) you may write — a file they ask for "
|
||
"goes there. Don't read or change projects, the homelab repo, `~/.claude`, "
|
||
"credentials or other conversations.",
|
||
"",
|
||
"- Nothing here is committed, pushed or deployed: to work on a project of "
|
||
f"their own they need {OWNER_NAME} to grant them one"
|
||
+ (" — or to start one (below)." if new_projects else "."),
|
||
]
|
||
if bash:
|
||
lines.append(
|
||
"- Questions for them go through `ask-form` / `notify ask` — those reach "
|
||
f"**them**, not {OWNER_NAME}. End your final message with the ```notify block (the closing push) as usual.")
|
||
else:
|
||
lines.append(
|
||
"- This conversation has **no shell**: you can't run commands, so no "
|
||
"`notify-done`, `notify ask`, `ask-form` or skill CLI — ignore any "
|
||
"instruction to run one, and don't try another way to. Ask your questions "
|
||
"and give your results in your reply; you can still read, search the web "
|
||
"and write files in the scratch folder. The closing push needs no shell: "
|
||
"end your final message with the ```notify block as usual.")
|
||
lines.append(
|
||
"- Messages start with an `<ai-agent-from …/>` tag naming who wrote them; "
|
||
"`role=\"app\"` turns come from the app itself.")
|
||
tools = tool_scope(caller, deps=deps) if bash else None
|
||
if not bash:
|
||
skills = []
|
||
if new_projects and "shared:new-frontend-project" in new_projects:
|
||
# Opening the New project form is a command too.
|
||
new_projects = ("- They may start a new project of their own with the app's "
|
||
"**+ New project** button — this conversation can't open "
|
||
"that form for them.")
|
||
if tools:
|
||
skills = [*tools["skills"], *(s for s in skills if s not in tools["skills"])]
|
||
lines.append(TOOLS_LINE.format(names=", ".join(
|
||
f"`shared:{r.split('/')[-1].lstrip('@')}`" for r in tools["skills"])))
|
||
if caller.cli and bash:
|
||
skills = [CLI_SKILL, *skills]
|
||
lines.append(CLI_LINE.format(name=caller.name))
|
||
if skills:
|
||
names = ", ".join(f"`shared:{r.rsplit('/', 1)[-1].lstrip('@')}`" for r in skills)
|
||
lines.append(f"- {OWNER_NAME} shares these skills with guests: {names}.")
|
||
if new_projects:
|
||
lines.append(new_projects)
|
||
if language_line(caller):
|
||
lines.append(language_line(caller))
|
||
out = {"writeDirs": [cwd, "/tmp"], "denyRead": list(DENY_READ),
|
||
"systemPrompt": "\n".join(lines), "remoteControl": False,
|
||
"sandbox": GUEST_SANDBOX, "gitAuthor": git_author(caller),
|
||
"git": {"user": caller.id, "email": caller.email or "", "push": []}}
|
||
if not bash:
|
||
out["noBash"] = True
|
||
if skills:
|
||
out["skills"] = list(skills)
|
||
if tools:
|
||
out["tools"] = {"url": tools["url"], "token": tools["token"]}
|
||
return out
|
||
|
||
|
||
def check_projects(caller: Caller, projects: list[str] | None, need: str = "chat") -> list[str]:
|
||
"""The granted projects a guest spawn works in, the first being the one it
|
||
runs in (its cwd) — the composer's mandatory project select; the rest are
|
||
the project chips they also turned on. Each needs ``need`` access."""
|
||
slugs = list(dict.fromkeys(p for p in (projects or []) if p))
|
||
if not slugs:
|
||
raise HTTPException(400, {"message": tr(caller.lang, "pick one of your projects"),
|
||
"kind": "guest_project"})
|
||
for slug in slugs:
|
||
if slug == ROOT_SLUG or not caller.can(slug, need) or project_dir(slug) is None:
|
||
raise HTTPException(403, {"message": tr(caller.lang, "no {level} access to "
|
||
"'{project}'", level=need, project=slug),
|
||
"kind": "guest_project"})
|
||
return slugs
|
||
|
||
|
||
def check_project(caller: Caller, projects: list[str] | None, need: str = "chat") -> str:
|
||
"""The one granted project a guest run starts in."""
|
||
slugs = check_projects(caller, projects, need)
|
||
if len(slugs) != 1:
|
||
raise HTTPException(400, {"message": tr(caller.lang,
|
||
"pick exactly one of your projects"),
|
||
"kind": "guest_project"})
|
||
return slugs[0]
|
||
|
||
|
||
def extra_projects(caller: Caller, projects: list[str] | None) -> list[str]:
|
||
"""A conversation's projects past its first that ``caller`` still holds
|
||
``chat`` on — the extra write scope a resumed/forked guest run keeps."""
|
||
return [p for p in list(dict.fromkeys(projects or []))[1:]
|
||
if p and p != ROOT_SLUG and caller.can(p, "chat") and project_dir(p) is not None]
|
||
|
||
|
||
def allowed_models(caller: Caller) -> list[str]:
|
||
"""The model keys a guest may run on the owner's account / plans: their own
|
||
list (Settings → Users; none ⇒ Sonnet, as always) within the guest pool
|
||
(Settings → Models' *Guests may use* — models/presets.py)."""
|
||
from models import presets as presets_mod
|
||
pool = presets_mod.guest_pool()
|
||
mine = [m.lower() for m in (caller.models or ())] or ["sonnet"]
|
||
return [m for m in dict.fromkeys(mine) if m in {p.lower() for p in pool}]
|
||
|
||
|
||
def check_model(caller: Caller, model: str | None) -> str:
|
||
"""An allowed model: an alias (``sonnet``), a pinned id of an allowed
|
||
Claude family (``claude-sonnet-4-5-…``) or another model's key / id
|
||
(``ggml-org/qwen3.8-27b``, ``gemini-4-neon``). Unset ⇒ the first allowed
|
||
Claude one (a run with no model picked is a Claude Code run)."""
|
||
from models import catalog, presets as presets_mod
|
||
allowed = allowed_models(caller)
|
||
if not model:
|
||
claude = [a for a in allowed if a in catalog.FAMILIES]
|
||
if claude:
|
||
return claude[0]
|
||
raise HTTPException(403, {"message": tr(caller.lang, "no model is enabled for you"),
|
||
"kind": "guest_model", "allowed": allowed})
|
||
m = model.lower()
|
||
key = (presets_mod.find_key(catalog.list_models(), model) or "").lower()
|
||
if m in allowed or key in allowed or any(
|
||
re.search(rf"(^|-){re.escape(a)}(-|$)", m) for a in allowed
|
||
if a in catalog.FAMILIES):
|
||
return model
|
||
raise HTTPException(403, {"message": tr(caller.lang, "model '{model}' isn't enabled "
|
||
"for you", model=model),
|
||
"kind": "guest_model", "allowed": allowed})
|
||
|
||
|
||
def model_route(caller: Caller, model: str | None) -> tuple[str, str | None]:
|
||
"""The harness a guest's pick runs on — its preset's, never the client's —
|
||
and the ``--model`` argument for it: ``("claude", model)`` for a Claude
|
||
model (or none: checked later, per the account it bills), else the
|
||
checked model's preset harness and entry (``("pi", "ggml-org/…")``)."""
|
||
from models import catalog, presets as presets_mod
|
||
if not model:
|
||
return "claude", None
|
||
models = catalog.list_models()
|
||
key = presets_mod.find_key(models, model)
|
||
hit = next((x for x in models if presets_mod.key_of(x) == key), None) if key else None
|
||
if not hit or (hit.get("harness") or "claude") == "claude":
|
||
return "claude", model
|
||
check_model(caller, model)
|
||
preset = presets_mod.presets(models).get(key) or {}
|
||
entry = presets_mod.entry_for(models, key, preset) or hit
|
||
return entry.get("harness") or "claude", entry.get("alias") or entry.get("id")
|
||
|
||
|
||
def run_other_harness(deps, caller: Caller, send, scope: dict | None = None,
|
||
sid: str | None = None) -> dict:
|
||
"""A guest's run on a model outside Claude Code (pi on the EVOX2 or
|
||
OpenRouter, agy on the owner's Google plan): no login of theirs to try,
|
||
the same live-run cap and month budget as the owner's account (a local
|
||
run costs $0; an agy one is priced at Google's list price). ``send()``
|
||
launches it."""
|
||
check_live_runs(deps, caller, sid)
|
||
check_budget(deps, caller)
|
||
if scope is not None:
|
||
scope.pop("maxBudgetUsd", None) # a claude flag
|
||
out = send()
|
||
return {**out, "account": out.get("account") or accounts_mod.DEFAULT}
|
||
|
||
|
||
def spend_by_user(cards: list[dict]) -> dict[str, dict]:
|
||
"""What each guest's conversations cost: ``{uid: {"month", "total",
|
||
"conversations", "ownMonth", "ownTotal", "ownConversations"}}``.
|
||
|
||
``month`` / ``total`` are what ran on the **owner's** account — ``month``
|
||
is what the budget is checked against (the conversations that ran this
|
||
calendar month, UTC); the ``own*`` figures are the conversations billed to
|
||
the guest's own Claude login (``guest-<uid>``): an estimate at list price,
|
||
never capped. A conversation is billed to the account of its latest run
|
||
(``meta.account`` — a fallback mid-thread moves the whole conversation).
|
||
``conversations`` counts both.
|
||
|
||
A conversation that ran on one of the guest's own computers (it has a
|
||
worker) is metered call by call by the Claude proxy instead
|
||
(``claudeproxy/limits.LEDGER``), which also sees calls that never make a
|
||
transcript here — so it stays out of ``month`` / ``total`` and is only
|
||
estimated in ``machineMonth`` / ``machineTotal``; ``with_computers`` adds
|
||
the ledger's month."""
|
||
start = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-01")
|
||
out: dict[str, dict] = {}
|
||
for c in cards:
|
||
meta = c.get("meta") or {}
|
||
uid = meta.get("owner")
|
||
if not uid:
|
||
continue
|
||
s = out.setdefault(uid, _zero_spend())
|
||
own = _billed_own(meta, uid)
|
||
machine = not own and bool(meta.get("workerSource") or meta.get("worker"))
|
||
key = "own" if own else "machine" if machine else ""
|
||
cost = float(c.get("cost") or 0)
|
||
s[f"{key}Total" if key else "total"] += cost
|
||
s["conversations"] += 1
|
||
if own:
|
||
s["ownConversations"] += 1
|
||
if (c.get("endedAt") or c.get("startedAt") or "") >= start:
|
||
s[f"{key}Month" if key else "month"] += cost
|
||
return out
|
||
|
||
|
||
def _billed_own(meta: dict, uid: str) -> bool:
|
||
"""A conversation billed to guest ``uid``'s own Claude — not one the
|
||
proxy caught billing the host instead (``ownLoginLeak``,
|
||
claudeproxy/routes._own_login_leak): a later turn's stamp can say
|
||
``guest-<uid>`` again after its calls already went through the proxy."""
|
||
return accounts_mod.guest_of(meta.get("account")) == uid and not meta.get("ownLoginLeak")
|
||
|
||
|
||
def _zero_spend() -> dict:
|
||
return {"month": 0.0, "total": 0.0, "conversations": 0, "ownMonth": 0.0,
|
||
"ownTotal": 0.0, "ownConversations": 0, "machineMonth": 0.0,
|
||
"machineTotal": 0.0}
|
||
|
||
|
||
def month_credit(deps, uid: str, month: str | None = None) -> float:
|
||
"""What the owner took off guest ``uid``'s month (``users.json``
|
||
``budgetCredits[<YYYY-MM>].usd``) — spend that wasn't theirs to carry:
|
||
Akira's 2026-11 runs routed to his own Pro that his computer still sent
|
||
through the proxy ($273.64, homelab ``data/log/2026-11-10-akira-budget-
|
||
proxy-leak.md``). Set with ``PUT /api/users/{uid}`` ``budgetCredit``."""
|
||
month = month or datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m")
|
||
u = (deps.users.get(uid) if deps is not None else None) or {}
|
||
c = (u.get("budgetCredits") or {}).get(month) or {}
|
||
try:
|
||
return max(0.0, float(c.get("usd") or 0))
|
||
except (TypeError, ValueError):
|
||
return 0.0
|
||
|
||
|
||
def with_computers(spend: dict[str, dict], uids, deps=None) -> dict[str, dict]:
|
||
"""``spend_by_user`` plus what each guest's computers spent this month
|
||
through the Claude proxy (its ledger) — into ``month`` (the budget's
|
||
figure) and ``computersMonth`` — less the owner's credit for the month
|
||
(``creditMonth``, :func:`month_credit`)."""
|
||
from claudeproxy import limits
|
||
for uid in uids:
|
||
got = limits.LEDGER.spent("guest", uid)
|
||
s = spend.setdefault(uid, _zero_spend())
|
||
s["computersMonth"] = got
|
||
credit = month_credit(deps, uid)
|
||
s["creditMonth"] = credit
|
||
s["month"] = max(0.0, s.get("month", 0.0) + got - credit)
|
||
return spend
|
||
|
||
|
||
_month_cache: dict[str, tuple[float, float]] = {}
|
||
|
||
|
||
def month_spend_all(deps, uid: str, max_age: float = 30.0) -> float:
|
||
"""``month_spend`` over every card, the cards' part cached ``max_age`` s
|
||
per guest — the Claude proxy asks before each call of a guest's computer.
|
||
The ledger's part is always live."""
|
||
from claudeproxy import limits
|
||
hit = _month_cache.get(uid)
|
||
if hit and time.time() - hit[0] < max_age:
|
||
lab = hit[1]
|
||
else:
|
||
from conversations.catalog import _conversation_cards
|
||
lab = spend_by_user(list(_conversation_cards(deps, False))).get(uid, {}).get("month", 0.0)
|
||
_month_cache[uid] = (time.time(), lab)
|
||
return max(0.0, lab + limits.LEDGER.spent("guest", uid) - month_credit(deps, uid))
|
||
|
||
|
||
def activity_of(cards: list[dict], uid: str, project_of=None, *, days: int = 30,
|
||
limit: int = 50, now: datetime.datetime | None = None) -> dict:
|
||
"""One guest's conversations for their page in Settings → Users: spend per
|
||
UTC day over the last ``days``, spend per project this month, their
|
||
latest ``limit`` conversations, and how many started in the last 7 days.
|
||
|
||
Costs are attributed like :func:`spend_by_user` — the whole conversation
|
||
to the day it last ran — with ``usd`` on the owner's account and
|
||
``ownUsd`` on their own Claude login. ``project_of(card)`` names the
|
||
project a conversation ran in (the guest's pick), else the card's first."""
|
||
now = now or datetime.datetime.now(datetime.timezone.utc)
|
||
first = now.date() - datetime.timedelta(days=days - 1)
|
||
daily = {d: {"date": d, "usd": 0.0, "ownUsd": 0.0} for d in
|
||
((first + datetime.timedelta(days=i)).isoformat() for i in range(days))}
|
||
month = now.strftime("%Y-%m-01")
|
||
week = (now - datetime.timedelta(days=7)).strftime("%Y-%m-%dT%H:%M:%S")
|
||
by_project: dict[str, dict] = {}
|
||
mine: list[tuple[str, dict, str | None, bool]] = []
|
||
this_week = 0
|
||
for c in cards:
|
||
meta = c.get("meta") or {}
|
||
if meta.get("owner") != uid:
|
||
continue
|
||
own = _billed_own(meta, uid)
|
||
cost = float(c.get("cost") or 0)
|
||
at = c.get("endedAt") or c.get("startedAt") or ""
|
||
project = ((project_of(c) if project_of else None)
|
||
or (meta.get("projects") or [None])[0])
|
||
day = daily.get(at[:10])
|
||
if day:
|
||
day["ownUsd" if own else "usd"] += cost
|
||
if at >= month:
|
||
p = by_project.setdefault(project or "", {
|
||
"project": project, "usd": 0.0, "ownUsd": 0.0, "conversations": 0})
|
||
p["ownUsd" if own else "usd"] += cost
|
||
p["conversations"] += 1
|
||
if (c.get("startedAt") or "") >= week:
|
||
this_week += 1
|
||
mine.append((at, c, project, own))
|
||
mine.sort(key=lambda r: r[0], reverse=True)
|
||
for d in daily.values():
|
||
d["usd"], d["ownUsd"] = round(d["usd"], 4), round(d["ownUsd"], 4)
|
||
for p in by_project.values():
|
||
p["usd"], p["ownUsd"] = round(p["usd"], 4), round(p["ownUsd"], 4)
|
||
return {
|
||
"dailySpend": list(daily.values()),
|
||
"spendByProject": sorted(by_project.values(),
|
||
key=lambda p: -(p["usd"] + p["ownUsd"])),
|
||
"recentConversations": [
|
||
{"id": c.get("id"), "sessionId": c.get("sessionId"), "title": c.get("title"),
|
||
"project": project, "costUsd": round(float(c.get("cost") or 0), 4),
|
||
"at": at or None, "startedAt": c.get("startedAt"),
|
||
"state": (c.get("meta") or {}).get("state"), "own": own}
|
||
for at, c, project, own in mine[:limit]],
|
||
"conversations": len(mine),
|
||
"conversationsThisWeek": this_week,
|
||
}
|
||
|
||
|
||
def month_spend(deps, uid: str, cards: list[dict]) -> float:
|
||
"""This month on the owner's account: the lab's conversations and what
|
||
the guest's computers spent through the proxy."""
|
||
return with_computers(spend_by_user(cards), [uid], deps).get(uid, {}).get("month", 0.0)
|
||
|
||
|
||
def check_budget(deps, caller: Caller) -> float | None:
|
||
"""What is left of the guest's month on the owner's account (None = no
|
||
budget); 402 once it is spent."""
|
||
budget = caller.budget_usd
|
||
if budget is None:
|
||
return None
|
||
from conversations.catalog import _conversation_cards
|
||
spent = month_spend(deps, caller.id, list(_conversation_cards(deps, False)))
|
||
if spent >= budget:
|
||
raise HTTPException(402, {
|
||
"message": tr(caller.lang, "monthly budget reached (${spent} of ${budget})",
|
||
spent=f"{spent:.2f}", budget=f"{budget:.0f}"),
|
||
"kind": "guest_budget", "spentUsd": round(spent, 2),
|
||
"budgetUsd": budget})
|
||
return budget - spent
|
||
|
||
|
||
# Live runs one guest may have at once (spawns, resumes and forks together).
|
||
GUEST_MAX_LIVE_RUNS = int(os.environ.get("GUEST_MAX_LIVE_RUNS", "3"))
|
||
|
||
|
||
def check_live_runs(deps, caller: Caller, sid: str | None = None) -> None:
|
||
"""429 when ``caller`` already has GUEST_MAX_LIVE_RUNS runs going (a turn
|
||
into one of them, ``sid``, doesn't add one). Unknown liveness lets it
|
||
through: the launch itself will say if the runner is down."""
|
||
from runs.sidecar_client import _sidecar_live_sids
|
||
live = _sidecar_live_sids(deps)
|
||
if not live:
|
||
return
|
||
mine = {s for s in live - {sid} if (deps.meta_store.peek(s) or {}).get("runAs") == caller.id}
|
||
if len(mine) >= GUEST_MAX_LIVE_RUNS:
|
||
raise HTTPException(429, {
|
||
"message": tr(caller.lang, "you already have {n} runs going — wait for one "
|
||
"to finish or stop it", n=len(mine)),
|
||
"kind": "guest_live_runs", "max": GUEST_MAX_LIVE_RUNS})
|
||
|
||
|
||
# ── the guest's own Claude login, and the fallback onto the owner's ──────────
|
||
# Why a launch on the guest's own login gives way to the owner's account.
|
||
FALLBACK_KINDS = ("auth", "rate_limit")
|
||
|
||
|
||
def own_connected(deps, caller: Caller) -> bool:
|
||
return bool(((deps.users.get(caller.id) or {}).get("claude") or {}).get("connectedAt"))
|
||
|
||
|
||
def own_account(deps, caller: Caller) -> str | None:
|
||
"""The guest's own login (``guest-<uid>``) when it is connected and usable
|
||
right now — not signed out, not inside its usage-limit hold
|
||
(accounts/health.py). None ⇒ their runs go to the owner's account."""
|
||
if not own_connected(deps, caller):
|
||
return None
|
||
acct = accounts_mod.guest_account(caller.id)
|
||
row = deps.account_health.snapshot.get(acct) or {}
|
||
if row.get("status") == "signed_out" or row.get("limited"):
|
||
return None
|
||
return acct
|
||
|
||
|
||
def prefers_host(deps, caller: Caller) -> bool:
|
||
"""The guest picked the owner's account on their composer's account chip
|
||
(``PUT /api/me/claude/bill``): their runs skip their own login."""
|
||
return ((deps.users.get(caller.id) or {}).get("claude") or {}).get("bill") == "host"
|
||
|
||
|
||
def fallback_model(caller: Caller, model: str | None) -> str:
|
||
"""The model a fallback onto the owner's account runs: the one asked for
|
||
when the guest may use it there, else their first allowed one (on their
|
||
own plan they may pick any model — the owner's still decides on his)."""
|
||
try:
|
||
return check_model(caller, model)
|
||
except HTTPException:
|
||
return check_model(caller, None)
|
||
|
||
|
||
def run_as_guest(deps, caller: Caller, send, model: str | None,
|
||
scope: dict | None = None, sid: str | None = None) -> dict:
|
||
"""Launch a guest's run: on their own login when it is usable (any model,
|
||
no budget), else — or when that launch is refused as signed out / at its
|
||
limit — on the owner's account, under the budget and allowed models.
|
||
``send(account, model)`` does the launch and returns its result.
|
||
|
||
On the owner's account the run's ``scope`` (the dict ``send`` launches
|
||
with) also caps that one run at what is left of the month
|
||
(``maxBudgetUsd`` → ``--max-budget-usd``): the budget used to be checked
|
||
at launch only, so one runaway run could spend the month and then some.
|
||
At most GUEST_MAX_LIVE_RUNS runs at a time (``sid``: the session a turn
|
||
goes into).
|
||
|
||
A guest who picked the owner's account on their account chip
|
||
(``prefers_host``) goes straight there — same budget and models as a
|
||
fallback."""
|
||
check_live_runs(deps, caller, sid)
|
||
own = None if prefers_host(deps, caller) else own_account(deps, caller)
|
||
if own:
|
||
if scope is not None:
|
||
scope.pop("maxBudgetUsd", None)
|
||
try:
|
||
return {**send(own, model), "account": own}
|
||
except HTTPException as e:
|
||
d = e.detail if isinstance(e.detail, dict) else {}
|
||
if d.get("kind") not in FALLBACK_KINDS:
|
||
raise
|
||
left = check_budget(deps, caller)
|
||
if scope is not None and left is not None:
|
||
scope["maxBudgetUsd"] = round(max(left, 0.01), 2)
|
||
m = fallback_model(caller, model) if own_connected(deps, caller) \
|
||
else check_model(caller, model)
|
||
return {**send(accounts_mod.DEFAULT, m), "account": accounts_mod.DEFAULT}
|
||
|
||
|
||
def shared_skills(deps) -> list[str]:
|
||
"""The owner's skills every guest run gets (Settings → Skills → *Share
|
||
with guests*), as ``name`` / ``<project>/<name>`` refs."""
|
||
return deps.users.defaults()["sharedSkills"]
|
||
|
||
|
||
def git_author(caller: Caller) -> dict:
|
||
"""The git author a guest's commits carry (scope ``gitAuthor`` → the run's
|
||
``GIT_AUTHOR_NAME``/``GIT_AUTHOR_EMAIL``). The address is the one their
|
||
Gitea account was made with (``tea-cli ensure-user``), so Gitea links the
|
||
commits to it; the committer stays the host's identity."""
|
||
return {"name": caller.name or caller.id,
|
||
"email": caller.email or f"{caller.id}@noreply.git.gabvdl.xyz"}
|
||
|
||
|
||
# A guest with the CLI switch on (users/cli.py): the skill their runs get —
|
||
# the sidecar's built-in ``@<name>`` ref, ``cli/skills/ai-agent`` in this
|
||
# repo — and the system-prompt line that says how it runs.
|
||
CLI_SKILL = "@ai-agent"
|
||
CLI_LINE = (
|
||
"- You can drive the hub with the `ai-agent` CLI, as {name}: start a "
|
||
"conversation of its own for a separate piece of work, continue or read "
|
||
"one of their conversations, wait for its answer. It reaches only their "
|
||
"own conversations and projects. Run it as a plain `ai-agent …` command "
|
||
"on its own — no pipes, `&&`, redirects or variables: the hub runs it "
|
||
"outside this session and hands back its output (that is why the call "
|
||
"shows as blocked). The `shared:ai-agent` skill lists the commands; "
|
||
"with the Cron jobs plugin on for them, `ai-agent plugin cron-jobs add …` "
|
||
"(the `shared:cron-jobs` skill) sets up a job that runs on its own on a "
|
||
"schedule when they ask for something recurring.")
|
||
|
||
|
||
# A guest's project run with the Approvals plugin on (managed, on for guests by
|
||
# default — ai-agent-plugins/plugins/approvals): a step only the owner can take
|
||
# goes to him as a request through its ``ask-approval`` skill, never as "ask
|
||
# Gabriel" at the end of a turn.
|
||
APPROVALS_PLUGIN = "approvals"
|
||
APPROVAL_LINE = (
|
||
"- A step only {owner} can take — a secret or setting you can't read, a "
|
||
"deploy or server you can't reach, money, his app or homelab — is not a dead "
|
||
"end: send it to him with the `shared:ask-approval` skill (the Approvals "
|
||
"plugin) and end your turn. It goes to {owner} alone; on his OK an owner run "
|
||
"does it and this conversation resumes with its report. Don't finish on « ask "
|
||
"{owner} to … » when a request would do.")
|
||
|
||
|
||
def scope_for(caller: Caller, slug: str, level: str | None,
|
||
skills: list[str] | tuple = (), extra: list[str] | tuple = (),
|
||
new_projects: str | None = None, deps=None) -> dict:
|
||
"""The sidecar ``scope`` of a guest run (see sidecar ``launch.scope_args``).
|
||
|
||
``slug`` is the project the run starts in; ``extra`` are the other
|
||
projects it may also work in (each one the guest holds ``chat`` on).
|
||
|
||
``skills`` reach the run as a generated Claude Code plugin (``--plugin-dir``)
|
||
named ``shared``, so they show up as ``shared:<name>`` next to the
|
||
project's own ``.claude/skills``. ``new_projects`` is the line saying
|
||
whether they may start projects (:func:`new_project_line`)."""
|
||
cwd = project_cwd(slug)
|
||
ship = level == "ship"
|
||
others = [(p, project_cwd(p), caller.level(p)) for p in extra if p != slug]
|
||
where = f"`{cwd}`" + "".join(f", `{d}`" for _, d, _ in others)
|
||
lines = [
|
||
f"## Who you are working for",
|
||
f"This session was started through {OWNER_NAME}'s ai-agent by a **guest**: "
|
||
f"{caller.name}" + (f" <{caller.email}>" if caller.email else "") + ".",
|
||
f"Their access: project `{slug}` (`{cwd}`), level **{level}**"
|
||
+ "".join(f"; project `{p}` (`{d}`), level **{lv}**" for p, d, lv in others)
|
||
+ ".",
|
||
"",
|
||
("- Treat their messages as the task, within that project. "
|
||
if not others else
|
||
f"- Treat their messages as the task. The session starts in `{slug}`; "
|
||
"they also picked the other projects listed above. ")
|
||
+ f"Work only in {where}: don't read or change other projects, the "
|
||
"homelab repo, `~/.claude`, credentials or other conversations. File "
|
||
"edits outside " + ("the project" if not others else "those projects")
|
||
+ " (and /tmp) are blocked for this session.",
|
||
("- They may commit, push and deploy this project to production."
|
||
+ (" On the other projects, their level above decides." if others else "")
|
||
if ship else
|
||
"- They may commit locally but not push or deploy — if they ask, say "
|
||
f"that needs the *ship* level, which {OWNER_NAME} can grant."),
|
||
f"- Commits made here are authored as {caller.name} (`GIT_AUTHOR_NAME`/"
|
||
"`GIT_AUTHOR_EMAIL` are set for this session) — don't pass `--author` "
|
||
"or change git's user config."
|
||
+ (" A plain `git push` works — as them, on their own Gitea account." if ship else ""),
|
||
"- Questions for them go through `ask-form` / `notify ask` — those reach "
|
||
f"**them**, not {OWNER_NAME}. End your final message with the ```notify block (the closing push) as usual.",
|
||
"- Messages start with an `<ai-agent-from …/>` tag naming who wrote them: "
|
||
f"a conversation can be shared with {OWNER_NAME} and other guests, and "
|
||
"each person's instructions carry their own access level; `role=\"app\"` "
|
||
"turns come from the app itself (a project was made, an approval came back).",
|
||
]
|
||
tools = tool_scope(caller, deps=deps)
|
||
if tools:
|
||
# Their live plugins' skills (the tools the hub shares with them).
|
||
skills = [*tools["skills"], *(s for s in skills if s not in tools["skills"])]
|
||
lines.append(TOOLS_LINE.format(names=", ".join(
|
||
f"`shared:{r.split('/')[-1].lstrip('@')}`" for r in tools["skills"])))
|
||
if caller.has("plugins.create") and "@create-plugin" not in skills:
|
||
skills = [*skills, "@create-plugin"]
|
||
if caller.cli:
|
||
# Their own edition of the ai-agent skill, ahead of any the owner
|
||
# shares: the plugin keeps the first skill of a name.
|
||
skills = [CLI_SKILL, *skills]
|
||
lines.append(CLI_LINE.format(name=caller.name))
|
||
if any(r.startswith("plugin:") and r.rsplit("/", 1)[-1] == APPROVALS_PLUGIN
|
||
for r in (tools or {}).get("skills") or ()):
|
||
lines.append(APPROVAL_LINE.format(owner=OWNER_NAME))
|
||
if skills:
|
||
names = ", ".join(f"`shared:{r.rsplit('/', 1)[-1].lstrip('@')}`" for r in skills)
|
||
lines.append(f"- {OWNER_NAME} shares these skills with guests: {names}.")
|
||
if GUEST_SANDBOX:
|
||
lines.append(
|
||
"- Shell commands run in a sandbox: this project, /tmp and the package "
|
||
"registries are reachable; other folders, SSH, docker and the lab's "
|
||
"services are not.")
|
||
if new_projects:
|
||
lines.append(new_projects)
|
||
if language_line(caller):
|
||
lines.append(language_line(caller))
|
||
out = {
|
||
"writeDirs": [cwd, *(d for _, d, _ in others), "/tmp"],
|
||
"denyRead": list(DENY_READ),
|
||
"systemPrompt": "\n".join(lines),
|
||
"remoteControl": False,
|
||
"sandbox": GUEST_SANDBOX,
|
||
"gitAuthor": git_author(caller),
|
||
# Pushes go to Gitea as the guest — on the projects they ship only;
|
||
# never with the owner's token (sidecar guest_git.py).
|
||
"git": {"user": caller.id, "email": caller.email or "",
|
||
"push": [p for p in [slug, *(p for p, _, _ in others)]
|
||
if caller.level(p) == "ship"]},
|
||
}
|
||
if skills:
|
||
out["skills"] = list(skills)
|
||
if tools:
|
||
out["tools"] = {"url": tools["url"], "token": tools["token"]}
|
||
return out
|
||
|
||
|
||
# The tools the hub shares with a guest — their live plugins (installed, or
|
||
# owner-managed and granted to them): what their run is told about them.
|
||
TOOLS_LINE = (
|
||
"- Tools the hub shares with them: {names}. They run through the hub's tool "
|
||
"proxy (`AIA_TOOLS_URL` / `AIA_TOOLS_TOKEN` are set for this session) — the keys "
|
||
"stay on the hub; a paid one (Nano Banana images) is billed to its own monthly "
|
||
"budget, the lab's 3D and video jobs, Matomo analytics (their own sites only) "
|
||
"and movie requests (Seerr, within their weekly quota) are free but counted. "
|
||
"Use those skills' scripts; never look for the owner's keys or call "
|
||
"the lab's services directly.")
|
||
TOOLS_URL = (os.environ.get("TOOLS_PROXY_GUEST_URL") or "").rstrip("/")
|
||
|
||
|
||
def tool_scope(caller: Caller, deps=None) -> dict | None:
|
||
"""``{skills, url, token}`` for a guest with live plugins that bring a
|
||
skill (installed or granted) — None otherwise, for the owner, or when the
|
||
hub has no public guest host to reach them on."""
|
||
from toolproxy import access
|
||
p_skills = (deps.plugin_store.live_skill_dirs(caller.id)
|
||
if deps is not None and getattr(deps, "plugin_store", None) else [])
|
||
if caller.is_owner or not p_skills:
|
||
return None
|
||
from users.deliver import GUEST_PUBLIC_URL
|
||
url = TOOLS_URL or (f"{GUEST_PUBLIC_URL}/proxy/tools" if GUEST_PUBLIC_URL else "")
|
||
if not url:
|
||
return None
|
||
skills: list[str] = []
|
||
for p in p_skills:
|
||
if p["ref"] not in skills:
|
||
skills.append(p["ref"])
|
||
return {"skills": skills, "url": url, "token": access.mint(caller.id)}
|
||
|
||
|
||
# ── a run on the guest's own computer (users/computers.py) ───────────────────
|
||
COMPUTER_LINE = (
|
||
"- This run is on {name}'s own computer (\"{machine}\"), started from their "
|
||
"ai-agent portal; they are a guest of the hub's owner. Nothing of the owner's "
|
||
"lab is here: no ~/homelab, no lab skills or services — work with what this "
|
||
"machine has. The conversation is mirrored to the hub, where they read it.")
|
||
|
||
|
||
def computer_prompt(caller: Caller, w: dict) -> str:
|
||
"""The system-prompt lines of a guest's run on their computer."""
|
||
lines = [COMPUTER_LINE.format(name=caller.name or caller.id,
|
||
machine=(w.get("name") or w.get("hostname") or "")[:60])]
|
||
lang = language_line(caller)
|
||
if lang:
|
||
lines.append(lang)
|
||
return "\n".join(lines)
|
||
|
||
|
||
def owns_computer(deps, caller: Caller, wid: str | None) -> bool:
|
||
from workers import guests
|
||
w = deps.worker_store.get(wid) if wid else None
|
||
return bool(w) and guests.owner_of(w) == caller.id
|
||
|
||
|
||
def computer_of(deps, caller: Caller, wid: str | None) -> dict | None:
|
||
"""The caller's own computer ``wid`` (404 for anyone else's)."""
|
||
from workers import guests
|
||
w = deps.worker_store.get(wid) if wid else None
|
||
if not w or guests.owner_of(w) != caller.id:
|
||
raise HTTPException(404, {"message": tr(caller.lang, "no such computer"),
|
||
"kind": "computer_unknown"})
|
||
if w.get("pending"):
|
||
raise HTTPException(409, {"message": tr(caller.lang, "this computer isn't connected yet"),
|
||
"kind": "worker_offline", "worker": wid})
|
||
if w.get("paused"):
|
||
raise HTTPException(409, {"message": tr(caller.lang, "this computer is paused — "
|
||
"switch it back on in Settings → My computers"),
|
||
"kind": "computer_paused", "worker": wid})
|
||
return w
|
||
|
||
|
||
def computer_project(deps, caller: Caller, w: dict, slugs: list[str] | None) -> dict | None:
|
||
"""The project on this computer a run of theirs starts in — the
|
||
composer's project pill on a computer lists the projects the hub deduced
|
||
there (projects/worker_projects.py, ``<folder>@<worker id>``). None: no
|
||
project, the computer's start folder. Anything else — a lab project, a
|
||
project of another machine, one the hub doesn't know — is refused rather
|
||
than run in a folder nobody picked."""
|
||
from projects import worker_projects
|
||
slug = next((s for s in slugs or [] if s), None)
|
||
if not slug:
|
||
return None
|
||
parsed = worker_projects.parse_slug(slug)
|
||
p = worker_projects.registry(deps).projects.get(slug) if parsed else None
|
||
if not p or p.get("worker") != w["id"] or not p.get("path"):
|
||
raise HTTPException(400, {"message": tr(caller.lang, "that project isn't on this computer"),
|
||
"kind": "guest_project"})
|
||
return {"slug": slug, "path": p["path"]}
|
||
|
||
|
||
def session_computer_project(deps, caller: Caller, w: dict, sid: str) -> str | None:
|
||
"""The folder of the computer project a session there was started in
|
||
(its stamped ``projects``) — None when it started in the start folder or
|
||
that project is no longer known (its turns then stay in the start folder)."""
|
||
slugs = (deps.meta_store.peek(sid) or {}).get("projects") or []
|
||
try:
|
||
proj = computer_project(deps, caller, w, slugs)
|
||
except HTTPException:
|
||
return None
|
||
return proj["path"] if proj else None
|
||
|
||
|
||
def computer_scope(deps, caller: Caller, w: dict, own: bool = False,
|
||
project: str | None = None) -> dict:
|
||
"""A run on the guest's computer is confined to its start folder: edits
|
||
there and in /tmp only, no permission prompts (the sidecar's scoped
|
||
launch), the run capped at what is left of their month — and told whose
|
||
machine it is on. On their own Claude (``own``) no budget applies.
|
||
Started in one of its projects (``project``, its folder — one their own
|
||
sessions already worked in, maybe outside the start folder), it may edit
|
||
there too."""
|
||
start = w.get("cwd")
|
||
if not start:
|
||
raise HTTPException(409, {"message": tr(caller.lang, "this computer isn't connected yet"),
|
||
"kind": "worker_offline", "worker": w["id"]})
|
||
dirs = [d for d in (project, start) if d]
|
||
scope = {"writeDirs": [*dict.fromkeys(dirs), "/tmp"], "denyRead": [], "remoteControl": False,
|
||
"systemPrompt": computer_prompt(caller, w)}
|
||
left = None if own else check_budget(deps, caller)
|
||
if left is not None:
|
||
scope["maxBudgetUsd"] = round(max(left, 0.01), 2)
|
||
return scope
|
||
|
||
|
||
# ── their own Claude on their own computer ──────────────────────────────────
|
||
# A guest's run on their computer bills the computer's own Claude login — the
|
||
# one `claude` in its terminal uses — first: account ``guest-<uid>``, which the
|
||
# computer's sidecar runs on that login, never through the proxy (sidecar
|
||
# ``claude_accounts.machine_login``). The owner's account (the proxy, within
|
||
# budget and models) is the fallback: the guest picked the host's account, the
|
||
# computer isn't signed in (``/health`` ``ownLogin``; a sidecar from before it
|
||
# says nothing — the host's, as before), or a run there ended on a usage limit
|
||
# (held LIMIT_HOLD_S) or a dead login (held until the computer signs in again).
|
||
COMPUTER_LIMIT_HOLD_S = float(os.environ.get("ACCOUNT_HEALTH_LIMIT_HOLD_S", str(5 * 3600)))
|
||
COMPUTER_AUTH_WINDOW_S = 7 * 86400
|
||
|
||
|
||
def computer_login(deps, w: dict) -> dict | None:
|
||
"""What the computer last said of its own Claude login (``/health``'s
|
||
``ownLogin``: ``{signedIn, subscriptionType, credentialsAt}``)."""
|
||
st = deps.worker_store.status(w["id"]) or {}
|
||
login = st.get("ownLogin")
|
||
return login if isinstance(login, dict) else None
|
||
|
||
|
||
def _epoch(iso) -> float:
|
||
try:
|
||
return datetime.datetime.fromisoformat(str(iso).replace("Z", "+00:00")).timestamp()
|
||
except ValueError:
|
||
return 0.0
|
||
|
||
|
||
# (worker, account) → the (summaries, meta) versions last scanned for a hold.
|
||
_hold_scanned: dict[tuple[str, str], tuple] = {}
|
||
|
||
|
||
def computer_hold(deps, w: dict, own: str) -> str | None:
|
||
"""``limited`` / ``signed_out`` when a run of theirs on this computer's
|
||
own login ended on that error lately — else None. What a scan finds is
|
||
kept on the worker's status: a later turn on the host's account that
|
||
answers clears the error from the transcript, not the plan's limit."""
|
||
st = deps.worker_store.status(w["id"]) or {}
|
||
held = dict(st.get("ownHold") or {})
|
||
login = computer_login(deps, w) or {}
|
||
found = False
|
||
key = (w["id"], own)
|
||
ver = (getattr(deps.store, "summaries_version", None), deps.meta_store.version)
|
||
scan = _hold_scanned.get(key) != ver or ver[0] is None
|
||
_hold_scanned[key] = ver
|
||
for _path, s in (deps.store.all_summaries() if scan else ()):
|
||
err = s.get("lastApiError")
|
||
if not err or err.get("kind") not in ("auth", "rate_limit"):
|
||
continue
|
||
meta = deps.meta_store.peek(s.get("sessionId") or "") or {}
|
||
if meta.get("worker") != w["id"] or meta.get("account") != own:
|
||
continue
|
||
at = _epoch(err.get("at"))
|
||
if at > (held.get(err["kind"]) or 0.0):
|
||
held[err["kind"]] = at
|
||
found = True
|
||
if found:
|
||
deps.worker_store.set_status(w["id"], ownHold=held)
|
||
now = time.time()
|
||
if held.get("auth") and now - held["auth"] < COMPUTER_AUTH_WINDOW_S \
|
||
and held["auth"] > _epoch(login.get("credentialsAt")):
|
||
return "signed_out"
|
||
if held.get("rate_limit") and now - held["rate_limit"] < COMPUTER_LIMIT_HOLD_S:
|
||
return "limited"
|
||
return None
|
||
|
||
|
||
def computer_own(deps, uid: str, w: dict) -> dict:
|
||
"""Where guest ``uid``'s own Claude stands on their computer ``w``, for
|
||
the composer chip and the routing: ``{signedIn, subscriptionType, usable,
|
||
hold}``."""
|
||
login = computer_login(deps, w) or {}
|
||
signed = bool(login.get("signedIn"))
|
||
hold = computer_hold(deps, w, accounts_mod.guest_account(uid)) if signed else None
|
||
return {"signedIn": signed, "subscriptionType": login.get("subscriptionType"),
|
||
"hold": hold, "usable": signed and not hold}
|
||
|
||
|
||
def computer_account(deps, caller: Caller, w: dict) -> str | None:
|
||
"""The account a guest's next run on their computer ``w`` tries first:
|
||
their own Claude there (``guest-<uid>``) when it is usable and they
|
||
didn't pick the host's account — else None (the owner's, as before)."""
|
||
if prefers_host(deps, caller) or not computer_own(deps, caller.id, w)["usable"]:
|
||
return None
|
||
return accounts_mod.guest_account(caller.id)
|
||
|
||
|
||
def run_on_computer(deps, caller: Caller, w: dict, send, project: str | None = None) -> dict:
|
||
"""Launch a guest's run on their computer: on its own login first
|
||
(``computer_account`` — any model, no budget), else — or when the
|
||
computer refuses that launch as signed out / at its limit — on the
|
||
owner's account through the proxy, under their budget and models.
|
||
``send(account, scope, fallback)`` does the launch; ``fallback`` says the
|
||
own login was tried (a model they may not use on the host's account is
|
||
swapped for one they may, as on the lab) — the model is its business."""
|
||
own = computer_account(deps, caller, w)
|
||
if own:
|
||
try:
|
||
return {**send(own, computer_scope(deps, caller, w, own=True, project=project), False),
|
||
"account": own}
|
||
except HTTPException as e:
|
||
d = e.detail if isinstance(e.detail, dict) else {}
|
||
if d.get("kind") not in FALLBACK_KINDS:
|
||
raise
|
||
# Signed in there but not tried (held, or they picked the host's): the
|
||
# host's account is a fallback too, the model swapped rather than refused.
|
||
fallback = bool(own) or bool((computer_login(deps, w) or {}).get("signedIn")
|
||
and not prefers_host(deps, caller))
|
||
return {**send(accounts_mod.DEFAULT, computer_scope(deps, caller, w, project=project), fallback),
|
||
"account": accounts_mod.DEFAULT}
|
||
|
||
|
||
def session_computer(deps, sid: str) -> dict | None:
|
||
"""The guest computer a session runs on, else None."""
|
||
from workers import guests
|
||
meta = deps.meta_store.peek(sid) or {}
|
||
wid = meta.get("worker") or meta.get("workerSource")
|
||
w = deps.worker_store.get(wid) if wid else None
|
||
return w if guests.is_guest(w) else None
|