Files
ai-agent/backend/schemas/users.py
gabrielvidalandClaude Opus 5.5 36528b2953 fix(plugins): leftovers of the plugin migration — read-only plugin reads, conversation.started, a clean OpenAPI dump
- `GET /api/plugins/{pid}/actions/{action}?payload=` runs an action the
  manifest marks `readOnly`; a read-only account (the screenshot bot) may only
  use safe methods, so its plugin frames send actions as GETs and plugin pages
  (Plans, Approvals, Forms) show their data instead of "method not allowed".
- Core now fires the `conversation.started` hub event it already accepted from
  manifests (prompt ≤ 4,000 chars, projects, worker, owner, origin) — Plans
  links the run its *Implement* opens.
- The plugin conversation bridge's rows carry `worker` ("local" = the lab), so
  Approvals can refuse requests from another machine again.
- The catch-all `/proxy/tools/plugins/{pid}/proxy/{path}` is out of the OpenAPI
  spec (six methods, one operation id): `frontend/openapi.json` is a full
  re-dump again and `src/generated/` is regenerated from it.
- `projects.create` and the `createProjects` switch are retired (New project is
  the `new-project` plugin's grant); the carry-over reads the old permission
  off the raw record. Mocks and the roles catalog dump follow.
- The worker outbox mirror loses the `frm` answer branch and the `secrets`
  hook the retired form engine used; its docstring no longer names /api/forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:23:21 +01:00

657 lines
23 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Guests: ``/api/me``, the owner's user admin, conversation sharing."""
from __future__ import annotations
from typing import Literal, Optional
from .base import Schema
from .misc import WorkerTool, WorkerToolInstall, WorkerToolJob
# A user's language preference (users.json ``lang``, core/i18n.py).
LangPref = Literal["auto", "en", "fr"]
__all__ = [
"ProjectGrant", "NotifyPrefs", "PushDevice", "PushPref", "PushDevices", "PushSendResult",
"PushTestResult", "Me", "GuestUser", "UsersResponse",
"DaySpend", "ProjectSpend", "UserConversation", "UserActivity",
"StatsPeriod", "StatsTotals", "StatsMonth", "StatsDay", "StatsCalendarDay",
"StatsProject", "StatsModel", "StatsTokens", "StatsFootprint", "GuestStats",
"LoginLink", "ShareCandidate", "TerminalSession", "TerminalSessions", "ConversationShare", "GuestShortcut",
"GuestDefaults", "GuestSkill", "GuestSkillsResponse",
"NewProjectAccess", "NewProjectPolicy", "DomainDns", "DomainStatus",
"ComputerPolicy", "ComputerLimits", "Computer", "ComputersResponse", "ComputerEnroll",
"ComputersWaiting", "IdpApp", "IdpStatus", "GuestIdp", "IdpSyncResult", "AuthMethods",
]
class ProjectGrant(Schema):
slug: str
level: str # "view" | "chat" | "ship"
class NotifyPrefs(Schema):
channels: list[str] # "in_app" | "email" | "webpush"
class PushDevice(Schema):
"""A browser a guest turned push on from (users/webpush.py) — ``id`` is
a hash of its push endpoint."""
id: str
label: str = ""
createdAt: Optional[str] = None
lastOkAt: Optional[str] = None
lastError: Optional[str] = None
class PushPref(Schema):
"""One group of push kinds and what it does on the user's devices
(users/push_style.py GROUPS) — the PWA's stand-in for Android channels."""
id: str
label: str
level: str # "buzz" | "silent" | "off"
default: str
class PushDevices(Schema):
publicKey: str # the VAPID applicationServerKey
devices: list[PushDevice]
prefs: list[PushPref] = []
class PushSendResult(Schema):
id: str
ok: bool
status: Optional[int] = None
error: Optional[str] = None
dropped: bool = False # the push service said it is gone
class PushTestResult(Schema):
results: list[PushSendResult]
devices: list[PushDevice]
class NewProjectAccess(Schema):
"""Whether the caller may start a project from a template now (the
composer's *+ New project* pick), and where it would be hosted."""
allowed: bool
reason: Optional[str] = None # why not, when not allowed
remaining: Optional[int] = None # projects left in the quota (None: no quota)
# Where a guest's projects go: <name>.<bucket>.<domain>, or
# <name>.<domain> under a root domain of their own with no bucket ("").
bucket: Optional[str] = None
domain: str = "gabvdl.xyz"
class NewProjectPolicy(Schema):
"""What guests may create (Settings → Users → Every guest → New projects)."""
quota: int = 10 # projects per guest, all time
templates: list[str] # templates offered to guests
approve: list[str] # of those, the ones the owner approves first
visibility: list[str] # "public" | "password" | "geo"
visibilityDefault: str = "public"
level: str = "ship" # the creator's grant on their new project
domain: str = "gabvdl.xyz" # <name>.<bucket>.<domain>
class GuestClaude(Schema):
"""A guest's own Claude login (accounts/guest.py) — what it is, whether it
works (``status`` from accounts/health.py; ``limited`` = at its usage
limit, runs fall back to the owner's account), and what ran on it this
month (``spentUsd`` — a list-price estimate, never capped)."""
connected: bool
account: str
email: Optional[str] = None
subscriptionType: Optional[str] = None
connectedAt: Optional[str] = None
status: Optional[str] = None # "ok" | "signed_out" | "unknown"
reason: Optional[str] = None
since: Optional[str] = None
limited: bool = False
pendingLogin: bool = False
# Their composer's account chip: "own" (their Claude first, the owner's
# as the fallback) or "host" (the owner's account) — PUT /api/me/claude/bill.
bill: str = "own"
spentUsd: Optional[float] = None
totalSpentUsd: Optional[float] = None
conversations: Optional[int] = None
class PaidToolLine(Schema):
usd: float = 0.0
calls: int = 0
# What the calls did: {"images": n} | {"jobs": n} | {"videos": n} | {"renders": n}
units: dict[str, float] = {}
class PaidToolsMonth(Schema):
"""One month of a caller's paid tools (toolproxy/ledger.py)."""
month: str
usd: float = 0.0
calls: int = 0
byTool: dict[str, PaidToolLine] = {}
class GuestTools(Schema):
"""A guest's paid tools (toolproxy/): the groups switched on (images,
video, 3d), Nano Banana Pro, the monthly tools budget — apart from their
Claude budget — and this month's usage."""
groups: list[str] = []
pro: bool = False
budgetUsd: float = 10.0
usage: Optional[PaidToolsMonth] = None
class Me(Schema):
"""Who the browser is: the owner, or a guest with their grants."""
id: str
role: str # "owner" | "guest"
name: str
email: Optional[str] = None
readonly: bool = False
# Their role (authz/roles.py; "operator" for the owner) and what they
# may do: the role's permissions plus their overrides.
roleId: Optional[str] = None
perms: list[str] = []
# What a read-only credential (the screenshot bot) may still read: the app
# shows those pages, the gate refuses their writes.
readPerms: list[str] = []
projects: list[ProjectGrant]
models: list[str]
budgetUsd: Optional[float] = None
spentUsd: Optional[float] = None
notify: Optional[NotifyPrefs] = None
mail: bool = False # outbound mail configured (login links can be mailed)
surface: Optional[str] = None # "admin" | "guest"
# The owner's shortcuts a guest gets, live (settings/shortcuts.py — guest
# wording applied); None for the owner, who holds the library itself.
sharedShortcuts: Optional[list["GuestShortcut"]] = None
# The owner's un-send sweep curve, live (settings/unsend.py); None for the
# owner (it is in their own settings store) and while it is the default.
unsendCurve: Optional["AnimationCurve"] = None
# The owner looking through this guest's eyes (Settings → Users →
# Impersonate): the PWA shows a "back to admin" bar.
impersonating: bool = False
newProjects: Optional[NewProjectAccess] = None
# A guest's own Claude login (None for the owner).
claude: Optional[GuestClaude] = None
# The language the app speaks to them (core/i18n.py): a guest's stored
# pick — "auto" = their browser's, resolved by the PWA (frontend/src/i18n)
# — set in Settings → Display or by the owner on their page; the owner is
# always "en".
lang: LangPref = "auto"
# A guest's *Auto fresh* (users/store.py ``auto_fresh``): a reply on an
# expired prompt cache compacts first instead of asking. None for the
# owner, whose own is in Settings → Fresh context (``autoFresh``).
autoFresh: Optional[bool] = None
# A guest's Code Mode switch (the composer's *Code β* chip); None for the owner.
codeMode: Optional[bool] = None
# A guest's paid tools and this month's use of them (None for the owner).
tools: Optional[GuestTools] = None
# The hub machine's display name (core/config.HUB_LABEL: "Homelab",
# "Devbox") — what the app calls the local runner.
hubName: str = "Homelab"
class ComputerPolicy(Schema):
enabled: bool = False
max: int = 3
count: int = 0 # how many they have paired
class ComputerLimits(Schema):
"""What the Claude proxy holds every guest's computers to: the owner's
plan utilization past which their calls wait, and the calls one computer
may have in flight (claudeproxy/limits.py)."""
fiveHourPct: int = 80
sevenDayPct: int = 85
inFlight: int = 10
perMinute: int = 60 # calls a minute, all of one guest's computers
rotateDays: int = 7 # their proxy + link tokens are replaced this often
mirrorMb: int = 500 # transcript MB the hub mirrors per computer a month
class ComputerOwnClaude(Schema):
"""A guest computer's own Claude login (its ``/health`` ``ownLogin``)."""
signedIn: bool = False
subscriptionType: Optional[str] = None
# usable: signed in and not held — limited (a run there hit its usage
# limit in the last 5 h) or signed_out (a run ended on a dead login)
usable: bool = False
hold: Optional[Literal["limited", "signed_out"]] = None
class Computer(Schema):
"""A guest's own computer, paired as a worker (users/computers.py)."""
id: str
name: Optional[str] = None
hostname: Optional[str] = None
platform: Optional[str] = None
machine: Optional[str] = None
# pairing (enrolled, its link not paired yet) | online | offline | unauthorized | unknown
status: str = "unknown"
lastSeen: Optional[str] = None
running: int = 0
pairedAt: Optional[str] = None
enrolledAt: Optional[str] = None
cwd: Optional[str] = None
lastError: Optional[str] = None
# What its Claude calls cost this month (the proxy's ledger).
spentUsd: float = 0
# The guest paused it: no run starts there and the proxy refuses its calls.
paused: bool = False
# Transcript MB mirrored from it this month (against limits.mirrorMb).
mirroredMb: float = 0
# Its terminal `claude` asks which Claude to use (None: a sidecar from
# before the launcher — it updates itself), and how many of its terminal
# sessions the guest synced (workers/terminal.py).
launcher: Optional[bool] = None
syncedSessions: int = 0
# Its own Claude login — what the guest's runs there bill first
# (users/runs.computer_account).
ownClaude: Optional["ComputerOwnClaude"] = None
# Its Setup checklist (claude / gh / pi) and the Install buttons' state
# (workers/tools.py) — None from a sidecar from before.
tools: Optional[dict[str, WorkerTool]] = None
toolsCheckedAt: Optional[int] = None
toolInstall: Optional[WorkerToolInstall] = None
toolJobs: Optional[dict[str, WorkerToolJob]] = None
class TerminalSession(Schema):
"""One of a guest computer's own Claude Code sessions, as its portal
lists them (``GET /api/me/computers/{id}/sessions``)."""
id: str
title: str
prompt: str = ""
cwd: Optional[str] = None
mtime: float
# The computer shares it (synced off the guest's own login).
synced: bool = False
# How the app has it: run (started from the app) | proxy (ai-agent
# Claude) | local (synced, their own login) | None (not in the app).
inApp: Optional[Literal["run", "proxy", "local"]] = None
# Its conversation in the app, once mirrored.
conversationId: Optional[str] = None
class TerminalSessions(Schema):
sessions: list[TerminalSession]
launcher: bool = True
class ComputersWaiting(Schema):
"""Why a guest's computers can't call Claude right now."""
kind: Literal["budget", "plan"]
message: str
class ComputersResponse(Schema):
computers: list[Computer]
enabled: bool
max: int
limits: ComputerLimits
# This month's metered spend of all their computers.
spentUsd: float = 0
# This month on the owner's account, the lab's conversations included —
# what their budget is checked against — and that budget.
monthUsd: float = 0
budgetUsd: Optional[float] = None
# Set while the proxy refuses their computers' calls (the Me banner).
waiting: Optional[ComputersWaiting] = None
# A code was handed out and not used yet (the add dialog waits on it).
enrolling: bool = False
class ComputerEnroll(Schema):
"""``POST /api/me/computers`` — the one-time code and the line to run."""
code: str
expiresAt: int
command: str
class GuestUser(Schema):
id: str
email: str
name: str
# Their role (authz/roles.py), the person-level permissions added to it
# and taken from it, and the result.
role: str
allow: list[str] = []
deny: list[str] = []
perms: list[str] = []
projects: dict[str, str]
models: list[str]
budgetUsd: float
notify: NotifyPrefs
disabled: bool
createdAt: str
lastLoginAt: Optional[str] = None
sessions: int = 0
# What their conversations cost: this month (what the budget is checked
# against) and all time, and how many conversations they started.
spentUsd: float = 0
totalSpentUsd: float = 0
conversations: int = 0
# This month's share of ``spentUsd`` that their own computers spent
# through the Claude proxy (its ledger).
computersSpentUsd: float = 0
# What the owner took off this month's spend (``budgetCredits``, a
# credit for spend that wasn't theirs — users/runs.month_credit).
creditUsd: float = 0
# Their own Claude login, and what ran on it (not on the owner's bill —
# the figures above are the owner's account only).
claude: Optional[GuestClaude] = None
# New projects (the new-project plugin): under which address bucket
# (blank ⇒ their id), under a root domain of their own (blank ⇒ the
# shared one; with it, a blank bucket ⇒ <name>.<domain>).
bucket: str = ""
domain: str = ""
# Their runs may drive the hub with the `ai-agent` CLI — as them, on their
# own conversations and projects (users/cli.py); off by default.
cli: bool = False
# They may connect AI apps (Claude.ai, ChatGPT…) to the hub's MCP server,
# as them (mcpserver/); off by default.
mcp: bool = False
pushDevices: list[PushDevice] = []
# The What's new carousel opens on its own when they load the app with
# entries they haven't seen (whatsnew/; Settings → Users → <guest>).
whatsNew: bool = True
# An expired-cache reply compacts first instead of asking (users/store.py
# ``auto_fresh``; on unless they or the owner turned it off).
autoFresh: bool = True
# Their *No project* conversations may run shell commands (users/store.py
# ``scratch_bash``; on unless the owner turned it off — off, those runs
# have no Bash at all).
scratchBash: bool = True
# May they start conversations in Claude Code's Code Mode (beta) — the
# composer's *Code β* chip. Unset ⇒ on.
codeMode: bool = True
# The language the app speaks to them — their pick or "auto" (their
# browser's) — and the browser language last seen on their sign-in or
# /api/me (what "auto" means for their pushes and mails), None before.
lang: LangPref = "auto"
browserLang: Optional[Literal["en", "fr"]] = None
# May they pair computers of their own as workers, and how many
# (users/computers.py); off by default.
computers: Optional[ComputerPolicy] = None
# Their paid tools (toolproxy/) and this month's use of them.
tools: Optional[GuestTools] = None
# The identity provider's other apps switched on for them (``{group: on}``)
# and their mirror there (None when no provider is set up).
apps: dict[str, bool] = {}
idp: Optional["GuestIdp"] = None
class IdpApp(Schema):
"""An app the identity provider signs guests in to besides this one
(users/idp.py ``IDP_APPS``): membership of ``group`` lets them in."""
group: str
label: str
url: str = ""
class IdpStatus(Schema):
"""The guests' identity provider (users/idp.py, users/oidc.py): mirrored
into (``enabled``: the admin API key is set) and signed in through
(``login``: the OIDC client is set — the mailed link login is off then)."""
enabled: bool = False
login: bool = False
issuer: Optional[str] = None
apps: list[IdpApp] = []
class GuestIdp(Schema):
"""A guest's mirror in the identity provider: its id there (the OIDC
``sub``) and how the last sync went."""
id: Optional[str] = None
ok: Optional[bool] = None
error: Optional[str] = None
at: Optional[str] = None
class IdpSyncResult(Schema):
results: dict[str, GuestIdp]
class AuthMethods(Schema):
"""How the login page signs a guest in: through the identity provider
(its button, ``provider``), or with a mailed link and code."""
oidc: bool
provider: Optional[str] = None
apps: list[str] = [] # the other apps the same account opens (labels)
# The owner's internet address (remoteaccess/): a passkey, not the provider.
passkey: bool = False
locked: bool = False # …with *Internet access* switched off
class UsersResponse(Schema):
users: list[GuestUser]
levels: list[str]
channels: list[str]
defaultModels: list[str]
mail: bool
guestUrl: Optional[str] = None
idp: Optional[IdpStatus] = None
class DaySpend(Schema):
date: str # YYYY-MM-DD (UTC)
usd: float # on the owner's account
ownUsd: float = 0 # on the guest's own Claude login (an estimate)
class ProjectSpend(Schema):
project: Optional[str] = None
usd: float
ownUsd: float = 0
conversations: int = 0
class UserConversation(Schema):
id: str
sessionId: Optional[str] = None
title: Optional[str] = None
project: Optional[str] = None
costUsd: float = 0
at: Optional[str] = None # when it last ran
startedAt: Optional[str] = None
state: Optional[str] = None # the card's state ("running", …)
own: bool = False # ran on their own Claude login
class UserActivity(Schema):
"""One guest's page in Settings → Users (``GET /api/users/{id}/activity``)."""
dailySpend: list[DaySpend] # the last 30 days, oldest first
spendByProject: list[ProjectSpend] # this month, biggest first
recentConversations: list[UserConversation]
conversations: int
conversationsThisWeek: int # started in the last 7 days
class StatsPeriod(Schema):
days: int # 7, 30 or 0 (all time)
start: str # local YYYY-MM-DD, both ends included
end: str
class StatsTotals(Schema):
usd: float # the period, on the owner's account
ownUsd: float = 0 # the period, on their own Claude (estimate)
conversations: int # that last ran in the period
activeMinutes: int # distinct 5-minute slots Claude worked × 5
activeDays: int
class StatsMonth(Schema):
usd: float # what the budget is checked against
ownUsd: float = 0
class StatsDay(Schema):
date: str # local YYYY-MM-DD
usd: float
ownUsd: float = 0
conversations: int = 0 # started that day
activeMinutes: int = 0
class StatsCalendarDay(Schema):
date: str
conversations: int = 0
activeMinutes: int = 0
class StatsProject(Schema):
project: Optional[str] = None
usd: float
ownUsd: float = 0
conversations: int = 0
activeMinutes: int = 0
class StatsModel(Schema):
model: str
conversations: int = 0
usd: float = 0
activeMinutes: int = 0
class StatsTokens(Schema):
model: str # the model the conversations are attributed to
input: int = 0
output: int = 0
cacheRead: int = 0
cacheWriteTokens: int = 0
class StatsFootprint(Schema):
"""What ``lib/footprint.ts`` estimates carbon, water and energy from."""
tokens: list[StatsTokens]
localWh: float = 0 # the EVOX2's measured share
class GuestStats(Schema):
"""A guest's own dashboard (``GET /api/me/stats``, the owner's
``/api/users/{id}/stats``): their conversations over ``period``."""
period: StatsPeriod
tzOffset: int
totals: StatsTotals
month: StatsMonth
conversations: int # all time
conversationsThisWeek: int # started in the last 7 days
firstDay: Optional[str] = None # their first conversation's local day
daily: list[StatsDay] # every day of the period, oldest first
calendar: list[StatsCalendarDay] # every day anything ran, all time
byProject: list[StatsProject] # the period, biggest first
byModel: list[StatsModel] # the period, busiest first
footprint: StatsFootprint # the period
class LoginLink(Schema):
url: str
sent: bool
expiresInS: int
class ShareCandidate(Schema):
id: str
name: str
level: Optional[str] = None
class AudienceMember(Schema):
id: str # "owner" or a guest's users.json id
name: str
class ConversationShare(Schema):
sessionId: str
owner: Optional[str] = None
project: Optional[str] = None
participants: list[str]
candidates: list[ShareCandidate]
# Does the caller hear about this conversation (its pushes, asks, forms)?
notifying: bool = False
# Everyone who does — who started it, who it's shared with, the owner if
# they follow it, minus whoever muted it.
audience: list[AudienceMember] = []
class CurvePoint(Schema):
"""A keyframe of an animation curve: time fraction ``x``, progress ``y``."""
x: float
y: float
class AnimationCurve(Schema):
"""``@gabvdl/ui``'s ``AnimationCurve``: keyframes joined by cubic-bézier
segments (``easings[i]`` = the CSS ``cubic-bezier(x1, y1, x2, y2)`` from
``points[i]`` to ``points[i + 1]``)."""
points: list[CurvePoint]
easings: list[list[float]]
class GuestShortcut(Schema):
"""A prompt shortcut in the frontend's ``PromptShortcut`` shape."""
id: str
label: str
icon: str = "Sparkles"
guideline: str = ""
defaultOn: bool = False
labelOff: Optional[str] = None
guidelineOff: Optional[str] = None
children: Optional[list[str]] = None
triggers: Optional[list[str]] = None
shared: Optional[bool] = None
class GuestCronLimitsOut(Schema):
"""How many scheduled jobs of their own each guest may have, and the model
a new one starts on ("qwen" | "sonnet")."""
maxJobs: int = 5
defaultModel: str = "qwen"
class GuestDefaults(Schema):
"""What the owner sets for every guest at once (Settings → Users)."""
promptShortcuts: list[GuestShortcut]
sharedSkills: list[str] # `name` (repo) | `<project>/<name>`
newProjects: NewProjectPolicy
computerLimits: ComputerLimits = ComputerLimits()
# A guest's own scheduled jobs (cron/guests.py).
cronLimits: GuestCronLimitsOut = GuestCronLimitsOut()
class DomainDns(Schema):
apex: list[str] = [] # the domain's A records (public resolvers)
wildcard: list[str] = [] # a name under it — the * record
ok: bool = False # both point at the lab's public IP
class DomainStatus(Schema):
"""A guest's own root domain at the zipgo host's public edge
(users/edge.py): ready once the DNS points at the lab, the edge
passes it through, zipgo has its folder and the certificate verifies."""
domain: str
publicIp: Optional[str] = None
dns: Optional[DomainDns] = None
routed: bool = False
folder: bool = False
https: bool = False
ready: bool = False
steps: list[str] = [] # what a setup just did
error: Optional[str] = None
checkedAt: Optional[str] = None
class GuestSkill(Schema):
"""A skill a guest's run can use — the composer's `/` mentions."""
name: str # the invocation name (`shared:<name>` when shared)
description: str = ""
triggerWords: list[str] = []
source: str # "shared" | <project slug>
class GuestSkillsResponse(Schema):
skills: list[GuestSkill]