Files
ai-agent/backend/conversations/resource_view.py
gabrielvidalandClaude Opus 5.5 618b17f6c2 feat(look): Linear projects — the card's colour and icon, a project pill
A resource plugin can declare a `hueRole: group` kind — what an issue
belongs to (a Linear project); its issue kind names it with `groupBy`.
The linear plugin's `linear-project` uses it (plugin 1.1.0, ai-agent-plugins
branch linear-projects). Decided in form linear-projects-icons-colour_yfnahd.

- Lookups only: get_project and list_projects (a new extractor field,
  `itemsPath: projects[]`, reads each item of a listing without tagging
  the conversation) teach Linear's icon and colour; `vendor_icons` turns
  `Brush` / `:heavy_plus_sign:` into glyph keys (`brush`, `emoji:➕`,
  gemoji table vendored). PARSER_VERSION 47 re-mines past lookups.
- Colour (`cardColour: group`, the default): a card wears its issue's
  project colour, each issue of the project a shade (`LookColors.group_color`,
  `shade_hex` ≡ the PWA's `shadeHex`); a palette hue when Linear's is
  unknown; an issue with no known project keeps issue + PR colours.
  A Settings → Tags colour on `linear:project/<name>` wins (the PWA
  re-shades it with `colorGroup` / `colorShade`); *Colour…* on such a card
  writes that tag.
- Icon (`iconOrder: group`): project › label › team; the project's tag
  icon, else Linear's own.
- Pill (`groupPills`): the issue's project beside it, in its own icon and
  colour (`Resource.icon` / `color`; the glyph is tinted, not the pill).
- `groupLooks` off: only what Settings → Tags sets.
- Emoji tag icons (`emoji:<char>`), Linear's look as a project tag's
  derived default in Settings → Tags, the mock seeds two projects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:50:11 +01:00

739 lines
32 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.
"""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 import vendor_icons
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", "icon", "color")
MAX_ON_CARD = 12
# What lookups say that the look reads: an issue's labels / project / team,
# a group's (a Linear project's) own icon and colour.
_META_FIELDS = ("labels", "project", "team", "icon", "color")
def _derive(reg, summary: dict) -> tuple:
"""What one transcript teaches every card: (teams by kind, names, titles,
metas, xrefs, groups seen). 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] = {}
# The group kind's records (Linear projects) named by a link only: key →
# the name its slug reads as — what an issue's `project` is matched to.
gseen: dict[str, str] = {}
gk = reg.group_def.kind if reg and reg.group_def else None
for r in summary.get("resourcesAuto") or ():
n = reg.normalize(r) if reg else None
if n is None:
continue
if gk and n["kind"] == gk and (n.get("title") or n.get("slugTitle")):
gseen.setdefault(ru.key(n), n.get("title") or n["slugTitle"])
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, gseen
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,
gseen: dict[str, str] | 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 {}
# group kind:id → the name a link's slug reads as (no lookup yet).
self.gseen = gseen or {}
self._groups: dict[str, dict] | None = None
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
and self.gseen == other.gseen)
# ── groups (Linear projects) ────────────────────────────────────────────
def _group_index(self) -> dict[str, dict]:
"""lower-cased name → ``{key, id, url, name, icon, color}`` of every
group the archive knows: looked up (``get_project`` /
``list_projects`` — a title, Linear's icon and colour) or linked."""
if self._groups is not None:
return self._groups
out: dict[str, dict] = {}
gd = self.registry.group_def
if gd is not None:
pre = gd.kind + ":"
keys = [k for k in (*self.titles, *self.metas, *self.gseen) if k.startswith(pre)]
for k in dict.fromkeys(keys):
rec = gd.finalize({"kind": gd.kind, "id": k[len(pre):]})
name = self.titles.get(k) or self.gseen.get(k) or rec.get("slugTitle")
if not name:
continue
m = self.metas.get(k) or {}
g = {"key": k, "id": rec["id"], "url": rec.get("url"), "name": name,
"icon": vendor_icons.icon_key(m.get("icon")),
"color": vendor_icons.hex_color(m.get("color"))}
cur = out.get(name.lower())
# Two records of one name (a link, then its lookup): the one
# that knows the look wins, then the one with a link.
if cur is None or ((g["icon"] or g["color"]) and not (cur["icon"] or cur["color"])) \
or (not cur["url"] and g["url"]):
out[name.lower()] = g
self._groups = out
return out
def group_named(self, name: str | None) -> dict | None:
return self._group_index().get(name.strip().lower()) if name and name.strip() else None
def group_of_key(self, key: str | None) -> dict | None:
if not key:
return None
return next((g for g in self._group_index().values() if g["key"] == key), None)
def group_name_of(self, issue_key: str | None) -> str | None:
"""The group a hue resource (an issue) belongs to — its lookups'
``groupBy`` field (``project``)."""
if not issue_key:
return None
d = self.registry.by_kind.get(issue_key.partition(":")[0])
if d is None or not d.group_by:
return None
v = (self.metas.get(issue_key) or {}).get(d.group_by)
return v.strip() if isinstance(v, str) and v.strip() else None
_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] = {}
gseen: dict[str, str] = {}
if reg:
seen: set = set()
for p, s in deps.store.all_summaries():
seen.add(p)
t, n, ti, me, x, gs = _per_summary.get(p, s, reg)
for k, v in gs.items():
gseen.setdefault(k, v)
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, gseen)
# 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; a
group's pill (a Linear project) reads as its name and wears its look."""
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 d is reg.group_def:
g = ctx.group_of_key(ru.key(r)) or ctx.group_named(r.get("title"))
if g and not r.get("url"):
r["url"] = g["url"]
r["label"] = (g or {}).get("name") or r.get("title") or r.get("label")
if g and reg.look.group_looks:
for f in ("icon", "color"):
if g.get(f):
r[f] = g[f]
if not r.get("label"):
r["label"] = str(r.get("id"))
return r
def group_look(ctx: Context, hue_key: str | None, subject_key: str | None) -> dict | None:
"""``{name, icon, color}`` of the group a card's colour and icon follow:
its issue's (``hue_key``) project, else the project the conversation is
about alone. Linear's icon and colour only with ``groupLooks`` on."""
reg = ctx.registry
if reg.group_def is None:
return None
g = None
if hue_key:
name = ctx.group_name_of(hue_key)
if name:
g = ctx.group_named(name) or {"name": name}
elif subject_key and "+" not in subject_key \
and subject_key.startswith(reg.group_def.kind + ":"):
g = ctx.group_of_key(subject_key)
if not g:
return None
out = {"name": g["name"]}
if reg.look.group_looks:
out.update({f: g[f] for f in ("icon", "color") if g.get(f)})
return out
def _group_pills(out: dict[str, dict], ctx: Context, scoped: frozenset) -> None:
"""Each issue's group (its Linear project) as a pill beside it — from
what a lookup said the issue belongs to (``groupBy``), the
``groupPills`` setting on (by default) and the group kind in scope."""
reg = ctx.registry
gd = reg.group_def
if gd is None or not reg.look.group_pills or gd.kind not in scoped:
return
have = set()
for k, r in out.items():
if r["kind"] == gd.kind:
g = ctx.group_of_key(k)
have.add(((g or {}).get("name") or ctx.titles.get(k) or ctx.gseen.get(k)
or r.get("title") or r.get("slugTitle") or "").lower())
for k, r in list(out.items()):
if reg.roles.get(r["kind"]) != "hue":
continue
name = ctx.group_name_of(k)
if not name or name.lower() in have:
continue
g = ctx.group_named(name)
rec = {"kind": gd.kind, "id": g["id"] if g else "name:" + _slug(name),
"title": name, "source": "auto", "via": "issue",
"firstSeen": r.get("firstSeen")}
if g and g.get("url"):
rec["url"] = g["url"]
if r.get("firstTurn"):
rec["firstTurn"] = True
rec = gd.finalize(rec)
out.setdefault(ru.key(rec), rec)
have.add(name.lower())
def _slug(name: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:100] or "project"
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
_group_pills(out, ctx, scoped)
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])