Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion docs/AGENT_BOARD.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
73 changes: 67 additions & 6 deletions loopdy_plugin/agent_board.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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 = (
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"]),
}

Expand Down Expand Up @@ -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."
)
Expand Down Expand Up @@ -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"))})
Expand Down
2 changes: 1 addition & 1 deletion loopdy_plugin/link_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
{
Expand Down
31 changes: 29 additions & 2 deletions loopdy_plugin/native_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 4 additions & 1 deletion loopdy_plugin/native_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion plugin.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions skills/bighelp-feed-and-ideas/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
70 changes: 70 additions & 0 deletions tests/test_agent_board.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading
Loading