Files
ai-agent/cli/conv_ref.py

295 lines
14 KiB
Python

#!/usr/bin/env python3
"""conv-ref: the ``UserPromptSubmit`` hook that tells an agent what "a conv" is.
Gabriel says *check past conv*, *previous convs*, *this conv 01a1e40a-…*, or pastes
a viewer link, and means a conversation in his ai-agent hub. In Nov 2026 the
lab's runs got that right: 22 out of 22 lookups went to ``ai-agent
search/show``. The workers' runs mostly didn't: 3 out of 15 reached the hub.
The others grepped the Mac's own ``~/.claude/projects``, which holds that
machine's sessions only, or hunted a conversation id with ``find`` and
``ssh homelab find /`` (``~/homelab/data/log/2026-11-22-check-conv-analysis.md``).
Installed in every account's ``settings.json`` on the lab and the owner's
workers (harness-claude's ``conv_ref_hook.py``). It reads the prompt from stdin. When the
prompt names a conversation or talks about past ones, it adds one block of
context (``additionalContext``):
* **where conversations live and how to read them** on *this* machine: on the
lab, the ``ai-agent`` CLI; on a worker, the hub's MCP tools, else
``ai-agent past`` through the outbox;
* **a card for each conversation it names** (id, session id, ≥ 8-hex prefix
after "conv", viewer link), resolved by the hub. On the lab that is
``GET /api/conversation-refs``; on a worker, a ``lookup`` outbox item with
``ids``, which the hub answers within that worker's profile. Each card has
the title, state, machine, the opening prompt, the last answer, and the
transcript's path when the file is on this machine.
It prints nothing for any other prompt, and nothing in a guest's run
(``AIA_GUEST`` / ``AIA_AS_SESSION``): there the hub would answer as the
owner. It never blocks a prompt, whatever fails. Stdlib only, so it runs on
the lab host and on every worker alike.
"""
from __future__ import annotations
import argparse
import datetime as dt
import glob
import json
import os
import re
import secrets
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
HUB = (os.environ.get("AI_AGENT_URL") or "http://127.0.0.1:8096").rstrip("/")
MAX_IDS = 5
LOOKUP_S = 6.0 # the whole hub round trip; the prompt waits on it
_UUID = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
UUID_RE = re.compile(rf"(?<![0-9a-f-])({_UUID})(?![0-9a-f-])", re.I)
LINK_RE = re.compile(r"https?://\S+?/conversation/([0-9a-f-]{6,36})", re.I)
# "conv 01a1e40a", "conversation #a2533c3a", "session a2533c3a-d718…"
NAMED_RE = re.compile(r"\b(?:convs?|conversations?|sessions?)\s*(?:id\s*)?[:#]?\s*"
r"([0-9a-f]{8}(?:[0-9a-f-]{0,28}))(?![0-9a-z])", re.I)
WORD = r"(?:convs?|conversations?|sessions?|chats?)"
PHRASE_RE = re.compile("|".join([
rf"\b(?:past|previous|prev|earlier|last|older?|other|recent|parent|sibling)\s+(?:\w+\s+){{0,2}}?{WORD}\b",
r"\bcheck\s+(?:the\s+|my\s+|these\s+|those\s+)?convs?\b",
r"\bconvs?\s+(?:about|where|on|that|which|in\s+which)\b",
r"\b(?:this|that|the|from|in)\s+conv\b",
r"\bconv(?:ersation)?s?\s+(?:précédente?s?|passée?s?|d'avant|d'hier)\b",
r"\b(?:ancienne?s?|dernière?s?|autres?|précédente?s?)\s+conv(?:ersation)?s?\b",
]), re.I)
# What the hub appends to a prompt (locations, skills, guidelines, uploads):
# its own wording ("search past ones…") is not Gabriel asking.
HUB_TAIL_RE = re.compile(r"\n\s*(?:Use the following in this task|Guidelines:|Work in the following "
r"homelab location|Attached files \(uploaded via the composer|Conversations referenced:)")
def own_text(prompt: str) -> str:
if (prompt or "").lstrip().startswith("This session is being continued from a previous conversation"):
return "" # a compaction summary, not a prompt
m = HUB_TAIL_RE.search(prompt or "")
return prompt[:m.start()] if m else (prompt or "")
def find_refs(text: str, own_session: str | None = None) -> tuple[list[str], set[str], bool]:
"""``(ids, named, talks_about_past)``. ``ids`` are the full ids, link ids and
named prefixes, in order (at most :data:`MAX_IDS`). ``named`` is the subset
the prompt *called* a conversation. Only those get a "not found" line, since
an Orus contract id is a UUIDv7 too."""
ids: list[str] = []
named: set[str] = set()
def add(ref: str, is_named: bool) -> None:
ref = ref.lower().strip("-")
if own_session and ref == own_session.lower():
return
if ref not in ids:
ids.append(ref)
if is_named:
named.add(ref)
for m in LINK_RE.finditer(text):
add(m.group(1), True)
for m in NAMED_RE.finditer(text):
add(m.group(1), True)
for m in UUID_RE.finditer(text):
add(m.group(1), False)
# a prefix also written in full is the full one
ids = [r for r in ids if not any(o != r and o.startswith(r) for o in ids)]
named = {r for r in named if r in ids} | {o for o in ids for r in named if o.startswith(r)}
return ids[:MAX_IDS], named, bool(PHRASE_RE.search(text))
# ── the hub ──────────────────────────────────────────────────────────────────
def _http(url: str, data: dict | None = None, *, token: str = "", timeout: float = 4.0) -> tuple[int, dict]:
body = json.dumps(data).encode() if data is not None else None
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(url, data=body, method="POST" if body else "GET", headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, json.loads(r.read().decode(errors="replace") or "{}")
except urllib.error.HTTPError as e:
try:
return e.code, json.loads(e.read().decode(errors="replace") or "{}")
except ValueError:
return e.code, {}
except (urllib.error.URLError, OSError, ValueError) as e:
return 0, {"error": str(e)}
def lookup_hub(ids: list[str], session: str | None, hub: str = HUB) -> dict:
q = urllib.parse.urlencode({k: v for k, v in (("ids", ",".join(ids)), ("session", session)) if v})
code, res = _http(f"{hub}/api/conversation-refs?{q}", timeout=LOOKUP_S)
if code != 200:
raise RuntimeError(res.get("detail") or res.get("error") or f"HTTP {code}")
return res
def lookup_outbox(ids: list[str], session: str | None, outbox: str, token: str) -> dict:
"""A one-shot ``lookup`` item; the hub answers it in its ack."""
oid = f"lkp_{secrets.token_hex(6)}"
deadline = time.monotonic() + LOOKUP_S
code, res = _http(f"{outbox}/outbox", {"kind": "lookup",
"payload": {"id": oid, "sessionId": session, "ids": ids}},
token=token)
if code not in (200, 202):
raise RuntimeError(f"the outbox refused the lookup: {res.get('detail') or res.get('error') or code}")
while (left := deadline - time.monotonic()) > 0:
wait = max(1, int(left))
code, it = _http(f"{outbox}/outbox/{oid}?waitSecs={wait}", token=token, timeout=wait + 2)
st, hub = it.get("status"), it.get("hub") or {}
if st == "applied":
return hub.get("result") or {}
if st == "failed":
raise RuntimeError(hub.get("error") or "the hub refused the lookup")
if code not in (200, 0):
raise RuntimeError(f"outbox: HTTP {code}")
if code == 0:
time.sleep(0.3)
_http(f"{outbox}/outbox/{oid}/cancel", {}, token=token, timeout=2)
raise RuntimeError(f"no answer from the hub in {LOOKUP_S:.0f} s")
# ── the card ─────────────────────────────────────────────────────────────────
def _ago(ts: str | None, now: dt.datetime | None = None) -> str:
try:
t = dt.datetime.fromisoformat((ts or "").replace("Z", "+00:00"))
except ValueError:
return "?"
s = int(((now or dt.datetime.now(dt.timezone.utc)) - t).total_seconds())
for unit, n in (("d", 86400), ("h", 3600), ("m", 60)):
if s >= n:
return f"{s // n}{unit} ago"
return "just now"
def _one_line(text: str | None, n: int) -> str:
text = " ".join((text or "").split())
return text if len(text) <= n else text[:n - 1] + "…"
def local_transcript(sid: str | None, transcript_path: str | None = None) -> str | None:
"""The session's transcript when it is on this machine: every Claude
config dir's ``projects/`` (the session's own first)."""
if not sid or not re.fullmatch(_UUID, sid, re.I):
return None
roots = []
if transcript_path:
roots.append(Path(transcript_path).expanduser().parent.parent)
home = Path.home()
for d in [os.environ.get("CLAUDE_CONFIG_DIR"), str(home / ".claude"), *glob.glob(str(home / ".claude-*"))]:
if d:
roots.append(Path(d) / "projects")
seen = set()
for r in roots:
if r in seen or not r.is_dir():
continue
seen.add(r)
hits = glob.glob(str(r / "*" / f"{sid}.jsonl"))
if hits:
return hits[0]
return None
def how_to(worker: bool) -> str:
if worker:
return ("Read them through the hub, which has every machine's conversations. Use its MCP tools "
"`mcp__ai-agent__search_conversations` (words), `mcp__ai-agent__past_conversations` (a "
"Linear issue, a PR or a conversation id) and `mcp__ai-agent__get_conversation` (an id; "
"`full`/`tools` for more), loaded with ToolSearch \"select:…\". Without them, "
"`ai-agent past KEY` works here through the outbox.")
return ("Read them with the `ai-agent` CLI: `ai-agent search WORDS [--project P] [--since 7d]`, "
"`ai-agent past INS-1234|PR|<conv id>`, `ai-agent show ID` (`--full`, `--tail N`, `--tools` "
"for more). The `ai-agent` skill has the rest.")
def render(ids: list[str], named: set[str], res: dict | None, err: str | None, *,
worker: bool, transcript_path: str | None = None, now: dt.datetime | None = None) -> str:
lines = ["[ai-agent] Here “conv” / “past conversation” means a conversation in Gabriel's ai-agent "
"hub: every run on the lab, his Macs and the devbox. It is not a file under "
"~/.claude/projects, which holds this machine's sessions only, named by session id, "
"never by conversation id.",
how_to(worker)]
res = res or {}
cards = res.get("cards") or []
if cards:
lines.append("Conversations this prompt names, as the hub has them:")
for c in cards:
when = _ago(c.get("endedAt") or c.get("startedAt"), now)
bits = [c.get("state") or "?", f"{'started' if c.get('state') == 'running' else 'ended'} {when}",
c.get("machine") or "?", c.get("account") or "",
", ".join(dict.fromkeys(p.split("@")[0] for p in c.get("projects") or []))]
lines.append(f"• {c['id']} “{_one_line(c.get('title'), 90) or '(untitled)'}” "
f"— {' · '.join(b for b in bits if b)}")
lines.append(f" session {c.get('sessionId')} · {c.get('url')}")
path = local_transcript(c.get("sessionId"), transcript_path)
if path:
lines.append(f" transcript on this machine: {path}")
if c.get("firstPrompt"):
lines.append(f" asked: {_one_line(c['firstPrompt'], 400)}")
if c.get("lastAnswer"):
lines.append(f" last answer: {_one_line(c['lastAnswer'], 800)}")
for a in res.get("ambiguous") or []:
lines.append(f"• {a['ref']}: names {a['count']} conversations; search, or ask for more characters.")
for ref in res.get("unknown") or []:
if ref in named:
lines.append(f"• {ref}: no conversation the hub shows here has this id.")
if err and any(r in named for r in ids):
lines.append(f"(The hub didn't resolve {', '.join(ids)}: {err}. Look them up as above.)")
return "\n".join(lines)
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--outbox", help="this worker's outbox (a worker's install)")
ap.add_argument("--token-file", help="the outbox's run token (0600)")
ap.add_argument("--hub", default=HUB, help="the hub's API (the lab's install)")
a = ap.parse_args(argv)
if os.environ.get("AIA_GUEST", "").strip() or os.environ.get("AIA_AS_SESSION", "").strip() \
or os.environ.get("AI_AGENT_CONV_REF") == "0":
return 0
try:
data = json.loads(sys.stdin.read() or "{}")
except ValueError:
return 0
text = own_text(str(data.get("prompt") or ""))
session = data.get("session_id") or None
ids, named, talks = find_refs(text, session)
if not ids and not talks:
return 0
outbox = (os.environ.get("AI_AGENT_OUTBOX_URL") or a.outbox or "").rstrip("/")
token = os.environ.get("AI_AGENT_OUTBOX_TOKEN", "")
if outbox and not token and a.token_file:
try:
token = Path(a.token_file).read_text().strip()
except OSError:
token = ""
res, err = None, None
if ids:
try:
res = lookup_outbox(ids, session, outbox, token) if outbox else lookup_hub(ids, session, a.hub)
except Exception as e: # never block a prompt
err = str(e)[:200]
if not talks and not (res or {}).get("cards") and not named:
return 0 # bare UUIDs that are no conversation: not ours to explain
ctx = render(ids, named, res, err, worker=bool(outbox), transcript_path=data.get("transcript_path"))
print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit",
"additionalContext": ctx}}, ensure_ascii=False))
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Exception: # a hook must never fail the prompt
sys.exit(0)