Files
gabrielvidalandClaude Opus 5.5 61ecbdd993 feat(plugins): handoffs leave the core for the Handoff plugin
The handoff link, the conversation menu's Hand off ▸, HandoffDialog, the
Continued from / Continued in banners and POST /api/handoff move to the
handoff live plugin (ai-agent-plugins). What the core keeps is generic:

- ui.menuItems (conversation.menu): a plugin row in the conversation menu
  opening the plugin's sandboxed dialog; frame bridges close() and toast()
- slot places conversation.threadHeader / conversation.threadEnd, whose
  update carries the plugin's own meta.plugins.<id> (pluginData)
- ConversationDetail.pluginData (owner only)
- conversations.data: GET|POST hub/conversations/{sid}/data, a plugin's
  own data on a conversation (handler only, owner only, operator approval)
- runs.start takes test; hub/conversations rows carry model and harness
- carryover.handoffs moves the old meta.handoffFrom / handoffTo stamps
  into meta.plugins.handoff once

Removed: runs/handoff.py, /api/handoff, SpawnBody.handoffFrom and the
spawn's handoff origin, meta.handoffFrom/handoffTo and their resolved refs,
Handoff.tsx, the Handoffs eye switch (the plugin's vis switch replaces it).
The CLI's --handoff-from and MCP handoff_from are left alone (inert) until
the CLI/MCP plugin-commands mechanism lands.

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

565 lines
28 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.
"""A conversation's resolved state and merged metadata (``_conv_meta``),
plus the per-account summary views."""
import datetime
import threading
import accounts as accounts_mod
import projects as projects_mod
from projects import worker_projects as worker_projects_mod
from conversations import look as look_mod
from conversations import spawned_live
from conversations import resource_view
from conversations.parse import limit_resets_at
from core import liveruns
from core.config import RUNNING_WINDOW_SECS
from core.memo import _Memo
from core.state import AppState
from profiles import store as profiles_mod
def _auto_state(ended_at: str | None) -> str:
"""``running`` if the last recorded activity is recent, else ``finished``."""
if not ended_at:
return "finished"
try:
dt = datetime.datetime.fromisoformat(ended_at.replace("Z", "+00:00"))
except ValueError:
return "finished"
now = datetime.datetime.now(datetime.timezone.utc)
age = (now - dt).total_seconds()
return "running" if 0 <= age < RUNNING_WINDOW_SECS else "finished"
# The API errors a run can simply be sent on from (a usage limit once it
# resets, Anthropic overloaded, the connection lost) — the rest need a fix
# first (a login, a CLI update).
RESUMABLE_ERRORS = ("rate_limit", "overloaded", "network")
def _stopped_on(summary: dict, state: str | None) -> dict | None:
"""The API error a stopped run ended on, when sending again is the way
back — the list card's *Resume* chip: ``{kind, resetsAt}`` (``resetsAt``
= when a usage limit reopens, epoch s, or None). None while it runs, or
when it ended any other way (a model answered after the error)."""
err = summary.get("lastApiError")
if state == "running" or not err or err.get("kind") not in RESUMABLE_ERRORS:
return None
at = err.get("resetsAt")
if at is None and err["kind"] == "rate_limit":
# Indexed before the parser stamped it: read it off the message.
at = limit_resets_at(err.get("message"), err.get("at"))
return {"kind": err["kind"], "resetsAt": at}
def _after(later: str | None, earlier: str | None) -> bool:
"""True when ``later`` is clearly (>10s slack) after ``earlier``."""
if not later or not earlier:
return False
try:
a = datetime.datetime.fromisoformat(later.replace("Z", "+00:00"))
b = datetime.datetime.fromisoformat(earlier.replace("Z", "+00:00"))
except ValueError:
return False
return (a - b).total_seconds() > 10
def _outlived_exit(exited_at: str | None, ended_at: str | None) -> bool:
"""True when the transcript's last activity is clearly *after* the recorded
process exit (>10s slack) — the session kept going in a run the sidecar
never saw (a terminal or remote-control turn), so the exit-time "finished"
stamp is stale and must not be trusted."""
return _after(ended_at, exited_at)
def _build_subagent_activity(deps: AppState) -> dict[str, str]:
out: dict[str, str] = {}
for path, s in deps.store.all_summaries():
if "/subagents/" not in path:
continue
sid, ended = s.get("sessionId"), s.get("endedAt")
if sid and ended and ended > out.get(sid, ""):
out[sid] = ended
return out
_subagent_activity_memo = _Memo(_build_subagent_activity)
def _subagent_activity(deps: AppState, summary: dict) -> str | None:
"""When a conversation's subagents last wrote: the newest ``endedAt`` of
the sidechains sharing its sessionId (every depth lives in the one
``subagents/`` dir). Only looked up for a root with an open Task/Agent
call — the one case it can change the state — from a map memoized on the
summaries version, so a card pays a dict lookup, not a transcript read."""
if summary.get("isSidechain") or not summary.get("runningAgents"):
return None
by_sid = _subagent_activity_memo.get(
(id(deps.store), deps.store.summaries_version), deps)
return by_sid.get(summary.get("sessionId") or "")
def _subagents_live(summary: dict, m: dict, subagents_at: str | None) -> bool:
"""True while a subagent is still at work after the main thread went quiet.
The main transcript stops moving when its turn ends — an orchestrator
waiting on background agents, a blocking Task, a headless run the CLI
keeps alive for them — so neither its recency nor its trailing marker
says anything about them. An open Task/Agent call whose agents wrote
after the main thread's last record (and after a recorded process exit:
agents killed with their run wrote nothing later) keeps the conversation
running, for as long as those writes stay inside the recency window. An
agent that died mid-call leaves its call open forever; going quiet is
what lets it go."""
if not subagents_at or not summary.get("runningAgents"):
return False
if _auto_state(subagents_at) != "running":
return False
return all(_after(subagents_at, t)
for t in (summary.get("endedAt"), m.get("exitedAt")) if t)
def _awaits_agents(summary: dict) -> bool:
"""The turn ended with a background agent still at work: its call is
open, and the CLI waits for it before the run can end."""
return any(a.get("background") for a in summary.get("runningAgents") or [])
def _resolve_state(summary: dict, m: dict, notified: str | None,
subagents_at: str | None = None,
run_alive: bool = False, run_held: bool = False,
children_running: bool = False) -> str:
"""Decide a conversation's lifecycle state.
The ``worktree``/``select-project`` skills stamp ``state=running`` but
nothing ever clears it, so finished conversations get stuck "running". We
treat an explicit ``running`` as trustworthy only while activity is recent;
once a conversation has both sent a notification and ended its last message
with the ``DONE`` marker (or the `complete` skill's ``COMPLETED`` marker —
see ``_COMPLETED_RE``; that pass continues the same session, so its own
reply becomes the transcript's last message and overwrites ``doneMarker``),
it is finished regardless of the recency window.
The everyday end is the transcript's own: a turn that ended
(``turnEnded`` — the CLI's ``stop_hook_summary`` / ``turn_duration`` record,
a harness mirror's ``turn_end``, with nothing after it) is ``finished``,
DONE or not, until a new turn starts.
The exit watcher (``_watch_sidecar_runs``) stamps ``finished`` the moment a
sidecar-launched run's process dies — what covers a transcript with no
turn-end record (an older CLI, a run killed mid-turn).
The closing push (``notify --final``) stamps ``finished`` too, but 8–20 s
*before* Claude writes the sign-off it precedes — a stamp with no process
exit behind it waits for the turn to end (that DONE/COMPLETED, the
turn-end record, the exit or the recency window), so the viewer never
folds a thread missing its last message.
A run whose transcript ends on a ``[Request interrupted by user]`` marker is
reported as ``interrupted`` (a terminal state, so it wins over recency and
over a stale ``running`` stamp); one ending on a ``No response requested.``
reply is reported as ``paused``. A run that parked itself waiting on a
trigger (a trailing ``ScheduleWakeup``/``Monitor`` — see the parser's
``waiting_trailing``) is ``paused`` too, instead of sitting on a "running"
badge while nothing happens. Other explicit states (e.g. ``review``) are
always honoured.
Running subagents outrank the main thread's recency, its trailing markers
and the exit stamp: ``subagents_at`` is when they last wrote (see
``_subagents_live``). A turn that ended with a background agent still at
work isn't ``turnEnded`` (the parser): the run waits on it. While the
hub-launched run's process is alive (``run_alive`` — ``core.liveruns``)
that's ``running`` however quiet the agent is (a long command, a form
wait); a terminal session has no process to go by, so its quiet agent
keeps it running for the recency window only.
So does a live run whose turn the runner's Stop guard holds for a
background shell (``run_held`` — ``core.liveruns.held``): the turn
ended, but the run waits on that shell (a deploy, a build) and carries on
when it ends — a deploy waited on past the recency window used to read
``finished`` with its result still to come.
A hub child still at work that will report back (``children_running`` —
``meta.reportTo`` armed, conversations/spawned.py) keeps it ``running``
like a native subagent: over a ``finished`` / ``paused`` end (the parent
waits on its report), never over an interrupt or an explicit ``review``.
"""
if m.get("state") in (None, "running", "finished") and (
_subagents_live(summary, m, subagents_at)
or (run_alive and (run_held or _awaits_agents(summary)))):
return "running"
auto = _auto_state(summary.get("endedAt")) # running if recent, else finished
# A trailing interrupt marker in the transcript is authoritative: the run
# was stopped by the user (Esc, or the interrupt button in this viewer).
if summary.get("interruptedByUser"):
return "interrupted"
if children_running and m.get("state") in (None, "running", "finished", "paused"):
return "running"
# A trailing "No response requested." reply (a queued/resume prompt that had
# nothing to answer) leaves the run paused rather than finished.
if summary.get("pausedByUser"):
return "paused"
if (summary.get("doneMarker") or summary.get("completedMarker")) and notified:
return "finished"
explicit = m.get("state")
# An exit-time "finished" is trusted only while the transcript hasn't
# moved past that exit; later activity means the session continued outside
# the sidecar — fall back to the recency heuristic instead. Without an exit
# at all it is the closing push's stamp, landed while the run is still
# writing its sign-off (the marker check above ends the wait).
if explicit == "finished" and (not m.get("exitedAt") or _outlived_exit(
m.get("exitedAt"), summary.get("endedAt"))):
explicit = None
if explicit in (None, "running"):
# Claude scheduled a wake-up / blocked on a Monitor and the turn ended:
# the run is idle until the trigger fires, however recent its activity.
if summary.get("waitingForTrigger"):
return "paused"
if summary.get("turnEnded"):
return "finished"
return auto # stale/absent "running" → fall back to recency
return explicit
def _scheduled_ref(ref: dict | None, started_at: str | None) -> dict | None:
"""``meta.scheduled`` with ``manual`` worked out for sessions stamped
before the scheduler recorded it: one that started ahead of its time was
the modal's *Start now* (the scheduler only fires once the time is up)."""
if not ref or "manual" in ref:
return ref
return {**ref, "manual": _after(ref.get("shouldStartAt"), started_at)}
def _merge_worktrees(*sources) -> list[dict]:
"""Union worktree records from several sources, keyed by directory basename.
Each source is a list of ``{name, dir, project?, createdAt, removedAt}``
(from the transcript parse and/or the live sidecar). Same ``dir`` → one
entry: earliest ``createdAt`` and latest ``removedAt`` win, and a real short
``name`` beats a fallback that equals the dir. ``project`` — the repo it is
a worktree of — is the one the parse read off ``-p``, else inferred from the
dir (projects.worktree_project), so a summary parsed before the field
existed gets one too. Ordered by creation (unknown-created last)."""
by_dir: dict[str, dict] = {}
for src in sources:
for e in src or []:
d = (e.get("dir") or e.get("name") or "").strip()
if not d:
continue
cur = by_dir.get(d)
if cur is None:
by_dir[d] = {"name": e.get("name") or d, "dir": d,
"project": e.get("project"),
"createdAt": e.get("createdAt"),
"removedAt": e.get("removedAt")}
continue
nm = e.get("name")
if nm and nm != d and (not cur["name"] or cur["name"] == d):
cur["name"] = nm
if e.get("project") and not cur.get("project"):
cur["project"] = e["project"]
for k, pick in (("createdAt", min), ("removedAt", max)):
vals = [v for v in (cur.get(k), e.get(k)) if v]
cur[k] = pick(vals) if vals else None
for w in by_dir.values():
if not w.get("project"):
w["project"] = projects_mod.worktree_project(w["dir"])
return sorted(by_dir.values(), key=lambda w: (w.get("createdAt") is None,
w.get("createdAt") or ""))
def _conv_title(deps: AppState, summary: dict, meta: dict | None = None) -> str | None:
"""The conversation's display title.
A session can rename itself (``conv-meta title "…"``) once it knows what it
is actually doing — the goal-keeper does this after picking its item, so its
card reads "Add a Work button to the Goals page" rather than the generic
spawn prompt it was launched with. That sidecar title wins (a manual rename
included), then the **resource title** of a work conversation
(``INS-2229 · <issue> · #13722`` — resource_view.py), then the parsed one
(Claude's ``ai-title``, else the first user message). ``meta`` is the
already-merged ``_conv_meta`` when the caller has it.
A subagent shares its parent's sessionId, so that sidecar (and the
resource title mined from it) is the **root's**: a sidechain is always
named by its own task — its first message — wherever it shows up (a
nested agent's parent chain, a skill prompt's source)."""
if summary.get("isSidechain"):
return summary.get("title")
sid = summary.get("sessionId") or ""
m = deps.meta_store.peek(sid)
if m.get("title"):
return m["title"]
if meta is not None:
rt = meta.get("resourceTitle")
else:
rt = resource_view.for_conversation(
deps, summary, m, m.get("worker") or m.get("workerSource"))[1]
return rt or summary.get("title")
_UNSET = object()
def _slim_notifications(notes: list | None) -> list[dict]:
if not notes:
return []
return [
{
"title": n.get("title") or "",
"body": "" if n.get("title") else (n.get("body") or "")[:160],
"at": n.get("at"),
}
for n in notes
]
def _slim_summary(summ) -> dict | None:
if isinstance(summ, dict):
return {"at": summ.get("at")}
return None
def _conv_meta(deps: AppState, summary: dict, *, slim: bool = False,
sub_at=_UNSET) -> dict:
"""Merge a conversation's parsed auto fields with its action sidecar."""
sid = summary.get("sessionId") or ""
m = deps.meta_store.peek(sid) # read-only — never mutated below
account = accounts_mod.resolve(summary, m)
worker = m.get("worker") or m.get("workerSource")
# The profile is the runner's (profiles/store.py): a personal task run on
# the lab on the work seat is a Personal conversation — and one a guest
# started is a Guests one, wherever it ran.
profile = deps.profile_store.of_meta(m, account)
# What it edited + what was stamped; on a worker, the projects deduced from
# where it wrote (projects/worker_projects.py). No project at all on the
# lab ⇒ it worked on the lab itself (a service, a skill, a script, a doc):
# the root project, so it stops falling out of every project-shaped view.
# Derived, never stored.
projects = worker_projects_mod.conversation_projects(deps, summary, m, profile)
# Homelab services touched by the conversation (mirrors ``projects``).
services = list(summary.get("servicesAuto") or [])
for s in (m.get("services") or []):
if s not in services:
services.append(s)
# Lifecycle stamps: the live sidecar (written by the skills) is authoritative;
# where it's empty we backfill from evidence mined out of the transcript.
auto = summary.get("lifecycleAuto") or {}
stamp = lambda k: m.get(k) or auto.get(k) # noqa: E731
notified = stamp("notified")
resources, resource_title = resource_view.for_conversation(deps, summary, m, worker)
rctx = resource_view.context(deps) if resources else None
subject_key, hue_key = (look_mod.subject(resources, rctx.registry.roles)
if rctx else (None, None))
look = look_mod.resolve(
m.get("look"),
sid=sid,
subject_key=subject_key,
seen=summary.get("endedAt"),
colors=getattr(deps, "look_colors", None),
auto=m.get("lookAuto"),
linear=rctx.metas.get(hue_key) if hue_key else None)
held = liveruns.held(sid)
resolved_sub_at = _subagent_activity(deps, summary) if sub_at is _UNSET else sub_at
return {
"state": _resolve_state(summary, m, notified,
resolved_sub_at,
liveruns.alive(sid), held is not None,
spawned_live.has_running_children(deps, sid)),
# The Stop guard holds the run's ended turn for a background shell
# ({since: epoch s, tasks: [ids]}) — the card's "waiting on a
# background shell" chip. None otherwise.
"held": held,
# Background tasks stopped from the app ({task id: epoch s},
# runs/bgtasks.py) — the Background shells card's "stopped by you".
"taskStops": m.get("taskStops") or None,
# What the lab's paid tools (toolproxy/) cost this conversation —
# {usd, calls, tools: {tool: calls}} — on top of `cost` (the model's):
# the card's tools chip. Stamped by the proxy on each metered call.
"tools": m.get("tools") or None,
# The custom sidecar title override, when set (the resolved top-level
# `title` already prefers it) — lets the UI tell a renamed card from an
# auto-titled one and offer "reset to auto title" in the rename dialog.
"title": m.get("title") or None,
# Who set it: "user" (the rename dialog — always wins), "agent"
# (`conv title`), "resources" (stamped once at the first resolve).
"titleSource": (m.get("titleSource") or None) if m.get("title") else None,
# The issues / PRs / branches / threads / links the conversation is
# about, primary first (resource_view.py) — only for conversations an
# active resource plugin's scope matches — and the title they make.
"resources": resources,
"resourceTitle": resource_title,
# The card's colour + action badge (conversations/look.py): what the
# session set with `conv look` over what derives — the colour of its
# Linear issue, an action guessed from the title.
"look": look,
"projects": projects,
"services": services,
# Git worktrees the conversation created/removed (with created/removed
# timestamps), merging the transcript parse with anything the worktree
# skill recorded live in the sidecar.
"worktrees": _merge_worktrees(summary.get("worktreesAuto"),
m.get("worktrees")),
"committed": stamp("committed"),
"pushed": stamp("pushed"),
"merged": stamp("merged"),
"deployed": stamp("deployed"),
"notified": notified,
"notifications": (_slim_notifications(m.get("notifications"))
if slim else (m.get("notifications") or [])),
# Hidden-from-list flag, toggled from the conversation card context menu.
"archived": bool(m.get("archived")),
# The hub archived it by itself ({kind: cron|test, at}) — see
# conversations/autoarchive.py — and the test flag it may go by.
"autoArchived": m.get("autoArchived") or None,
"test": bool(m.get("test")),
# Guests (users/): who started it (None = the owner) and who it is
# shared with. The list filter (users/access.filter_cards) reads these
# off the card, so they must ride along here.
"owner": m.get("owner") or None,
"participants": list(m.get("participants") or []),
# Which agent harness runs this session ("claude"/"pi"/"opencode"/"agy").
# Stamped by /api/spawn; an opencode session started in a terminal is
# known from its transcript (the mirror's records say so); anything
# else unstamped falls back to "claude" client-side.
"harness": m.get("harness") or summary.get("harness")
or (None if accounts_mod.harness_of(account) == "claude"
else accounts_mod.harness_of(account)),
# The thinking / `--effort` setting the session was spawned or last
# resumed with — what the resume composer's chips seed from. Declared on
# the schema all along but never emitted, so they always read "default".
"thinking": m.get("thinking"),
"effort": m.get("effort"),
# Which Claude account the session ran on / bills ("personal"/"work").
# Always resolved (accounts.resolve: spawn stamp → import source → cwd
# rule → default), so a terminal session is tagged too.
"account": account,
# The profile it belongs to — its runner's (an explicit ``profile``
# stamp pins it: the Orus tasks run on the lab before the Mac was
# paired). What the PWA's profile scope filters lists by.
"profile": profile,
# The paired worker (workers.py) the session runs on — launched there
# by the hub (``worker``) or mirrored from its terminal
# (``workerSource``). None = the host sidecar / a lab terminal.
"worker": worker,
# A guest computer's own terminal session the app mirrors
# (workers/terminal.py): "proxy" — it ran on ai-agent Claude — or
# "local" — on the guest's own login, synced. None otherwise.
"terminal": m.get("terminal"),
# Launched with --chrome (runs/service.py): the session drives the
# browser paired to its account — the conversation page's Browser dock
# and the resume box's badge key on it.
"chrome": bool(m.get("chrome")),
# Claude Code's Code Mode (beta): the session runs in it — the run
# said so (``meta.codeMode``, from the sidecar's banner read) or its
# transcript does (a terminal session started in it). Sticky: every
# turn resumes on the sidecar's pty wrapper. ``codeModeOff``: asked
# for, the CLI started without it — why (the thread's notice).
"codeMode": bool(m.get("codeMode") or summary.get("codeMode")),
"codeModeOff": (m.get("codeModeOff")
if not (m.get("codeMode") or summary.get("codeMode")) else None),
# Source conversation + message ordinal when this one is a fork.
"forkedFrom": m.get("forkedFrom"),
# The conversation that started this one ({sessionId, depth, at}),
# when a run spawned it with the `ai-agent` CLI (runs/children.py).
"spawnedBy": m.get("spawnedBy"),
# The AI app that started it through the MCP server ({kind: "mcp",
# app, connection} — mcpserver/routes.py): the "via Claude.ai" pill.
"via": m.get("via"),
# The cron job that spawned this session ({id, name}), if any — the
# viewer tags the conversation and links back to Settings → Cron.
"cron": m.get("cron"),
# Set when a scheduled conversation ("Send later") started this
# session ({id, scheduledAt, shouldStartAt, manual}) — the card's
# badge, which a by-hand start (`manual`) doesn't show.
"scheduled": _scheduled_ref(m.get("scheduled"), summary.get("startedAt")),
# The agent definition this session was launched from ({name, at}) by
# the agent page's "Run now" — the manual sibling of `cron`, and what
# puts the run in that agent's history.
"agentRun": m.get("agentRun"),
# When the `complete` skill's end-of-task pass ran on this session:
# its reply signs off with COMPLETED instead of DONE (the parser's
# ``completedMarker``), so the marker on the last message *is* the
# record — no sidecar stamp to keep in sync. The viewer turns it into
# the COMPLETED seal on the card.
"completedAt": (summary.get("endedAt")
if summary.get("completedMarker") else None),
# The conversation's published summary, written by that same pass
# ({markdown, at}) and rendered under the thread (see scaffold.py).
# List cards omit the multi-KB markdown body and keep only `{at}`.
"summary": (_slim_summary(m.get("summary")) if slim
else (m.get("summary") or None)),
}
# ── accounts: which Claude subscription each run bills (accounts.py) ─────────
# Every aggregate the dashboards read (activity, projects, skills, agents) is
# split by account, and the default ("totals") view leaves out accounts flagged
# ``excludeFromTotals`` — the work seat isn't the owner's money. Resolving an
# account is a meta peek + a cwd split per summary; memoized on the (summaries,
# sidecar) versions since both feed it.
_acct_cache: tuple[tuple[int, int], list] | None = None
_acct_lock = threading.Lock()
def _account_of(deps: AppState, summary: dict) -> str:
"""A run's account. A subagent shares its parent's sessionId (so its
metadata) and cwd, so it resolves to the parent's account."""
return accounts_mod.resolve(
summary, deps.meta_store.peek(summary.get("sessionId") or ""))
def _profile_of(deps: AppState, summary: dict) -> str:
"""A run's profile: an explicit stamp, Guests for a guest's run, else its
runner's (a subagent shares its parent's sessionId, so its metadata),
else where its account is a ★ (``ProfileStore.of_meta``)."""
m = deps.meta_store.peek(summary.get("sessionId") or "")
return deps.profile_store.of_meta(m, accounts_mod.resolve(summary, m))
def _account_project_fallback(deps: AppState, summary: dict) -> str | None:
"""The project a project-less conversation is attributed to: its
profile's first project (Settings → Profiles) — None keeps the root."""
return deps.profile_store.home_project(_profile_of(deps, summary))
def _summaries_with_account(deps: AppState) -> list[tuple[str, dict, str]]:
"""``store.all_summaries()`` with each run's account attached (same order)."""
global _acct_cache
key = (deps.store.summaries_version, deps.meta_store.version)
with _acct_lock:
if _acct_cache and _acct_cache[0] == key:
return _acct_cache[1]
out = [(p, s, _account_of(deps, s)) for p, s in deps.store.all_summaries()]
with _acct_lock:
_acct_cache = (key, out)
return out
def _summaries_for(deps: AppState, account: str | None) -> list[tuple[str, dict]]:
"""The summaries an ``?account=`` view covers (``ProfileStore.selector``:
unset = the aggregated totals, i.e. without the excluded accounts;
``profile:<id>`` = a profile's conversations on its own seats, plus the
guests' ones billed to those seats; ``guest:<uid>`` narrows the Guests
profile to those guests)."""
sel = deps.profile_store.selector(account)
if not getattr(sel, "by_profile", False):
return [(p, s) for p, s, a in _summaries_with_account(deps, ) if sel(a)]
out = []
for p, s, a in _summaries_with_account(deps, ):
m = deps.meta_store.peek(s.get("sessionId") or "")
if sel(a, deps.profile_store.of_meta(m, a), profiles_mod.guest_owner(m, a)):
out.append((p, s))
return out
def _by_account(rows) -> dict[str, dict]:
"""``{account: {cost, tokens, conversations}}`` over ``(path, summary,
account)`` rows — every run's spend (subagents included, as separate
summaries), conversations counted top-level only. Every profile appears,
zeros included, so the UI never has to guess whether a key is missing."""
out = {a: {"cost": 0.0, "tokens": 0, "conversations": 0}
for a in accounts_mod.ids()}
for _p, s, a in rows:
if not s.get("messages"):
continue
e = out.setdefault(a, {"cost": 0.0, "tokens": 0, "conversations": 0})
e["cost"] += float(s.get("cost") or 0.0)
e["tokens"] += int(s.get("tokens") or 0)
if not s.get("isSidechain"):
e["conversations"] += 1
return out