diff --git a/docs/AGENT_BOARD.md b/docs/AGENT_BOARD.md index efdbe9c..81153ae 100644 --- a/docs/AGENT_BOARD.md +++ b/docs/AGENT_BOARD.md @@ -29,8 +29,21 @@ All take `agentId` and follow the native context/ETag/request-ID contract. | Route | Body | Returns | |---|---|---| | `board/list` | `kinds`, `limit`, `includeDismissed` | `items` | -| `board/update` | `itemId`, `liked`, `dismissed`, `status` (goals) | `item` | +| `board/update` | `itemId`, `liked`, `dismissed`, `status` (goals); with feedback: `rating` (`up`/`down`/`none`), `reason` (thumbs down, 120 chars), `read` | `item` | | `board/media` | `itemId`, `index` | `mimeType`, base64 `data` | | `board/activity` | `limit` | `activity` with Hermes' session `title` | | `board/approvals` | `limit` | `approvals` with `sessionTitle` | | `board/identity` | — | `soul`, `memory`, `user`: `text` (64 KiB max), `updatedAt`, `truncated` | + +With `native-agent-board-feedback-v1` (2.19.0): + +| Route | Body | Returns | +|---|---|---| +| `board/read` | `itemIds` (up to 200), `read` | `updated` count | +| `board/promote` | `itemId` of an idea | the new goal `item`; the idea is hidden | + +Items carry `rating`, `reason` and `read`. `liked` stays for older apps and maps +to thumbs up. Hiding (`dismissed`) is the app's delete and can be undone; hidden +items never reach the agent's `list`, which returns rating, reason and read so +the agent can post more of what the user rates up. Boards from before 2.19.0 +keep their likes as thumbs up and start fully read. diff --git a/loopdy_plugin/agent_board.py b/loopdy_plugin/agent_board.py index aa6ad1f..ddef474 100644 --- a/loopdy_plugin/agent_board.py +++ b/loopdy_plugin/agent_board.py @@ -27,6 +27,8 @@ logger = logging.getLogger(__name__) CAPABILITY = "native-agent-board-v1" +# Thumbs up/down with a reason, read state, bulk read and idea → goal. +FEEDBACK_CAPABILITY = "native-agent-board-feedback-v1" TOOL_NAME = "bighelp_board" KINDS = ("feed", "idea", "goal") GOAL_SECTIONS = ("tracking", "goal") @@ -41,6 +43,9 @@ MAX_IMAGE_BYTES = 8 * 1024 * 1024 MAX_ITEMS_PER_KIND = 500 MAX_ACTIVITY = 1_000 +MAX_REASON = 120 +MAX_READ_BATCH = 200 +RATINGS = {"down": -1, "none": 0, "up": 1} MAX_APPROVALS = 1_000 _ITEM_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}\Z") _IMAGE_TYPES = ( @@ -108,6 +113,17 @@ def __init__(self, directory: Path): description TEXT NOT NULL DEFAULT '', command TEXT NOT NULL DEFAULT '', choice TEXT NOT NULL DEFAULT '', created REAL NOT NULL); """) + columns = {row["name"] for row in db.execute("PRAGMA table_info(items)")} + if "rating" not in columns: + # Likes become thumbs up. Everything already on the board counts + # as read, so an update doesn't turn it all into "new". + db.executescript(""" + ALTER TABLE items ADD COLUMN rating INTEGER NOT NULL DEFAULT 0; + ALTER TABLE items ADD COLUMN reason TEXT NOT NULL DEFAULT ''; + ALTER TABLE items ADD COLUMN read INTEGER NOT NULL DEFAULT 0; + UPDATE items SET rating=1 WHERE liked=1; + UPDATE items SET read=1; + """) @contextmanager def _db(self): @@ -185,19 +201,59 @@ def update_goal(self, item_id: Any, *, note: Any = None, status: Any = None, return self._item(db.execute("SELECT * FROM items WHERE id=?", (item_id,)).fetchone()) def set_flags(self, item_id: str, *, liked: bool | None = None, dismissed: bool | None = None, - status: str | None = None) -> dict: + status: str | None = None, rating: str | None = None, reason: str | None = None, + read: bool | None = None) -> dict: + """What the person did with an item in the app. ``liked`` is the older + app's heart; it maps onto the thumbs rating.""" + if rating is not None and rating not in RATINGS: + raise BoardError("rating must be up, down or none.") with self._db() as db: row = db.execute("SELECT * FROM items WHERE id=?", (item_id,)).fetchone() if row is None: raise BoardError("That item no longer exists.") if status is not None and (row["kind"] != "goal" or status not in GOAL_STATUSES): raise BoardError("Only goals have a status.") - db.execute("UPDATE items SET liked=?, dismissed=?, status=?, updated=? WHERE id=?", ( - int(row["liked"] if liked is None else liked), + score = row["rating"] + if rating is not None: + score = RATINGS[rating] + elif liked is not None: + score = 1 if liked else (0 if score == 1 else score) + next_reason = row["reason"] if reason is None else _clean(reason, MAX_REASON, field="reason") + if rating is not None and reason is None: + next_reason = "" + if score != -1: + next_reason = "" + db.execute("""UPDATE items SET liked=?, rating=?, reason=?, read=?, dismissed=?, status=?, updated=? + WHERE id=?""", ( + int(score == 1), score, next_reason, + int(row["read"] if read is None else read), int(row["dismissed"] if dismissed is None else dismissed), row["status"] if status is None else status, time.time(), item_id)) return self._item(db.execute("SELECT * FROM items WHERE id=?", (item_id,)).fetchone()) + def mark_read(self, item_ids: list[str], *, read: bool = True) -> int: + """Marks items read (or unread) together, as the app shows them.""" + if len(item_ids) > MAX_READ_BATCH: + raise BoardError(f"Mark at most {MAX_READ_BATCH} items at once.") + ids = [item_id for item_id in dict.fromkeys(item_ids) if _ITEM_ID.fullmatch(item_id)] + if not ids: + return 0 + with self._db() as db: + return db.execute(f"UPDATE items SET read=? WHERE id IN ({','.join('?' for _ in ids)})", + (int(read), *ids)).rowcount + + def promote_idea(self, item_id: Any, *, now: float | None = None) -> dict: + """An idea the person wants to pursue becomes one of their goals.""" + item_id = _clean(item_id, 64, field="id", required=True) + with self._db() as db: + row = db.execute("SELECT * FROM items WHERE id=? AND kind='idea'", (item_id,)).fetchone() + if row is None: + raise BoardError("No idea has that id.") + goal = self.publish("goal", title=row["title"], body=row["body"], icon=row["icon"], section="goal", + source=row["source"] or "From an idea", now=now) + self.set_flags(item_id, dismissed=True) + return goal + def remove(self, item_id: Any) -> bool: item_id = _clean(item_id, 64, field="id", required=True) with self._db() as db: @@ -300,7 +356,9 @@ def _item(row) -> dict: "id": row["id"], "kind": row["kind"], "title": row["title"], "body": row["body"], "icon": row["icon"], "section": row["section"], "status": row["status"], "note": row["note"], "links": json.loads(row["links"]), "images": images, "source": row["source"], - "liked": bool(row["liked"]), "dismissed": bool(row["dismissed"]), + "liked": row["rating"] == 1, "dismissed": bool(row["dismissed"]), + "rating": {-1: "down", 1: "up"}.get(row["rating"], "none"), "reason": row["reason"], + "read": bool(row["read"]), "createdAt": int(row["created"]), "updatedAt": int(row["updated"]), } @@ -428,7 +486,8 @@ def session_titles(profile: str, session_ids: list[str]) -> dict[str, str]: "update with optional images and links); 'idea' proposes something you could do for the user; " "'goal' adds or updates a Goal (section 'tracking' for things you watch, 'goal' for the user's " "own goals) with a short status note; 'update_goal' changes a goal's note or marks it done; " - "'list' shows recent items so you can update rather than duplicate; 'remove' deletes one. " + "'list' shows recent items with the user's rating (up/down), reason and read state, so you can " + "update rather than duplicate and post more of what they rate up; 'remove' deletes one. " "Only publish what the user asked you to surface. Never create schedules or posts on your own " "initiative; see the bighelp-feed-and-ideas skill." ) @@ -480,8 +539,10 @@ def handle_tool(args: dict, store: BoardStore | None = None) -> str: elif action == "list": kind = args.get("kind") items = store.items((kind,) if kind in KINDS else KINDS, limit=30, include_dismissed=False) + # The person's thumbs, reasons and read state tell the agent what's worth posting. return json.dumps({"items": [{key: item[key] for key in - ("id", "kind", "title", "section", "status", "note", "createdAt")} + ("id", "kind", "title", "section", "status", "note", "source", "createdAt", + "rating", "reason", "read")} for item in items]}) elif action == "remove": return json.dumps({"removed": store.remove(args.get("id"))}) diff --git a/loopdy_plugin/link_contracts.py b/loopdy_plugin/link_contracts.py index d0230b7..27c10aa 100644 --- a/loopdy_plugin/link_contracts.py +++ b/loopdy_plugin/link_contracts.py @@ -112,7 +112,7 @@ def parse_direct_enrollment(payload: dict[str, Any]) -> dict[str, Any]: "body_fat_percentage", "workout", ) -PLUGIN_VERSION = "2.18.2" +PLUGIN_VERSION = "2.19.0" AVAILABLE_WIKI_OPERATIONS = available_wiki_operations() GROUPS_OPERATIONS = frozenset( { diff --git a/loopdy_plugin/native_api.py b/loopdy_plugin/native_api.py index 478cd45..7408a94 100644 --- a/loopdy_plugin/native_api.py +++ b/loopdy_plugin/native_api.py @@ -6,7 +6,7 @@ import logging import re import sys -from typing import Any, Literal, TypeVar +from typing import Annotated, Any, Literal, TypeVar from fastapi import APIRouter, Request from fastapi.responses import JSONResponse, Response @@ -334,6 +334,18 @@ class _BoardUpdate(_Body): liked: StrictBool | None = None dismissed: StrictBool | None = None status: Literal["active", "done"] | None = None + rating: Literal["up", "down", "none"] | None = None + reason: str | None = Field(default=None, max_length=120) + read: StrictBool | None = None + + +class _BoardRead(_Body): + itemIds: list[Annotated[str, Field(pattern=_BOARD_ITEM_ID)]] = Field(min_length=1, max_length=200) + read: StrictBool = True + + +class _BoardItem(_Body): + itemId: str = Field(pattern=_BOARD_ITEM_ID) class _BoardMedia(_Body): @@ -368,7 +380,12 @@ def _board(request: Request, owner: NativeContext, body: _Body, operation: str) include_dismissed=body.includeDismissed)} elif operation == "update" and isinstance(body, _BoardUpdate): result = {"item": store.set_flags(body.itemId, liked=body.liked, dismissed=body.dismissed, - status=body.status)} + status=body.status, rating=body.rating, reason=body.reason, + read=body.read)} + elif operation == "read" and isinstance(body, _BoardRead): + result = {"updated": store.mark_read(body.itemIds, read=body.read)} + elif operation == "promote" and isinstance(body, _BoardItem): + result = {"item": store.promote_idea(body.itemId)} elif operation == "media" and isinstance(body, _BoardMedia): mime, data = store.image(body.itemId, body.index) result = media_payload(mime, data) @@ -412,6 +429,16 @@ async def board_update(request: Request) -> Response: return await _board_request(request, _BoardUpdate, "update", MAX_BODY_BYTES) +@router.post("/board/read") +async def board_read(request: Request) -> Response: + return await _board_request(request, _BoardRead, "read", MAX_BODY_BYTES) + + +@router.post("/board/promote") +async def board_promote(request: Request) -> Response: + return await _board_request(request, _BoardItem, "promote", MAX_BODY_BYTES) + + @router.post("/board/media") async def board_media(request: Request) -> Response: return await _board_request(request, _BoardMedia, "media", _BOARD_MEDIA_BYTES) diff --git a/loopdy_plugin/native_context.py b/loopdy_plugin/native_context.py index a4c46ea..a779da9 100644 --- a/loopdy_plugin/native_context.py +++ b/loopdy_plugin/native_context.py @@ -237,13 +237,16 @@ def skip(feature: str, reason: str) -> None: skip("native-workspace-recent-v1", "workspace file support is unimportable.") try: from .agent_board import CAPABILITY as board_capability + from .agent_board import FEEDBACK_CAPABILITY as board_feedback_capability from .agent_board import available as board_available if board_available(): - features.append(board_capability) + features.extend((board_capability, board_feedback_capability)) else: skip(board_capability, "public profile helpers are unimportable.") + skip(board_feedback_capability, "public profile helpers are unimportable.") except ImportError: skip("native-agent-board-v1", "agent board support is unimportable.") + skip("native-agent-board-feedback-v1", "agent board support is unimportable.") try: from .native_attachments import CAPABILITY as attachments_capability from .native_attachments import MEDIA_CAPABILITY as media_capability diff --git a/plugin.yaml b/plugin.yaml index 510d760..3d13a2a 100644 --- a/plugin.yaml +++ b/plugin.yaml @@ -2,7 +2,7 @@ manifest_version: 1 name: loopdy label: Loopdy kind: platform -version: "2.18.2" +version: "2.19.0" license: Apache-2.0 description: > Native authenticated Hermes workspace controls, media voice, approvals, and diff --git a/skills/bighelp-feed-and-ideas/SKILL.md b/skills/bighelp-feed-and-ideas/SKILL.md index 507d146..737a9bd 100644 --- a/skills/bighelp-feed-and-ideas/SKILL.md +++ b/skills/bighelp-feed-and-ideas/SKILL.md @@ -54,6 +54,20 @@ The bighelp app shows three boards next to the chat. You write to them with the `package-hollywood-feed`), then `update_goal` with a fresh `note` whenever it changes. Mark `status: done` when it is finished. +## Learn from the user's thumbs + +The user can rate each item thumbs up or thumbs down in the app, sometimes with +a reason ("Not relevant", "Too frequent", "Already knew", "Wrong timing"). +`action: list` returns each item's `rating` (`up`, `down` or `none`), `reason` +and `read`. Check it before a scheduled run posts: + +- Post more of what they rate up: the same topics, sources and format. +- Cut back on what they rate down, and act on the reason: drop an irrelevant + topic, post less often, skip what they already knew, or move the time. +- Items the user deleted never appear in `list`; don't post them again. +- Unread items mean the user hasn't looked yet. Don't pile more on top of a + long unread stretch; one good post beats several. + ## When the user replies from the app A **Discuss** tap opens a chat that quotes the post or idea. Treat it as the user diff --git a/tests/test_agent_board.py b/tests/test_agent_board.py index 6f3cce5..1108864 100644 --- a/tests/test_agent_board.py +++ b/tests/test_agent_board.py @@ -83,6 +83,76 @@ def test_tool_reports_errors_to_the_agent_instead_of_raising(self): self.assertIn("error", json.loads(handle_tool({"action": "launch"}, self.store))) + def test_feedback_rates_items_with_a_reason_and_the_agent_sees_it(self): + post = self.store.publish("feed", title="Evening AI news", source="Evening AI news") + other = self.store.publish("feed", title="Stock tips") + self.assertEqual((post["rating"], post["reason"], post["read"]), ("none", "", False)) + liked = self.store.set_flags(post["id"], rating="up") + self.assertEqual((liked["rating"], liked["liked"]), ("up", True)) + down = self.store.set_flags(other["id"], rating="down", reason="Not relevant") + self.assertEqual((down["rating"], down["reason"], down["liked"]), ("down", "Not relevant", False)) + # A reason belongs to a thumbs down only. + self.assertEqual(self.store.set_flags(post["id"], reason="Too frequent")["reason"], "") + # Older apps still send liked. + self.assertEqual(self.store.set_flags(other["id"], liked=True)["rating"], "up") + self.assertEqual(self.store.set_flags(other["id"], liked=False)["rating"], "none") + with self.assertRaises(BoardError): + self.store.set_flags(post["id"], rating="sideways") + self.store.set_flags(other["id"], rating="down", reason="Already knew") + listed = json.loads(handle_tool({"action": "list", "kind": "feed"}, self.store))["items"] + by_title = {item["title"]: item for item in listed} + self.assertEqual(by_title["Evening AI news"]["rating"], "up") + self.assertEqual((by_title["Stock tips"]["rating"], by_title["Stock tips"]["reason"]), ("down", "Already knew")) + self.assertEqual(by_title["Stock tips"]["read"], False) + self.assertIn("source", by_title["Evening AI news"]) + + def test_read_state_survives_and_marks_in_bulk(self): + first = self.store.publish("feed", title="One") + second = self.store.publish("idea", title="Two") + self.assertEqual(self.store.mark_read([first["id"], second["id"], "gone"], read=True), 2) + self.assertTrue(all(item["read"] for item in BoardStore(self.root / "board").items())) + self.assertFalse(self.store.set_flags(first["id"], read=False)["read"]) + with self.assertRaises(BoardError): + self.store.mark_read(["x"] * 201) + + def test_hide_can_be_undone_and_hidden_items_stay_out_of_the_agents_list(self): + item = self.store.publish("idea", title="Plan a trip") + self.store.set_flags(item["id"], dismissed=True) + self.assertEqual(json.loads(handle_tool({"action": "list", "kind": "idea"}, self.store))["items"], []) + self.store.set_flags(item["id"], dismissed=False) + self.assertEqual([row["title"] for row in self.store.items(("idea",))], ["Plan a trip"]) + + def test_an_idea_turns_into_a_goal(self): + idea = self.store.publish("idea", title="Sleep by 11", body="I can nudge you at 10:30.", icon="🌙") + goal = self.store.promote_idea(idea["id"]) + self.assertEqual((goal["kind"], goal["title"], goal["icon"], goal["status"]), ("goal", "Sleep by 11", "🌙", "active")) + self.assertEqual(goal["section"], "goal") + self.assertEqual(self.store.items(("idea",)), [], "The idea moved to Goals") + with self.assertRaises(BoardError): + self.store.promote_idea(goal["id"]) + + def test_old_boards_keep_likes_and_start_read(self): + legacy = self.root / "legacy" + legacy.mkdir() + import sqlite3 + db = sqlite3.connect(legacy / "board.sqlite3") + db.executescript("""CREATE TABLE items( + id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, + body TEXT NOT NULL DEFAULT '', icon TEXT NOT NULL DEFAULT '', + section TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', links TEXT NOT NULL DEFAULT '[]', + images TEXT NOT NULL DEFAULT '[]', source TEXT NOT NULL DEFAULT '', + liked INTEGER NOT NULL DEFAULT 0, dismissed INTEGER NOT NULL DEFAULT 0, + created REAL NOT NULL, updated REAL NOT NULL); + INSERT INTO items(id,kind,title,liked,created,updated) VALUES('a','feed','Liked',1,1,1); + INSERT INTO items(id,kind,title,liked,created,updated) VALUES('b','feed','Plain',0,2,2);""") + db.commit() + db.close() + items = {item["id"]: item for item in BoardStore(legacy).items()} + self.assertEqual((items["a"]["rating"], items["b"]["rating"]), ("up", "none")) + self.assertTrue(items["a"]["read"] and items["b"]["read"], "Nothing already there shows as new") + self.assertFalse(BoardStore(legacy).publish("feed", title="Fresh")["read"]) + class ActivityRecorderTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory() diff --git a/tests/test_native_api.py b/tests/test_native_api.py index 55f9122..ea355cf 100644 --- a/tests/test_native_api.py +++ b/tests/test_native_api.py @@ -144,7 +144,7 @@ def test_context_exact_safe_identity_cookie_and_no_unimplemented_features(self): expected.extend(("native-workspace-files-v1", "native-workspace-recent-v1")) from loopdy_plugin.agent_board import available as board_available if board_available(): - expected.append("native-agent-board-v1") + expected.extend(("native-agent-board-v1", "native-agent-board-feedback-v1")) from loopdy_plugin.native_attachments import available as attachments_available if attachments_available(): expected.extend(("native-agent-attachments-v1", "native-agent-media-v1")) @@ -267,6 +267,25 @@ def board(operation, payload): self.assertEqual(board("list", {"agentId": "missing-profile"}).status_code, 404) self.assertEqual(board("list", {"agentId": "default", "kinds": ["secret"]}).status_code, 422) + # Thumbs with a reason, read state in bulk, undo, and idea → goal. + rated = board("update", {"agentId": "default", "itemId": post["id"], "rating": "down", + "reason": "Too frequent", "read": True}).json()["item"] + self.assertEqual((rated["rating"], rated["reason"], rated["read"], rated["liked"]), + ("down", "Too frequent", True, False)) + self.assertEqual(board("update", {"agentId": "default", "itemId": post["id"], "rating": "meh"}).status_code, 422) + self.assertEqual(board("update", {"agentId": "default", "itemId": post["id"], + "reason": "x" * 121}).status_code, 422) + read = board("read", {"agentId": "default", "itemIds": [post["id"], "pkg"], "read": False}) + self.assertEqual(read.json()["updated"], 2) + self.assertEqual(board("read", {"agentId": "default", "itemIds": ["../x"]}).status_code, 422) + hidden = board("update", {"agentId": "default", "itemId": "pkg", "dismissed": True}).json()["item"] + self.assertTrue(hidden["dismissed"]) + self.assertFalse(board("update", {"agentId": "default", "itemId": "pkg", "dismissed": False}).json()["item"]["dismissed"]) + idea = store.publish("idea", title="Sleep by 11", icon="🌙") + goal = board("promote", {"agentId": "default", "itemId": idea["id"]}).json()["item"] + self.assertEqual((goal["kind"], goal["title"]), ("goal", "Sleep by 11")) + self.assertEqual(board("promote", {"agentId": "default", "itemId": "pkg"}).status_code, 404) + def test_template_headers_are_required_exact_and_echoed(self): headers = self.headers() response = self.post("list", {"agentId": "default"}, headers)