Shared hooks for templates, memories, desk-phone, activity, project-env, ship and blue-green-deploy, with no legacy module removed: - manifest: owner-only templates.read / memories.read / projects.env / activity.read / ship.run (one _OPERATOR_CAPS set); provides memories.index, notify.audio, app.banner - runner: AIA_TEMPLATES_DIR / AIA_MEMORIES_DIR / AIA_PROJECTS_DIR for the owner's runs; requester_context() carries sessionId for runAs: owner - /api/plugins (+ ui): active provides keys (no app.banner for guests) - hub/conversations: memories=1 (memoriesRead, model), memory=<slug> - hub/activity (plugins/activitydata.py now holds the rollup; dashboards/activity.py is a shim; dashboards/timebins.py helpers) - /api/usage/daily (owner, lab.read); Home's usage card reads it - memories_bridge.py (plans_bridge twin), Graph prefers it - banner.py + /api/app-banner + StatusBanner.tsx; webhook/action of the provider invalidates and publishes SSE banner; is_maintenance pauses guest-job delivery - hubbridge: inline scaffold template list; ship/deploy, ship/audit, ship/scan bridges - project.detail slot on Project.tsx; aiAgentPlugin.copy(text) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
307 lines
9.6 KiB
Python
307 lines
9.6 KiB
Python
"""Plan usage: the official /usage percentages (rate-limits.json snapshots, HA
|
||
backfill) and their calibration against the plan units conversations spend."""
|
||
from __future__ import annotations
|
||
|
||
from typing import Literal, Optional
|
||
|
||
from .base import Schema
|
||
|
||
__all__ = [
|
||
"LimitWindow",
|
||
"PlanSegment",
|
||
"PlanHistory",
|
||
"WindowFit",
|
||
"Calibration",
|
||
"BillingWeek",
|
||
"Billing",
|
||
"AccountLimits",
|
||
"UsageLimitsResponse",
|
||
"LimitPoint",
|
||
"HourMeter",
|
||
"DayMeter",
|
||
"UsageHistory",
|
||
"CalibrationHistory",
|
||
"CalibrateResult",
|
||
"UsageImportResult",
|
||
"BudgetAmount",
|
||
"BudgetItem",
|
||
"BudgetUpcoming",
|
||
"BudgetPace",
|
||
"BudgetFamily",
|
||
"BudgetRate",
|
||
"UsageBudget",
|
||
"BurnRate",
|
||
"UsageBurnResponse",
|
||
"DailyUsageDay",
|
||
"DailyUsageResponse",
|
||
]
|
||
|
||
|
||
class LimitWindow(Schema):
|
||
pct: float
|
||
resetsAt: Optional[float] = None
|
||
|
||
|
||
class PlanSegment(Schema):
|
||
"""A stretch of time an account spent on one plan (usage/plans.py): its
|
||
login's rate-limit tier and the limit windows it enforced. Each segment is
|
||
calibrated on its own hours."""
|
||
account: str
|
||
since: float
|
||
until: Optional[float] = None # None: the plan in force
|
||
tier: Optional[str] = None # default_claude_max_20x; None = unknown
|
||
label: str # Max 20×
|
||
multiplier: Optional[float] = None # × Pro (Max 20× = 20)
|
||
displayName: Optional[str] = None # what Claude calls the plan ("Ultra")
|
||
subscriptionType: Optional[str] = None # the login's: max | team | pro | enterprise
|
||
windows: list[str] = [] # fit names: week, h5
|
||
# detected — seen changing; assumed — the account's past, backfilled on
|
||
# the first reading; manual — recorded by hand (POST /api/usage/plans)
|
||
source: Literal["detected", "assumed", "manual"] = "detected"
|
||
reason: Optional[str] = None # "Max 5× → Max 20×", "5-hour window gone"
|
||
|
||
|
||
class PlanHistory(Schema):
|
||
account: str
|
||
current: Optional[PlanSegment] = None
|
||
history: list[PlanSegment] = []
|
||
|
||
|
||
class WindowFit(Schema):
|
||
"""One window's exchange rate: plan units (and list $) per 1 %."""
|
||
unitsPerPct: float
|
||
usdPerPct: Optional[float] = None
|
||
r2: Optional[float] = None
|
||
n: int = 0
|
||
interceptPct: Optional[float] = None
|
||
|
||
|
||
class Calibration(Schema):
|
||
account: str
|
||
fittedAt: float
|
||
days: int
|
||
# fit — measured; default / carried / scaled — a plan segment's seed
|
||
# before its first trusted fit: the account's default rate, the previous
|
||
# plan's last fit, or that fit × the tiers' multipliers.
|
||
source: Literal["fit", "default", "carried", "scaled"]
|
||
# Passed the bar to become the rate in force (enough hours, R², and within
|
||
# ×3 of the seed rate); untrusted fits are kept for the history chart.
|
||
trusted: bool = False
|
||
week: WindowFit
|
||
# None for a plan with no 5-hour window (the personal Max since
|
||
# 2026-10-31, the opencode ChatGPT seat).
|
||
h5: Optional[WindowFit] = None
|
||
# The plan segment this rate belongs to (absent on fits from before plans
|
||
# were tracked).
|
||
plan: Optional[PlanSegment] = None
|
||
# A seed: the multiplier applied to the rate it carries over, and the
|
||
# fittedAt of the fit it came from.
|
||
scale: Optional[float] = None
|
||
basedOn: Optional[float] = None
|
||
|
||
|
||
class WeekTarget(Schema):
|
||
"""The week an account wants maxed out (usage/target.py): a straight
|
||
line from 0 % when the window opens to ``goal`` % at its reset."""
|
||
goal: float
|
||
# One push each time the week falls this many points under the line.
|
||
behindAlert: Optional[float] = None
|
||
|
||
|
||
class BillingWeek(Schema):
|
||
"""One weekly window of the billing cycle and the highest % it reached."""
|
||
resetsAt: float
|
||
peak: float
|
||
current: bool = False # still open: its peak can still rise
|
||
inCycle: bool = True # ends in this cycle (else the previous one)
|
||
|
||
|
||
class Billing(Schema):
|
||
"""A paid plan's billing cycle (usage/billing.py). The dates are an
|
||
estimate: a monthly renewal on the day the subscription started."""
|
||
subscriptionStartedAt: float
|
||
periodStart: float # the last renewal
|
||
previousPeriodStart: Optional[float] = None # the renewal before it
|
||
nextBillingAt: float
|
||
estimated: bool = True
|
||
weeks: list[BillingWeek] = [] # this cycle's and the previous one's weeks, oldest first
|
||
|
||
|
||
class AccountLimits(Schema):
|
||
account: str
|
||
label: Optional[str] = None
|
||
# Only on an account that declares one (the personal Max).
|
||
weekTarget: Optional[WeekTarget] = None
|
||
# "five_hour", "seven_day" (and any model-specific "seven_day_<model>").
|
||
windows: dict[str, LimitWindow] = {}
|
||
updatedAt: Optional[float] = None
|
||
stale: bool = True
|
||
calibration: Optional[Calibration] = None
|
||
plan: Optional[PlanSegment] = None
|
||
# A Claude plan Gabriel pays for: when it renews, this cycle's weeks.
|
||
billing: Optional[Billing] = None
|
||
|
||
|
||
class UsageLimitsResponse(Schema):
|
||
accounts: dict[str, AccountLimits]
|
||
|
||
|
||
class LimitPoint(Schema):
|
||
t: float
|
||
pct: float
|
||
resetsAt: Optional[float] = None
|
||
|
||
|
||
class HourMeter(Schema):
|
||
t: float
|
||
cost: float
|
||
units: float
|
||
dWeek: Optional[float] = None
|
||
d5h: Optional[float] = None
|
||
|
||
|
||
class DayMeter(Schema):
|
||
day: str
|
||
cost: float
|
||
units: float
|
||
observedWeek: Optional[float] = None
|
||
predictedWeek: Optional[float] = None
|
||
untrackedWeek: Optional[float] = None
|
||
observed5h: Optional[float] = None
|
||
predicted5h: Optional[float] = None
|
||
|
||
|
||
class UsageHistory(Schema):
|
||
account: str
|
||
days: int
|
||
series: dict[str, list[LimitPoint]]
|
||
hourly: list[HourMeter]
|
||
daily: list[DayMeter]
|
||
calibration: Optional[Calibration] = None
|
||
# The plan segments overlapping the range, oldest first.
|
||
plans: list[PlanSegment] = []
|
||
|
||
|
||
class CalibrationHistory(Schema):
|
||
account: str
|
||
current: Optional[Calibration] = None
|
||
history: list[Calibration] = []
|
||
|
||
|
||
class CalibrateResult(Schema):
|
||
calibrations: dict[str, Calibration]
|
||
shifted: list[str] = []
|
||
|
||
|
||
class UsageImportResult(Schema):
|
||
imported: int
|
||
|
||
|
||
class BudgetAmount(Schema):
|
||
"""A share of the week: %, plan units, list $ (None without a $ rate)."""
|
||
pct: float
|
||
units: float
|
||
usd: Optional[float] = None
|
||
|
||
|
||
class BudgetItem(Schema):
|
||
"""Spend already due before the reset: an enabled cron job's firings
|
||
(priced at the median of its last runs) or a scheduled conversation."""
|
||
kind: Literal["cron", "scheduled"]
|
||
id: Optional[str] = None
|
||
name: str
|
||
runs: int # firings before the reset
|
||
next: float # epoch of the first one
|
||
unitsPerRun: float
|
||
sampled: int = 0 # runs the price is the median of (0 = a guess)
|
||
units: float
|
||
|
||
|
||
class BudgetUpcoming(Schema):
|
||
pct: float
|
||
units: float
|
||
items: list[BudgetItem] = []
|
||
|
||
|
||
class BudgetPace(Schema):
|
||
"""% of the week per hour: observed (None after a reset or without an old
|
||
enough reading), the % it reaches at the reset at that pace, and the pace
|
||
that would use every free % by then."""
|
||
last6h: Optional[float] = None
|
||
last24h: Optional[float] = None
|
||
projected: Optional[float] = None
|
||
needed: Optional[float] = None
|
||
|
||
|
||
class BudgetFamily(Schema):
|
||
"""What the free part buys in one model family (fable/opus/sonnet/haiku)."""
|
||
tokensPerPct: Optional[float] = None
|
||
freeTokens: Optional[float] = None
|
||
unitsPerHour: float # a nonstop single-prompt run's burn
|
||
rateRuns: int = 0 # runs that rate is the median of (0 = default)
|
||
streams: Optional[float] = None # nonstop runs needed to use it all by the reset
|
||
|
||
|
||
class BudgetRate(Schema):
|
||
unitsPerPct: float
|
||
usdPerPct: Optional[float] = None
|
||
source: Optional[str] = None
|
||
trusted: bool = False
|
||
|
||
|
||
class UsageBudget(Schema):
|
||
"""GET /api/usage/budget — what is left of an account's week before its
|
||
reset, what is already due before it, and what the rest buys."""
|
||
account: str
|
||
label: Optional[str] = None
|
||
plan: Optional[PlanSegment] = None
|
||
window: Optional[str] = None # seven_day; None = no reading
|
||
pct: float = 0.0
|
||
resetsAt: Optional[float] = None
|
||
hoursLeft: float = 0.0
|
||
stale: bool = False
|
||
rate: Optional[BudgetRate] = None
|
||
left: Optional[BudgetAmount] = None
|
||
upcoming: Optional[BudgetUpcoming] = None
|
||
free: Optional[BudgetAmount] = None
|
||
pace: Optional[BudgetPace] = None
|
||
families: dict[str, BudgetFamily] = {}
|
||
|
||
|
||
class BurnRate(Schema):
|
||
"""One account's burn rate (usage/burn.py): the last ``windowMinutes`` of
|
||
spend per hour against the pace that reaches ``goal`` % at the reset."""
|
||
account: str
|
||
windowMinutes: int = 60
|
||
usdPerHour: float = 0.0
|
||
unitsPerHour: float = 0.0
|
||
pctPerHour: Optional[float] = None
|
||
goal: float = 100.0
|
||
pct: Optional[float] = None
|
||
resetsAt: Optional[float] = None
|
||
hoursLeft: Optional[float] = None
|
||
neededPctPerHour: Optional[float] = None
|
||
neededUsdPerHour: Optional[float] = None
|
||
# Where the week ends at the reset if this hour's pace holds (≤ 100).
|
||
projected: Optional[float] = None
|
||
stale: bool = True
|
||
at: float = 0.0
|
||
|
||
|
||
class UsageBurnResponse(Schema):
|
||
"""GET /api/usage/burn — every account with a week target."""
|
||
accounts: dict[str, BurnRate]
|
||
|
||
|
||
class DailyUsageDay(Schema):
|
||
"""One local day of ``GET /api/usage/daily``."""
|
||
date: str # YYYY-MM-DD, local to the caller's tzOffset
|
||
cost: float # USD, API-equivalent
|
||
tokens: int
|
||
conversations: int # top-level conversations active that day
|
||
|
||
|
||
class DailyUsageResponse(Schema):
|
||
"""The last N local days, oldest first — Home's usage card."""
|
||
days: list[DailyUsageDay]
|