agy and pi name nothing themselves (Claude Code writes ai-title, opencode's mirror its session title), so their cards read the first prompt. Core side of the conversation-titles plugin: - meta.autoTitle: cards._conv_title reads it like Claude's own title — the owner's rename, the agent's conv title and a resource title win, it beats the first prompt. - conversations.label bridges: GET hub/labels/untitled?harness=agy,pi (conversations/title_pending.py — sid answers from the meta's harness before the transcript is indexed) and POST hub/labels/title (an empty answer is stored as null — never asked again — but never replaces a title). - complete.run on an agent preset: preset "default" (the source's preset in Settings → Agent presets) or "<id>", resolved by the runs.route provider on the call's profile; the plugin's own model becomes the fallback and answers alone with no preset set. GET hub/complete/route: that route, no call. - run_router.sources(): complete.run holders naming the routing provider in requires / optionalRequires are listed as sources (uses: complete). - conversation.started carries the run's harness. - docs/plugins.md + CLAUDE.md; tests in test_hubcomplete, test_run_router, test_plugin_deps_agents. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
279 lines
15 KiB
Python
279 lines
15 KiB
Python
"""The ``complete.run`` / ``conversations.label`` bridges and the
|
|
``conversation.title`` dispatch (plugins/hubcomplete.py, labels_bridge.py):
|
|
the body a plugin may send, the spend booked per engine, the labels written,
|
|
and what the core does with no labelling plugin installed."""
|
|
|
|
import types
|
|
import unittest
|
|
|
|
from plugins import hubcomplete, labels_bridge, manifest
|
|
|
|
USAGE = {"input_tokens": 400, "output_tokens": 20, "cache_read_input_tokens": 0,
|
|
"cache_creation_input_tokens": 0}
|
|
|
|
|
|
class Ledger:
|
|
def __init__(self):
|
|
self.rows = []
|
|
|
|
def add_side_call(self, kind, ref, account, model, cost, units, usage, t=None):
|
|
self.rows.append((kind, ref, account, model, cost, units, usage))
|
|
|
|
|
|
class NormComplete(unittest.TestCase):
|
|
def test_clamps_and_keeps_known_fields(self):
|
|
b = hubcomplete.norm_complete({"prompt": " hi ", "system": "s", "model": "haiku",
|
|
"harness": "claude", "account": "work",
|
|
"fallbackModel": "gemini-3.8-flash",
|
|
"fallbackHarness": "agy", "timeout": 999,
|
|
"bogus": 1})
|
|
self.assertEqual(b, {"system": "s", "prompt": "hi", "wakeLocal": False, "timeout": 120,
|
|
"model": "haiku", "harness": "claude", "account": "work",
|
|
"fallbackModel": "gemini-3.8-flash", "fallbackHarness": "agy"})
|
|
|
|
def test_refuses(self):
|
|
for bad in ({}, {"prompt": "x", "model": "a b"}, {"prompt": "x", "harness": "../x"},
|
|
{"prompt": "x", "account": "A;rm"}):
|
|
with self.assertRaises(ValueError):
|
|
hubcomplete.norm_complete(bad)
|
|
|
|
|
|
class Book(unittest.TestCase):
|
|
def setUp(self):
|
|
self.deps = types.SimpleNamespace(usage_store=Ledger())
|
|
|
|
def test_claude_is_priced_from_its_tokens(self):
|
|
from conversations import pricing
|
|
model = "claude-haiku-5-5-20261001"
|
|
out = hubcomplete.book(self.deps, {"harness": "claude", "model": model, "usage": USAGE,
|
|
"account": "work", "costUsd": 99}, "short-title", "c1")
|
|
[(kind, ref, account, m, cost, units, usage)] = self.deps.usage_store.rows
|
|
u = pricing.norm_usage(USAGE)
|
|
self.assertEqual((kind, ref, account, m, usage), ("short-title", "c1", "work", model, USAGE))
|
|
self.assertAlmostEqual(cost, pricing.usage_cost(u, model))
|
|
self.assertAlmostEqual(units, pricing.plan_units(u, model))
|
|
self.assertAlmostEqual(out["costUsd"], round(cost, 6))
|
|
|
|
def test_direct_engines_carry_their_own_figure(self):
|
|
hubcomplete.book(self.deps, {"harness": "openrouter", "model": "qwen/qwen3.8-27b",
|
|
"usage": USAGE, "account": "openrouter", "costUsd": 0.0012},
|
|
"look", "s")
|
|
hubcomplete.book(self.deps, {"harness": "evox2", "model": "inkling-2-mini",
|
|
"usage": USAGE, "account": "evox2", "costUsd": 0.0},
|
|
"look", "s")
|
|
self.assertEqual([(r[2], r[4], r[5]) for r in self.deps.usage_store.rows],
|
|
[("openrouter", 0.0012, 0.0), ("evox2", 0.0, 0.0)])
|
|
|
|
|
|
class WriteLook(unittest.TestCase):
|
|
def setUp(self):
|
|
self.metas, self.events = {}, []
|
|
self.deps = types.SimpleNamespace(
|
|
meta_store=types.SimpleNamespace(update=lambda sid, p: self.metas.setdefault(sid, p)),
|
|
hub=types.SimpleNamespace(publish=self.events.append))
|
|
|
|
def test_known_action_kept_unknown_stored_as_none(self):
|
|
self.assertEqual(hubcomplete.write_look(self.deps, "s1", " Fix ", "haiku", "plugin:x"),
|
|
"fix")
|
|
self.assertIsNone(hubcomplete.write_look(self.deps, "s2", "dance", "haiku"))
|
|
self.assertEqual(self.metas["s1"]["lookAuto"]["action"], "fix")
|
|
self.assertEqual(self.metas["s1"]["lookAuto"]["source"], "plugin:x")
|
|
self.assertIsNone(self.metas["s2"]["lookAuto"]["action"])
|
|
self.assertEqual(self.events, [{"type": "meta", "id": "s1"}, {"type": "meta", "id": "s2"}])
|
|
|
|
|
|
class NoPlugin(unittest.TestCase):
|
|
"""No ``conversation.title`` provider: nothing is asked (the
|
|
scheduled-conversations plugin then titles a prompt by its first words)."""
|
|
|
|
def test_falls_back(self):
|
|
deps = types.SimpleNamespace(plugin_store=None)
|
|
self.assertFalse(labels_bridge.available(deps))
|
|
self.assertIsNone(labels_bridge.title(deps, "Audit every compose file", "scheduled-title"))
|
|
|
|
def test_a_provider_answer_is_cleaned(self):
|
|
orig = labels_bridge.run
|
|
seen = []
|
|
labels_bridge.run = lambda deps, key, payload: seen.append((key, payload)) or {
|
|
"title": ' "Nightly audit" ', "summary": "Checks."}
|
|
try:
|
|
ans = labels_bridge.title(object(), "x" * 9000, "short-title", "c", "work")
|
|
finally:
|
|
labels_bridge.run = orig
|
|
self.assertEqual(ans, {"title": "Nightly audit", "summary": "Checks."})
|
|
[(key, payload)] = seen
|
|
self.assertEqual(key, "conversation.title")
|
|
self.assertEqual((len(payload["text"]), payload["account"], payload["isolated"]),
|
|
(6000, "work", True))
|
|
|
|
|
|
class PresetRoute(unittest.TestCase):
|
|
"""``complete.run`` on an agent preset: what a body may name, and how the
|
|
preset's route and the plugin's own model share the call."""
|
|
|
|
def test_preset_arg(self):
|
|
self.assertEqual(hubcomplete.preset_arg({}), (None, None))
|
|
self.assertEqual(hubcomplete.preset_arg({"preset": False}), (None, None))
|
|
self.assertEqual(hubcomplete.preset_arg({"preset": True}), ("default", None))
|
|
self.assertEqual(hubcomplete.preset_arg({"preset": " Preset:Background ", "profile": "work"}),
|
|
("background", "work"))
|
|
for bad in ({"preset": "../x"}, {"preset": "a b"}, {"preset": "x", "profile": "Bad Id"}):
|
|
with self.assertRaises(ValueError):
|
|
hubcomplete.preset_arg(bad)
|
|
|
|
ROUTE = {"model": "haiku", "harness": "claude", "account": "work"}
|
|
|
|
def test_the_plugins_own_model_becomes_the_fallback(self):
|
|
out = hubcomplete.apply_route({"prompt": "p", "model": "gemini-3.8-flash", "harness": "agy",
|
|
"account": "google", "preset": "default"}, self.ROUTE)
|
|
self.assertEqual((out["model"], out["harness"], out["account"]), ("haiku", "claude", "work"))
|
|
self.assertEqual((out["fallbackModel"], out["fallbackHarness"], out["fallbackAccount"]),
|
|
("gemini-3.8-flash", "agy", "google"))
|
|
self.assertEqual(hubcomplete.norm_complete(out)["model"], "haiku")
|
|
|
|
def test_an_explicit_fallback_wins_and_the_same_model_is_no_fallback(self):
|
|
out = hubcomplete.apply_route({"prompt": "p", "model": "x", "fallbackModel": "y"}, self.ROUTE)
|
|
self.assertEqual(out["fallbackModel"], "y")
|
|
self.assertNotIn("fallbackHarness", out)
|
|
same = hubcomplete.apply_route({"prompt": "p", "model": "haiku", "harness": "claude"},
|
|
{"model": "haiku", "harness": "claude", "account": None})
|
|
self.assertNotIn("fallbackModel", same)
|
|
self.assertNotIn("account", same)
|
|
|
|
def test_route_preset_asks_the_provider_for_the_plugins_source(self):
|
|
from unittest import mock
|
|
seen = []
|
|
|
|
def fake(deps, **kw):
|
|
seen.append(kw)
|
|
return {"preset": "background", "name": "Background", "i": 1, "n": 4,
|
|
"harness": "agy", "model": "gemini-3.8-flash", "modelId": "gemini-3.8-flash",
|
|
"account": None, "full": False}
|
|
with mock.patch("plugins.run_router.resolve_new_run", side_effect=fake):
|
|
r = hubcomplete.route_preset(object(), "conversation-titles", "default", "work")
|
|
hubcomplete.route_preset(object(), "conversation-titles", "free", None)
|
|
self.assertEqual((r["preset"], r["harness"], r["model"], r["i"]),
|
|
("background", "agy", "gemini-3.8-flash", 1))
|
|
self.assertEqual((seen[0]["model"], seen[0]["profile"], seen[0]["stamp"]),
|
|
(None, "work", {"plugin": "conversation-titles"}))
|
|
self.assertEqual(seen[1]["model"], "preset:free")
|
|
with mock.patch("plugins.run_router.resolve_new_run", return_value=None):
|
|
self.assertIsNone(hubcomplete.route_preset(object(), "x", "default", None))
|
|
|
|
|
|
class AutoTitle(unittest.TestCase):
|
|
def setUp(self):
|
|
self.metas, self.events = {}, []
|
|
self.deps = types.SimpleNamespace(
|
|
meta_store=types.SimpleNamespace(update=lambda sid, p: self.metas.setdefault(sid, {}).update(p),
|
|
peek=lambda sid: self.metas.get(sid) or {}),
|
|
hub=types.SimpleNamespace(publish=self.events.append))
|
|
|
|
def test_an_empty_answer_never_replaces_a_title(self):
|
|
hubcomplete.write_title(self.deps, "s1", "Port the CLI", "haiku")
|
|
self.assertEqual(hubcomplete.write_title(self.deps, "s1", "", "qwen"), "Port the CLI")
|
|
self.assertEqual(self.metas["s1"]["autoTitle"]["title"], "Port the CLI")
|
|
self.assertEqual(hubcomplete.write_title(self.deps, "s1", "Port the CLI to Rust", "qwen"),
|
|
"Port the CLI to Rust")
|
|
|
|
def test_clean_title(self):
|
|
self.assertEqual(hubcomplete.clean_title(' "Fix the login\nredirect." '), "Fix the login redirect")
|
|
self.assertIsNone(hubcomplete.clean_title(" \"\" "))
|
|
self.assertEqual(len(hubcomplete.clean_title("x" * 500)), hubcomplete.MAX_TITLE)
|
|
|
|
def test_written_with_its_model_and_source_empty_as_none(self):
|
|
self.assertEqual(hubcomplete.write_title(self.deps, "s1", "Port the CLI to Rust.", "haiku",
|
|
"plugin:conversation-titles"), "Port the CLI to Rust")
|
|
self.assertIsNone(hubcomplete.write_title(self.deps, "s2", "", "haiku"))
|
|
a = self.metas["s1"]["autoTitle"]
|
|
self.assertEqual((a["title"], a["model"], a["source"]),
|
|
("Port the CLI to Rust", "haiku", "plugin:conversation-titles"))
|
|
self.assertIsNone(self.metas["s2"]["autoTitle"]["title"])
|
|
self.assertEqual(self.events, [{"type": "meta", "id": "s1"}, {"type": "meta", "id": "s2"}])
|
|
|
|
|
|
class TitlePending(unittest.TestCase):
|
|
"""``conversations/title_pending.py``: the agy / pi conversations still
|
|
without a title, and the one a ``conversation.started`` event names."""
|
|
|
|
def setUp(self):
|
|
import datetime
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
iso = lambda h: (now - datetime.timedelta(hours=h)).strftime("%Y-%m-%dT%H:%M:%SZ") # noqa: E731
|
|
self.summaries = [
|
|
("a", {"sessionId": "agy-1", "harness": "agy", "userTurns": 1, "firstPrompt": "fix x",
|
|
"title": "fix x", "startedAt": iso(1)}),
|
|
("b", {"sessionId": "pi-1", "harness": "pi", "userTurns": 2, "firstPrompt": "add y",
|
|
"startedAt": iso(3)}),
|
|
("c", {"sessionId": "cl-1", "userTurns": 1, "firstPrompt": "z", "startedAt": iso(1)}),
|
|
("d", {"sessionId": "pi-old", "harness": "pi", "userTurns": 1, "firstPrompt": "old",
|
|
"startedAt": iso(24 * 5)}),
|
|
("e", {"sessionId": "pi-sub", "harness": "pi", "userTurns": 1, "firstPrompt": "sub",
|
|
"isSidechain": True, "startedAt": iso(1)}),
|
|
("f", {"sessionId": "agy-named", "harness": "agy", "userTurns": 1, "firstPrompt": "n",
|
|
"startedAt": iso(1)}),
|
|
("g", {"sessionId": "agy-done", "harness": "agy", "userTurns": 1, "firstPrompt": "d",
|
|
"startedAt": iso(1)}),
|
|
]
|
|
self.meta = {"agy-named": {"title": "My rename", "titleSource": "user"},
|
|
"agy-done": {"autoTitle": {"title": None}},
|
|
"agy-new": {"harness": "agy", "state": "running"}}
|
|
self.deps = types.SimpleNamespace(
|
|
store=types.SimpleNamespace(all_summaries=lambda: list(self.summaries)),
|
|
meta_store=types.SimpleNamespace(peek=lambda sid: self.meta.get(sid) or {}))
|
|
|
|
def test_pending_newest_first_only_the_asked_harnesses(self):
|
|
from conversations import title_pending
|
|
rows = title_pending.pending(self.deps, {"agy", "pi"}, days=2, limit=10)
|
|
self.assertEqual([r["sessionId"] for r in rows], ["agy-1", "pi-1"])
|
|
self.assertEqual([r["harness"] for r in rows], ["agy", "pi"])
|
|
self.assertEqual(rows[0]["firstPrompt"], "fix x")
|
|
self.assertIn("account", rows[0])
|
|
self.assertEqual([r["sessionId"] for r in title_pending.pending(self.deps, {"pi"}, days=10)],
|
|
["pi-1", "pi-old"])
|
|
|
|
def test_one_conversation_from_its_meta_before_its_transcript(self):
|
|
from conversations import title_pending
|
|
[row] = title_pending.pending(self.deps, {"agy"}, sid="agy-new")
|
|
self.assertEqual((row["sessionId"], row["harness"], row["firstPrompt"]), ("agy-new", "agy", None))
|
|
self.assertEqual(title_pending.pending(self.deps, {"pi"}, sid="agy-new"), [])
|
|
self.assertEqual(title_pending.pending(self.deps, {"agy"}, sid="agy-done"), [])
|
|
self.assertEqual(title_pending.pending(self.deps, {"agy"}, sid="agy-named"), [])
|
|
|
|
|
|
class ConvTitle(unittest.TestCase):
|
|
"""A generated title ranks like Claude's own: a rename and a resource
|
|
title win, it beats the first prompt."""
|
|
|
|
def test_rank(self):
|
|
from conversations import cards
|
|
meta = {}
|
|
deps = types.SimpleNamespace(meta_store=types.SimpleNamespace(peek=lambda sid: meta))
|
|
s = {"sessionId": "s", "title": "please fix the thing that is broken in the login page"}
|
|
self.assertEqual(cards._conv_title(deps, s, {"resourceTitle": None}), s["title"])
|
|
meta["autoTitle"] = {"title": "Fix the login page"}
|
|
self.assertEqual(cards._conv_title(deps, s, {"resourceTitle": None}), "Fix the login page")
|
|
self.assertEqual(cards._conv_title(deps, s, {"resourceTitle": "INS-1 · Login"}), "INS-1 · Login")
|
|
meta["title"] = "Mine"
|
|
self.assertEqual(cards._conv_title(deps, s, {}), "Mine")
|
|
meta.pop("title")
|
|
meta["autoTitle"] = {"title": None} # asked, no usable answer
|
|
self.assertEqual(cards._conv_title(deps, s, {"resourceTitle": None}), s["title"])
|
|
meta["autoTitle"] = "junk"
|
|
self.assertEqual(cards._conv_title(deps, s, {"resourceTitle": None}), s["title"])
|
|
self.assertEqual(cards._conv_title(deps, {**s, "isSidechain": True}, {}), s["title"])
|
|
|
|
|
|
class Manifest(unittest.TestCase):
|
|
def test_new_capabilities_and_provides_are_operator_only(self):
|
|
for cap in ("complete.run", "conversations.label"):
|
|
self.assertIn(cap, manifest._CAPABILITIES)
|
|
self.assertIn(cap, manifest._OPERATOR_CAPS)
|
|
self.assertIn(cap, manifest._CAP_LABELS)
|
|
for key in ("conversation.title", "conversation.look"):
|
|
self.assertIn(key, manifest._PROVIDES)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|