Work Resources becomes generic core composition over declarative plugin
`resources[]`, ahead of the `github` / `linear` / `slack` plugins (Wave 2B-2).
- Core knows only `branch` and `url` (cli/resource_urls.py). Every link is
mined raw, so the plugins' kinds apply at view time: installing a plugin
lights up the whole archive with zero re-parse. Notion links are plain
`url` pills.
- New backend/plugins/resources.py: PluginResourceRegistry compiled from the
owner's active plugins' `resources[]` + each plugin's settings (workers,
cwdGlobs, notifPills, channelMap, {config.*} templates); cached on the new
PluginStore.version and kept by identity while unchanged.
- manifest.py: expanded, ReDoS-checked `resources[]` (urlRegex, idRegex,
id/url/label templates, titleToken, bareKeyRegex + team gate,
branchKeyPattern cross-links, ignoreUrlRegex, toolExtractors[], icon,
color, stateTones, clickAction, priority, hueRole); the v3 shape and the
approval fingerprint stay as they were.
- ResourceMiner runs declarative toolExtractors / bare keys in-process (no
subprocess); legacy resourcesAuto / resourceTeams / slackChannels still read.
- resource_view: per-plugin scope, branchKeyPattern cross-linking, priority
primary, generic `<lead> · <title> · <shade>` title; Context cached on
(summaries, meta, registry) with per-transcript memo.
- look.subject → generic (hueKey, shadeKey) from hueRole; past.py generic.
- conv add/rm send raw links / keys; the hub's registry reads them.
- Removed: conversations/pr_state.py, sidecar/routes_gh.py (/gh/pr-states),
deps.pr_states, Profile.resources + Orus defaults (dropped on load),
GET /api/profiles/resource-directory, ProfileResourcesEditor + the
Profile page's Tracking tab.
- Frontend pills read `ui.resources` descriptors (icon, tone, stateTones,
clickAction); historical kinds keep a fallback. ResourceKind widens to str.
- Fixture manifests + test kit for the three plugins in
backend/fixtures/resource_plugins/.
OpenAPI not re-dumped (coordinator does it after Batch 2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
601 lines
26 KiB
Python
601 lines
26 KiB
Python
"""How a conversation's resources show on its card.
|
||
|
||
Two sources merge, keyed ``kind:id``:
|
||
|
||
* ``summary.resourcesAuto`` — what the parser mined (resources.py): free,
|
||
deterministic, and the backfill of every past conversation;
|
||
* ``meta.resources`` — what the session recorded itself (the ``conv`` CLI)
|
||
or the owner added; their fields win, and their ``primary`` is the primary.
|
||
|
||
Every record goes through the **plugin resource registry**
|
||
(``plugins/resources.py``) at view time: a raw ``url`` an active plugin
|
||
matches becomes that plugin's kind (zero re-parse: installing the ``github``
|
||
plugin turns every PR link already in the archive into a PR pill), an id is
|
||
completed from the plugin's settings (``#13722`` → its repo, a key → its
|
||
workspace's link), a kind no active plugin declares falls back to a plain
|
||
link. Then, per conversation:
|
||
|
||
* a plugin's kinds show only where **its own scope** (its ``workers`` +
|
||
``cwdGlobs`` settings — empty = everywhere) matches; the core ``branch`` /
|
||
``url`` pills where at least one plugin's does. What the session recorded
|
||
itself always shows;
|
||
* bare keys only for the teams seen in real links (``UTF-8`` is no issue);
|
||
* ``branchKeyPattern`` cross-links: the issue a branch / a PR's head names
|
||
(``ins-2229-…`` → ``INS-2229``) — between plugins that never import each
|
||
other;
|
||
* labels from the names learned (Slack channels: the plugin's ``channelMap``
|
||
› learned from transcripts › ``conv add --label``); several threads of one
|
||
channel get their date;
|
||
* one primary — the lowest ``priority`` first-turn resource — and a title
|
||
built from the **first-turn** resources only, so it doesn't drift as the
|
||
thread grows: ``<primary token> · <title> · <shade token>``
|
||
(``INS-2229 · Separate tenant · #13722``).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
import threading
|
||
|
||
from conversations import ids
|
||
from conversations import look as look_mod
|
||
from conversations.resources import names_of, ru
|
||
from plugins import resources as plugin_resources
|
||
|
||
# Fields a card's resource carries (the API's `Resource`).
|
||
OUT_FIELDS = ("kind", "id", "url", "label", "title", "state", "checks",
|
||
"reviewDecision", "primary", "source", "via", "firstSeen",
|
||
"firstTurn")
|
||
MAX_ON_CARD = 12
|
||
_META_FIELDS = ("labels", "project", "team")
|
||
|
||
|
||
def _derive(reg, summary: dict) -> tuple:
|
||
"""What one transcript teaches every card: (teams by kind, names, titles,
|
||
metas, xrefs). Pure — cached per summary object (:class:`_PerSummary`)."""
|
||
teams: dict[str, set] = {}
|
||
names = names_of(summary)
|
||
titles: dict[str, str] = {}
|
||
metas: dict[str, dict] = {}
|
||
xrefs: dict[str, list] = {}
|
||
for r in summary.get("resourcesAuto") or ():
|
||
n = reg.normalize(r) if reg else None
|
||
if n is None:
|
||
continue
|
||
d = reg.by_kind.get(n["kind"])
|
||
if d is not None and d.team_group and not n.get("bare") and n.get("team"):
|
||
teams.setdefault(n["kind"], set()).add(n["team"])
|
||
if n.get("headRefName"):
|
||
xrefs.setdefault(ru.key(n), []).append(n["headRefName"])
|
||
for k, v in (summary.get("resourceInfo") or {}).items():
|
||
if v.get("title"):
|
||
titles.setdefault(k, v["title"])
|
||
m = {f: v[f] for f in _META_FIELDS if v.get(f)}
|
||
if m:
|
||
metas[k] = m
|
||
x = ([v["headRefName"]] if v.get("headRefName") else []) + list(v.get("xref") or ())
|
||
if x:
|
||
xrefs.setdefault(k, []).extend(x)
|
||
return teams, names, titles, metas, xrefs
|
||
|
||
|
||
class _PerSummary:
|
||
"""``_derive`` per transcript, kept while its summary object and the
|
||
registry hold (the store replaces a changed summary, never mutates it)."""
|
||
|
||
def __init__(self):
|
||
self._memo: dict = {}
|
||
|
||
def get(self, path, summary: dict, reg) -> tuple:
|
||
hit = self._memo.get(path)
|
||
if hit is not None and hit[0] is summary and hit[1] is reg:
|
||
return hit[2]
|
||
out = _derive(reg, summary)
|
||
self._memo[path] = (summary, reg, out)
|
||
return out
|
||
|
||
def keep_only(self, paths: set) -> None:
|
||
"""Forget transcripts the last full pass didn't see (deleted ones)."""
|
||
if len(self._memo) > len(paths):
|
||
self._memo = {p: v for p, v in self._memo.items() if p in paths}
|
||
|
||
|
||
_per_summary = _PerSummary()
|
||
|
||
|
||
class Context:
|
||
"""What every card's view shares, built once per (summaries, meta,
|
||
registry) version: the active kinds, the teams seen in real links, the
|
||
names learned anywhere, the titles / metadata / cross-references any
|
||
lookup found in the archive."""
|
||
|
||
def __init__(self, registry, teams: dict[str, set] | None = None,
|
||
names: dict[str, str] | None = None,
|
||
titles: dict[str, str] | None = None,
|
||
metas: dict[str, dict] | None = None,
|
||
xrefs: dict[str, list] | None = None):
|
||
self.registry = registry
|
||
self.teams = {k: frozenset(v) for k, v in (teams or {}).items()}
|
||
# The registry's channelMap settings win over what was learned.
|
||
self.names = {**(names or {}), **registry.names}
|
||
# kind:id → a title some lookup found (get_issue, gh pr view, conv add)
|
||
# anywhere in the archive — beats a URL / branch slug's guess.
|
||
self.titles = titles or {}
|
||
# kind:id → {labels, project, team} a lookup said — what the card's
|
||
# work icon is drawn from (look.py) and Settings → Tags lists.
|
||
self.metas = metas or {}
|
||
# kind:id → strings that may name another resource (a PR's head
|
||
# branch, what its body closes): `branchKeyPattern` cross-links.
|
||
self.xrefs = xrefs or {}
|
||
|
||
def same(self, other: "Context") -> bool:
|
||
"""Built from the same inputs (everything else derives from these)."""
|
||
return (self.registry is other.registry and self.teams == other.teams
|
||
and self.names == other.names and self.titles == other.titles
|
||
and self.metas == other.metas and self.xrefs == other.xrefs)
|
||
|
||
|
||
_ctx_cache: tuple[tuple, Context] | None = None
|
||
_ctx_lock = threading.Lock()
|
||
|
||
|
||
def context(deps) -> Context:
|
||
global _ctx_cache
|
||
reg = plugin_resources.registry(deps)
|
||
key = (deps.store.summaries_version, deps.meta_store.version, id(reg), reg.version)
|
||
hit = _ctx_cache
|
||
if hit and hit[0] == key:
|
||
return hit[1]
|
||
with _ctx_lock:
|
||
hit = _ctx_cache
|
||
if hit and hit[0] == key:
|
||
return hit[1]
|
||
teams: dict[str, set] = {}
|
||
names: dict[str, str] = {}
|
||
titles: dict[str, str] = {}
|
||
metas: dict[str, dict] = {}
|
||
xrefs: dict[str, list] = {}
|
||
if reg:
|
||
seen: set = set()
|
||
for p, s in deps.store.all_summaries():
|
||
seen.add(p)
|
||
t, n, ti, me, x = _per_summary.get(p, s, reg)
|
||
for k, v in t.items():
|
||
teams.setdefault(k, set()).update(v)
|
||
for cid, name in n.items():
|
||
names.setdefault(cid, name)
|
||
for k, v in ti.items():
|
||
titles.setdefault(k, v)
|
||
for k, v in me.items():
|
||
cur = metas.setdefault(k, {})
|
||
for f, fv in v.items():
|
||
cur.setdefault(f, fv)
|
||
for k, v in x.items():
|
||
lst = xrefs.setdefault(k, [])
|
||
lst.extend(t for t in v if t not in lst)
|
||
_per_summary.keep_only(seen)
|
||
for _sid, m in deps.meta_store.items():
|
||
for r in m.get("resources") or ():
|
||
n = reg.normalize(r)
|
||
if n is None:
|
||
continue
|
||
d = reg.by_kind.get(n["kind"])
|
||
if d is not None and d.team_group and n.get("team"):
|
||
teams.setdefault(n["kind"], set()).add(n["team"])
|
||
if d is not None and d.names_group and r.get("label"):
|
||
# `conv add --label "#prod"`: a name the session gave.
|
||
v = (d.id_groups(n["id"]) or {}).get(d.names_group)
|
||
lab = str(r["label"]).lstrip("#@")
|
||
if v and lab and lab != v and not lab.startswith(v):
|
||
names[v] = lab
|
||
if r.get("title"):
|
||
titles[ru.key(n)] = r["title"] # recorded wins
|
||
ctx = Context(reg, teams, names, titles, metas, xrefs)
|
||
# Same content as the last build (most writes teach it nothing new):
|
||
# keep that object — the list's per-card cache keys the cards built
|
||
# from it on its identity (conversations/catalog.py).
|
||
if hit and hit[1].same(ctx):
|
||
ctx = hit[1]
|
||
_ctx_cache = (key, ctx)
|
||
return ctx
|
||
|
||
|
||
def _complete(r: dict, ctx: Context) -> dict:
|
||
"""Labels (names learned), titles found elsewhere in the archive."""
|
||
reg = ctx.registry
|
||
d = reg.by_kind.get(r.get("kind"))
|
||
if d is not None:
|
||
r = d.finalize(r, names=ctx.names)
|
||
if not r.get("title"):
|
||
r["title"] = ctx.titles.get(ru.key(r)) or r.get("slugTitle")
|
||
if not r.get("label"):
|
||
r["label"] = str(r.get("id"))
|
||
return r
|
||
|
||
|
||
def _keep(r: dict, ctx: Context, scoped: frozenset, in_scope: bool,
|
||
recorded: bool) -> bool:
|
||
kind = r["kind"]
|
||
if recorded:
|
||
return True
|
||
if kind in plugin_resources.CORE_KINDS:
|
||
return in_scope
|
||
if kind not in scoped:
|
||
return False
|
||
d = ctx.registry.by_kind.get(kind)
|
||
if r.get("bare") and d is not None and d.team_group \
|
||
and str(r.get("team") or "").upper() not in ctx.teams.get(kind, ()):
|
||
return False # `UTF-8`, `D541-9`: no real link ever named that team
|
||
return True
|
||
|
||
|
||
def merge(auto: list[dict], recorded: list[dict], hidden: list[str], ctx: Context,
|
||
scoped: frozenset, in_scope: bool) -> list[dict]:
|
||
"""The card's resources, primary first, then first-turn, then by when
|
||
they were first seen."""
|
||
reg = ctx.registry
|
||
out: dict[str, dict] = {}
|
||
for r in auto:
|
||
n = reg.normalize(r)
|
||
if n is None or not _keep(n, ctx, scoped, in_scope, False):
|
||
continue
|
||
k = ru.key(n)
|
||
out[k] = ru.merge(out[k], n) if k in out else n
|
||
out[k].pop("primary", None)
|
||
prim = None
|
||
for r in recorded:
|
||
n = reg.normalize(r)
|
||
if n is None:
|
||
continue
|
||
k = ru.key(n)
|
||
cur = out.get(k)
|
||
out[k] = ru.merge(cur, n) if cur else dict(n)
|
||
out[k].pop("bare", None)
|
||
if cur and cur.get("source") == "auto":
|
||
out[k]["source"] = r.get("source") or "agent"
|
||
out[k]["via"] = cur.get("via")
|
||
if r.get("primary"):
|
||
prim = k
|
||
# Cross-links: what a branch / a PR's head names in another plugin's
|
||
# kind — first-turn when the record naming it is.
|
||
if any(d.kind in scoped for d in reg.branch_defs):
|
||
for k, r in list(out.items()):
|
||
texts = [r["id"]] if r["kind"] == "branch" else (
|
||
([r["headRefName"]] if r.get("headRefName") else []) + ctx.xrefs.get(k, []))
|
||
for s in texts:
|
||
for lr in reg.cross_links(s, skip=r["kind"]):
|
||
lr.update({"source": "auto", "via": "branch" if r["kind"] == "branch"
|
||
else "xref", "firstSeen": r.get("firstSeen")})
|
||
if r.get("firstTurn"):
|
||
lr["firstTurn"] = True
|
||
if not _keep(lr, ctx, scoped, in_scope, False):
|
||
continue
|
||
lk = ru.key(lr)
|
||
if lk in out:
|
||
if r.get("firstTurn"):
|
||
out[lk]["firstTurn"] = True
|
||
else:
|
||
out[lk] = lr
|
||
for k in hidden or ():
|
||
out.pop(k, None)
|
||
rs = [_complete(r, ctx) for r in out.values()]
|
||
_date_repeated(rs, reg)
|
||
for r in rs:
|
||
r["primary"] = False
|
||
pk = prim if prim and any(ru.key(r) == prim for r in rs) else _pick_primary(rs, reg)
|
||
rs.sort(key=lambda r: (ru.key(r) != pk, not r.get("firstTurn"),
|
||
r.get("firstSeen") or ""))
|
||
if rs and pk and ru.key(rs[0]) == pk:
|
||
rs[0]["primary"] = True
|
||
return [{f: r[f] for f in OUT_FIELDS if r.get(f) not in (None, "", False)}
|
||
for r in rs]
|
||
|
||
|
||
def _date_repeated(rs: list[dict], reg) -> None:
|
||
"""Several threads in one channel read ``#tech-alerts · 13 Oct`` — three
|
||
identical ``#tech-alerts`` pills say nothing (``dateGroup``)."""
|
||
by_label: dict[tuple, list[dict]] = {}
|
||
for r in rs:
|
||
d = reg.by_kind.get(r.get("kind"))
|
||
if d is not None and d.date_group:
|
||
by_label.setdefault((r["kind"], r.get("label") or ""), []).append(r)
|
||
for (_kind, label), group in by_label.items():
|
||
if len(group) < 2:
|
||
continue
|
||
for r in group:
|
||
dt = reg.by_kind[r["kind"]].date_of(r)
|
||
if dt is not None:
|
||
r["label"] = f"{label} · {dt.day} {dt.strftime('%b')}"
|
||
|
||
|
||
def _priority(r: dict, reg) -> int | None:
|
||
d = reg.by_kind.get(r.get("kind"))
|
||
return d.priority if d is not None else None
|
||
|
||
|
||
def _pick_primary(rs: list[dict], reg) -> str | None:
|
||
"""The first-turn plugin resource of the lowest ``priority`` (an issue
|
||
before its PR before a thread), else the same over the whole
|
||
conversation; else the first."""
|
||
ft = [r for r in rs if r.get("firstTurn")]
|
||
for pool in (ft, rs):
|
||
hit = sorted((r for r in pool if _priority(r, reg) is not None),
|
||
key=lambda r: (_priority(r, reg), r.get("firstSeen") or ""))
|
||
if hit:
|
||
return ru.key(hit[0])
|
||
return ru.key(rs[0]) if rs else None
|
||
|
||
|
||
def _names(text: str | None, tokens: list[str]) -> bool:
|
||
"""Whether a title already says which resource it is about."""
|
||
t = (text or "").lower()
|
||
for tok in tokens:
|
||
tok = (tok or "").strip().lstrip("#").lower()
|
||
if tok and re.search(rf"(?<![\w-]){re.escape(tok)}(?![\w-])", t):
|
||
return True
|
||
return False
|
||
|
||
|
||
def title_for(resources: list[dict], fallback: str | None, reg) -> str | None:
|
||
"""The resource title, from first-turn resources only:
|
||
``<lead> · <title> · <shade>`` — the lead is the first-turn plugin
|
||
resource of the lowest priority, the shade the first first-turn
|
||
``hueRole: shade`` one of another kind (``INS-2229 · <issue title> ·
|
||
#13722``; ``#13722 · <PR title>`` for a PR alone; ``#channel · <ai
|
||
title>`` for a thread). None when the first turn named no plugin
|
||
resource, or when the AI title already names it and nothing better is
|
||
known. A primary the session *recorded* counts as first-turn: ``conv add
|
||
--primary`` says which one the conversation is about."""
|
||
ft = [r for r in resources if r.get("firstTurn")
|
||
or (r.get("primary") and r.get("source") != "auto")]
|
||
ft = [r for r in ft if _priority(r, reg) is not None]
|
||
if not ft:
|
||
return None
|
||
ft.sort(key=lambda r: (_priority(r, reg), r.get("firstSeen") or ""))
|
||
lead = None
|
||
for r in ft:
|
||
tok = reg.by_kind[r["kind"]].token(r)
|
||
if tok:
|
||
lead = (r, tok)
|
||
break
|
||
if lead is None:
|
||
return None
|
||
lr, ltok = lead
|
||
shade = None
|
||
if reg.roles.get(lr["kind"]) != "shade":
|
||
for r in ft:
|
||
if r["kind"] != lr["kind"] and reg.roles.get(r["kind"]) == "shade":
|
||
tok = reg.by_kind[r["kind"]].token(r)
|
||
if tok:
|
||
shade = (r, tok)
|
||
break
|
||
title = lr.get("title") or (shade[0].get("title") if shade else None)
|
||
if not title and _names(fallback, [ltok, lr.get("id")] + ([shade[1]] if shade else [])):
|
||
return None # the AI title already says it: prefixing would say it twice
|
||
segs = [ltok, title or fallback, shade[1] if shade else None]
|
||
out = " · ".join(s for s in segs if s and s.strip())
|
||
return out[:160] or None
|
||
|
||
|
||
def for_conversation(deps, summary: dict, meta: dict,
|
||
worker: str | None) -> tuple[list[dict], str | None]:
|
||
"""``(resources, resource title)`` for one conversation — ``([], None)``
|
||
unless an active plugin's scope matches it (or the session recorded some)."""
|
||
if not summary.get("resourcesAuto") and not meta.get("resources"):
|
||
return [], None # most conversations: nothing to look up
|
||
ctx = context(deps)
|
||
reg = ctx.registry
|
||
scoped = reg.scoped_kinds(worker, summary.get("cwd"))
|
||
in_scope = bool(scoped)
|
||
if not in_scope and not meta.get("resources"):
|
||
return [], None
|
||
rs = merge(summary.get("resourcesAuto") or [] if in_scope else [],
|
||
meta.get("resources") or [], meta.get("resourcesHidden") or [],
|
||
ctx, scoped, in_scope)
|
||
title = title_for(rs, summary.get("title"), reg)
|
||
return rs[:MAX_ON_CARD], title
|
||
|
||
|
||
# ── recording (POST /api/conversation-meta, the outbox's `meta` items) ──────
|
||
_RECORD_SOURCES = ("agent", "user")
|
||
_TEXT_MAX = {"label": 80, "title": 300, "state": 40, "channel": 40, "ts": 20,
|
||
"repo": 120}
|
||
_KIND_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")
|
||
|
||
|
||
def _shape(r: dict, reg) -> dict | None:
|
||
"""A recorded item → a record: ``{ref}`` (a key / an id / a branch the
|
||
CLI couldn't read — the hub's registry does), ``{kind: url, url}`` (a
|
||
plugin kind when one matches), or ``{kind, id}``."""
|
||
kind = r.get("kind")
|
||
if kind is not None and (not isinstance(kind, str) or not _KIND_RE.match(kind)):
|
||
raise ValueError("resource kind must be a slug")
|
||
if r.get("ref") is not None:
|
||
ref = r["ref"]
|
||
if not isinstance(ref, str) or not ref.strip() or len(ref) > 2000:
|
||
raise ValueError("resource ref must be text")
|
||
hit = reg.parse_ref(ref, kind=kind)
|
||
if hit is None:
|
||
raise ValueError(f"not a resource of an active kind: {ref[:80]!r}")
|
||
return {**{k: v for k, v in r.items() if k not in ("ref", "kind", "id", "url")}, **hit}
|
||
if kind not in (*plugin_resources.CORE_KINDS, *reg.kinds):
|
||
raise ValueError("resource kind must be one of "
|
||
+ ", ".join((*plugin_resources.CORE_KINDS, *sorted(reg.kinds))))
|
||
if kind == "url" and isinstance(r.get("url"), str):
|
||
hit = reg.resolve_url(r["url"])
|
||
if hit:
|
||
return {**{k: v for k, v in r.items() if k not in ("kind", "id", "url")}, **hit}
|
||
if kind in reg.kinds:
|
||
return reg.by_kind[kind].finalize(dict(r))
|
||
return dict(r)
|
||
|
||
|
||
def clean_recorded(items, source: str = "agent", reg=None) -> list[dict]:
|
||
"""Validate resources a session (``conv add``) or the owner records: a
|
||
core or active plugin kind (or a ``ref`` the registry reads), an id,
|
||
http(s) links only, bounded text. Unknown fields are dropped; ``source``
|
||
defaults to who is recording."""
|
||
reg = reg if reg is not None else plugin_resources.EMPTY
|
||
if not isinstance(items, list) or len(items) > 50:
|
||
raise ValueError("resources must be a list (50 max)")
|
||
out = []
|
||
for raw in items:
|
||
if not isinstance(raw, dict):
|
||
raise ValueError("a resource is an object")
|
||
url = raw.get("url")
|
||
if url is not None and (not isinstance(url, str) or len(url) > 2000
|
||
or not url.startswith(("https://", "http://"))):
|
||
raise ValueError("resource url must be an http(s) link")
|
||
r = _shape(raw, reg)
|
||
rid = str(r.get("id") or "").strip()
|
||
if not rid or len(rid) > 200 or "\n" in rid:
|
||
raise ValueError("resource id is required (200 chars max)")
|
||
url = r.get("url")
|
||
if url is not None and (not isinstance(url, str) or len(url) > 2000
|
||
or not url.startswith(("https://", "http://"))):
|
||
raise ValueError("resource url must be an http(s) link")
|
||
c = {"kind": r["kind"], "id": rid, "url": url or None,
|
||
"source": raw.get("source") if raw.get("source") in _RECORD_SOURCES else source}
|
||
for f, n in _TEXT_MAX.items():
|
||
v = raw.get(f) if raw.get(f) else r.get(f)
|
||
if isinstance(v, str) and v.strip():
|
||
c[f] = v.strip()[:n]
|
||
if isinstance(r.get("number"), int):
|
||
c["number"] = r["number"]
|
||
if raw.get("primary"):
|
||
c["primary"] = True
|
||
for f in ("firstSeen", "at"):
|
||
if isinstance(raw.get(f), str) and len(raw[f]) <= 40:
|
||
c[f] = raw[f]
|
||
out.append(c)
|
||
return out
|
||
|
||
|
||
def clean_remove(keys, reg=None) -> list[str]:
|
||
"""``resourcesRemove``: ``kind:id`` keys, or what ``conv rm`` was handed
|
||
(a link, a key) — read by the registry into its key (and a link's plain
|
||
``url:`` key too, so it stays gone if its plugin goes)."""
|
||
reg = reg if reg is not None else plugin_resources.EMPTY
|
||
if not isinstance(keys, list) or len(keys) > 50:
|
||
raise ValueError("resourcesRemove takes kind:id keys")
|
||
out: list[str] = []
|
||
for k in keys:
|
||
if not isinstance(k, str) or not k.strip() or len(k) > 2000:
|
||
raise ValueError("resourcesRemove takes kind:id keys")
|
||
k = k.strip()
|
||
kind, sep, rid = k.partition(":")
|
||
if sep and _KIND_RE.match(kind) and not rid.startswith("//") and len(k) <= 220:
|
||
out.append(k)
|
||
continue
|
||
hit = reg.parse_ref(k)
|
||
if hit is None:
|
||
raise ValueError(f"not a resource: {k[:80]!r}")
|
||
out.append(ru.key(hit))
|
||
if k.startswith(("http://", "https://")):
|
||
u = ru.parse_url(k)
|
||
if u:
|
||
out.append(ru.key(u))
|
||
return list(dict.fromkeys(out))
|
||
|
||
|
||
def _summary_for(deps, sid: str) -> dict:
|
||
"""The stored summary of a session's main transcript ({} if none yet)."""
|
||
from conversations.catalog import _conv_ids_by_session # cycle-free here
|
||
cid = _conv_ids_by_session(deps).get(sid) if sid else None
|
||
return (deps.store.get_summary(ids.path_of(cid)) if cid else None) or {}
|
||
|
||
|
||
def stamp_title(deps, sid: str) -> str | None:
|
||
"""The first resolve names the conversation, once: when it has a
|
||
recorded primary and no title yet, stamp the resource title as
|
||
``meta.title`` (``titleSource: resources``) — so it reads the same
|
||
everywhere from then on, and a later rename (or ``conv title``) wins."""
|
||
m = deps.meta_store.peek(sid)
|
||
if m.get("title") or not any(r.get("primary") for r in m.get("resources") or ()):
|
||
return None
|
||
summary = _summary_for(deps, sid)
|
||
if not summary:
|
||
return None # not indexed yet: the derived title covers it
|
||
_rs, title = for_conversation(deps, summary, m, m.get("worker") or m.get("workerSource"))
|
||
if not title:
|
||
return None
|
||
deps.meta_store.update(sid, {"title": title, "titleSource": "resources"})
|
||
return title
|
||
|
||
|
||
# What a run may set on its own conversation through a worker's outbox: its
|
||
# resources, a title and its look (`conv look`) — never its account, owner,
|
||
# archived flag or a "user" title (the owner's rename).
|
||
_RECORD_KEYS = ("resources", "resourcesRemove", "title", "titleSource", "look")
|
||
|
||
|
||
def apply_recorded(deps, payload: dict) -> dict:
|
||
"""A ``meta`` outbox item (``conv add`` / ``title`` / ``look`` on a worker):
|
||
whitelisted keys only, and only onto a session that runs on the worker it
|
||
came from. Raw links and keys are read here, by the hub's registry.
|
||
Returns the mirror's ack."""
|
||
sid = str(payload.get("sessionId") or "")
|
||
patch = payload.get("patch") if isinstance(payload.get("patch"), dict) else {}
|
||
patch = {k: v for k, v in patch.items() if k in _RECORD_KEYS and v is not None}
|
||
if not sid or not patch:
|
||
return {"failed": True, "error": "nothing to record (sessionId + patch)"}
|
||
m = deps.meta_store.peek(sid)
|
||
runs_on = m.get("worker") or m.get("workerSource")
|
||
if runs_on and payload.get("worker") and runs_on != payload["worker"]:
|
||
return {"failed": True, "error": "that session runs elsewhere"}
|
||
if patch.get("titleSource") not in (None, "agent", "resources"):
|
||
return {"failed": True, "error": "titleSource must be agent or resources"}
|
||
if "title" in patch and not isinstance(patch["title"], str):
|
||
return {"failed": True, "error": "title must be text"}
|
||
if "title" in patch:
|
||
patch["title"] = patch["title"].strip()[:200]
|
||
patch.setdefault("titleSource", "agent")
|
||
reg = plugin_resources.registry(deps)
|
||
try:
|
||
if "resources" in patch:
|
||
patch["resources"] = clean_recorded(patch["resources"], reg=reg)
|
||
if "look" in patch:
|
||
patch["look"] = look_mod.clean(patch["look"])
|
||
if "resourcesRemove" in patch:
|
||
patch["resourcesRemove"] = clean_remove(patch["resourcesRemove"], reg)
|
||
except ValueError as e:
|
||
return {"failed": True, "error": str(e)}
|
||
deps.meta_store.update(sid, dict(patch))
|
||
if any(r.get("primary") for r in patch.get("resources") or ()):
|
||
stamp_title(deps, sid)
|
||
deps.hub.publish({"type": "meta", "id": sid})
|
||
return {"id": payload.get("id"), "ok": True}
|
||
|
||
|
||
# ── notification pills ──────────────────────────────────────────────────────
|
||
NOTIF_FIELDS = ("kind", "id", "url", "label", "title", "state", "primary")
|
||
NOTIF_MAX = 3
|
||
|
||
|
||
def notif_pills_on(deps, worker: str | None, cwd: str | None) -> bool:
|
||
"""Whether a plugin in scope for this conversation shows pills on its
|
||
pushes (its ``notifPills`` setting)."""
|
||
return plugin_resources.registry(deps).notif_pills(worker, cwd)
|
||
|
||
|
||
def compact(rs: list[dict], n: int = NOTIF_MAX) -> list[dict]:
|
||
return [{f: r[f] for f in NOTIF_FIELDS if r.get(f) not in (None, "", False)}
|
||
for r in rs[:n]]
|
||
|
||
|
||
def notif_resources(deps, sid: str) -> list[dict]:
|
||
"""What a new push from ``sid`` carries: its conversation's main
|
||
resources (≤3, primary first) when a plugin in scope shows pills on
|
||
notifications — so the card renders them without a join, as they were
|
||
when it was sent."""
|
||
if not sid:
|
||
return []
|
||
m = deps.meta_store.peek(sid)
|
||
summary = _summary_for(deps, sid)
|
||
if not summary.get("resourcesAuto") and not m.get("resources"):
|
||
return []
|
||
worker = m.get("worker") or m.get("workerSource")
|
||
if not notif_pills_on(deps, worker, summary.get("cwd")):
|
||
return []
|
||
return compact(for_conversation(deps, summary, m, worker)[0])
|