From 912417792f2ba270beb923c11fe6a1941c6a188c Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Thu, 8 Oct 2026 02:05:31 +0000 Subject: [PATCH] seeds: ship create_nextcloud_task as a starter skill Turn the generated productivity_management.create_nextcloud_task body into a committed seed in the CODEGEN.md folder format. It goes through the Nextcloud bridge: GET /tasklists picks a VTODO-capable target (never an event-only calendar or a Deck board) and POST /tasks creates the task; the LLM bridge phrases the summary/description. The CONTRACT mirrors the four bridge config vars the body reads, so the seed passes the integration and contract checks. Register productivity_management in CATEGORY_DESCRIPTIONS so the seed's category is described for navigation, and list the seed in tests/test_seed_skills.py. --- AGENTS.md | 9 +- .../create_nextcloud_task/contract.json | 6 + .../create_nextcloud_task/manifest.json | 3 + .../create_nextcloud_task/skill.py | 204 +++++++++++ .../create_nextcloud_task/skill.test.py | 345 ++++++++++++++++++ semif_agent/skills.py | 4 + tests/test_seed_skills.py | 1 + 7 files changed, 569 insertions(+), 3 deletions(-) create mode 100644 seeds/productivity_management/create_nextcloud_task/contract.json create mode 100644 seeds/productivity_management/create_nextcloud_task/manifest.json create mode 100644 seeds/productivity_management/create_nextcloud_task/skill.py create mode 100644 seeds/productivity_management/create_nextcloud_task/skill.test.py diff --git a/AGENTS.md b/AGENTS.md index e2feebc..03a85f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -833,9 +833,12 @@ CLI, unit tests (24) + integration tests (2). resumes, resolves the target calendar with a SemIf choice over the owned calendars — a strong winner is used, otherwise the configured default); `calendar.next_event` is the read counterpart (Nextcloud CalDAV, recurring - events expanded server-side); `simplex.next_message` (read via the forwarding - bridge) and `simplex.connect_link` (show/create the forwarding bot's contact - link) are the messenger seeds; `time.now`, `time.date`, `time.set_timer`, and + events expanded server-side); `productivity_management.create_nextcloud_task` + adds a task to a Nextcloud task list through the Nextcloud bridge (`GET + /tasklists` for a VTODO-capable target, `POST /tasks` to create it, the LLM + bridge to phrase the summary/description); `simplex.next_message` (read via the + forwarding bridge) and `simplex.connect_link` (show/create the forwarding bot's + contact link) are the messenger seeds; `time.now`, `time.date`, `time.set_timer`, and `time.set_alarm` are the local time utilities (`compute` transport, empty contract) — they read the host clock and schedule on `ctx.timers`. Local time is the top-level `timezone` config value (an IANA name such as diff --git a/seeds/productivity_management/create_nextcloud_task/contract.json b/seeds/productivity_management/create_nextcloud_task/contract.json new file mode 100644 index 0000000..9710aa8 --- /dev/null +++ b/seeds/productivity_management/create_nextcloud_task/contract.json @@ -0,0 +1,6 @@ +{ + "nextcloud_bridge_url": "Base URL of the local Nextcloud bridge, e.g. http://127.0.0.1:5230 (no trailing slash needed); used to list task lists and create the task.", + "nextcloud_bridge_token": "Shared secret for the Nextcloud bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", + "llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to phrase the task title and description.", + "llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth." +} diff --git a/seeds/productivity_management/create_nextcloud_task/manifest.json b/seeds/productivity_management/create_nextcloud_task/manifest.json new file mode 100644 index 0000000..de0247d --- /dev/null +++ b/seeds/productivity_management/create_nextcloud_task/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Add a single task to a Nextcloud task list from a request such as \"add a task to eat more hot dogs\"." +} diff --git a/seeds/productivity_management/create_nextcloud_task/skill.py b/seeds/productivity_management/create_nextcloud_task/skill.py new file mode 100644 index 0000000..e24c246 --- /dev/null +++ b/seeds/productivity_management/create_nextcloud_task/skill.py @@ -0,0 +1,204 @@ +"""Add a single task to a Nextcloud task list. + +Real integration: the Nextcloud bridge over HTTP, which fronts the user's +Nextcloud (CalDAV VTODO). The bridge URL/token and the LLM bridge URL/token are +operational values supplied through `ctx.config` (declared in CONTRACT); the task +summary and description are derived from `request.text`. + +`GET /tasklists` returns only VTODO-capable task lists (the bridge excludes +event-only calendars and Nextcloud Deck boards), so a task can never be written +to a collection that rejects it. When the account has several task lists the +target is resolved by a single SemIf choice over them; otherwise the sole list is +used. The task is created for real with `POST /tasks` and the real outcome is +reported — a failure is never dressed up as success. +""" + +from __future__ import annotations + +import json +import urllib.error +import urllib.request + +from semif_agent.decisions import DecisionRequest, Option +from semif_agent.skills import ActionResult + +INTEGRATION = { + "service": "nextcloud", + "transport": "http", + "config_vars": [ + "nextcloud_bridge_url", + "nextcloud_bridge_token", + "llm_bridge_url", + "llm_bridge_token", + ], +} + +CONTRACT = { + "nextcloud_bridge_url": "Base URL of the local Nextcloud bridge, e.g. http://127.0.0.1:5230 (no trailing slash needed); used to list task lists and create the task.", + "nextcloud_bridge_token": "Shared secret for the Nextcloud bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", + "llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to phrase the task title and description.", + "llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", +} + + +def _headers(token): + """Build request headers, sending the bridge token only when one is set.""" + headers = {"Content-Type": "application/json"} + if token: + headers["X-Semif-Token"] = token + return headers + + +def _call(method, url, headers, payload=None, timeout=25): + """Perform one HTTP call, returning (status, decoded_json_or_error_dict).""" + data = json.dumps(payload).encode("utf-8") if payload is not None else None + req = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=timeout) as response: + body = response.read().decode("utf-8") + return response.status, (json.loads(body) if body else {}) + except urllib.error.HTTPError as exc: + try: + detail = json.loads(exc.read().decode("utf-8")) + except Exception: + detail = {"error": str(exc)} + return exc.code, detail + except (urllib.error.URLError, ValueError) as exc: + return None, {"error": str(exc)} + + +def _parse_json_object(text): + """Pull the first JSON object out of a model reply, or return None.""" + if not text: + return None + start = text.find("{") + end = text.rfind("}") + if start == -1 or end <= start: + return None + try: + data = json.loads(text[start : end + 1]) + except ValueError: + return None + return data if isinstance(data, dict) else None + + +def _extract_task(ctx, request): + """Ask the LLM bridge for (summary, description) of the task; else an error.""" + llm_url = str(ctx.config.get("llm_bridge_url", "") or "").rstrip("/") + headers = _headers(ctx.config.get("llm_bridge_token", "")) + messages = [ + { + "role": "system", + "content": ( + "You turn a user's request into a single to-do task. Reply with " + 'only a JSON object: {"summary": "", ' + '"description": ""}.' + ), + }, + {"role": "user", "content": request.text or ""}, + ] + status, payload = _call( + "POST", + f"{llm_url}/chat", + headers, + {"messages": messages, "max_tokens": 200}, + ) + if status != 200: + return ( + None, + None, + f"could not phrase the task via the LLM bridge at {llm_url}: " + f"status {status}, {payload.get('error', payload)}", + ) + data = _parse_json_object(payload.get("text") or "") + if not data or not str(data.get("summary") or "").strip(): + return ( + None, + None, + f"LLM bridge at {llm_url} returned no usable task text: " + f"{payload.get('text')!r}", + ) + return ( + str(data["summary"]).strip(), + str(data.get("description") or "").strip(), + None, + ) + + +def act(ctx, request) -> ActionResult: + """Add one task to the chosen Nextcloud task list and report the result.""" + decisions = [] + base_url = str(ctx.config.get("nextcloud_bridge_url", "") or "").rstrip("/") + nc_headers = _headers(ctx.config.get("nextcloud_bridge_token", "")) + + # 1. Phrase the task from the request via the LLM bridge. + summary, description, llm_error = _extract_task(ctx, request) + if llm_error: + return ActionResult( + action_log=llm_error, + new_state=request.text, + decisions=decisions, + ) + + # 2. Find the task list to write to (the bridge returns only VTODO-capable + # task lists, so an event-only calendar can never be chosen). + status, payload = _call("GET", f"{base_url}/tasklists", nc_headers) + if status != 200: + return ActionResult( + action_log=( + f"could not list Nextcloud task lists from {base_url}: " + f"status {status}, {payload.get('error', payload)}" + ), + new_state=request.text, + decisions=decisions, + ) + task_lists = [c for c in (payload.get("tasklists") or []) if c.get("name")] + if not task_lists: + return ActionResult( + action_log="no Nextcloud task lists are available to add a task to", + new_state=request.text, + decisions=decisions, + ) + + if len(task_lists) == 1: + target = task_lists[0]["name"] + else: + decision = DecisionRequest( + state=request.text, + question="Which Nextcloud task list should the new task be added to?", + options=[ + Option(c["name"], c.get("label") or c["name"]) for c in task_lists + ], + ) + result = ctx.engine.call(decision) + decisions.append((decision, result)) + target = result.selected + target_label = next( + (c.get("label") or c["name"] for c in task_lists if c["name"] == target), + target, + ) + + # 3. Create the task for real through the bridge. + status, payload = _call( + "POST", + f"{base_url}/tasks", + nc_headers, + {"calendar": target, "summary": summary, "description": description}, + ) + if status != 200 or not payload.get("ok"): + return ActionResult( + action_log=( + f"failed to add task \"{summary}\" to Nextcloud task list " + f"\"{target_label}\": status {status}, {payload.get('error', payload)}" + ), + new_state=request.text, + decisions=decisions, + ) + + uid = payload.get("uid", "") + calendar = payload.get("calendar", target) + report = ( + f'added task "{summary}" to Nextcloud task list "{target_label}" ' + f"(calendar={calendar}, uid={uid})" + ) + return ActionResult(action_log=report, new_state=report, decisions=decisions) diff --git a/seeds/productivity_management/create_nextcloud_task/skill.test.py b/seeds/productivity_management/create_nextcloud_task/skill.test.py new file mode 100644 index 0000000..e89f663 --- /dev/null +++ b/seeds/productivity_management/create_nextcloud_task/skill.test.py @@ -0,0 +1,345 @@ +"""Hermetic mechanics test for productivity_management.create_nextcloud_task. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the Nextcloud bridge (`GET /tasklists`, `POST /tasks`) and the +LLM bridge's `POST /chat`. This proves the body phrases the task through the LLM +bridge, picks a task list (the sole one, or a SemIf choice when there are +several), creates the task through the bridge, and fails honestly when the LLM +bridge or the Nextcloud bridge errors. It does NOT prove the live integration — +only a real run against the user's Nextcloud does. +""" + +import json +import socket +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +def make_handler(routes, seen): + """Build a request handler that records every request and replays `routes`.""" + + class Handler(BaseHTTPRequestHandler): + def _respond(self): + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) if length else b"" + try: + body = json.loads(raw.decode("utf-8")) if raw else None + except ValueError: + body = raw.decode("utf-8", "replace") + seen.append( + { + "method": self.command, + "path": self.path, + "headers": {k.lower(): v for k, v in self.headers.items()}, + "body": body, + } + ) + key = (self.command, self.path.split("?")[0]) + status, payload = routes.get(key, (404, {"error": "no route"})) + data = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + do_GET = _respond + do_POST = _respond + + def log_message(self, *args): + pass + + return Handler + + +def start_server(routes): + seen = [] + server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(routes, seen)) + threading.Thread(target=server.serve_forever, daemon=True).start() + url = "http://127.0.0.1:%d" % server.server_address[1] + return server, seen, url + + +def stop(server): + server.shutdown() + server.server_close() + + +def closed_port_url(): + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() + return "http://127.0.0.1:%d" % port + + +class FakeResult: + """Minimal stand-in for a DecisionResult: the body only reads `.selected`.""" + + def __init__(self, selected): + self.selected = selected + + +class FakeEngine: + """Test-only decision engine; records the requests the body asked for.""" + + def __init__(self, choice=None): + self.choice = choice + self.calls = [] + + def call(self, decision): + self.calls.append(decision) + return FakeResult(self.choice) + + +def test_happy_path_single_task_list(): + llm_routes = { + ("POST", "/chat"): ( + 200, + { + "text": '{"summary": "Eat hot dogs", ' + '"description": "Buy and eat hot dogs"}' + }, + ) + } + nc_routes = { + ("GET", "/tasklists"): ( + 200, + {"tasklists": [{"name": "tasks", "label": "Tasks"}]}, + ), + ("POST", "/tasks"): ( + 200, + {"ok": True, "uid": "uid-1", "calendar": "tasks"}, + ), + } + llm_server, llm_seen, llm_url = start_server(llm_routes) + nc_server, nc_seen, nc_url = start_server(nc_routes) + try: + engine = FakeEngine() + ctx = ActionContext( + engine=engine, + config={ + "nextcloud_bridge_url": nc_url, + "nextcloud_bridge_token": "nc-secret", + "llm_bridge_url": llm_url, + "llm_bridge_token": "llm-secret", + }, + ) + request = Request("Add a task in next cloud for eating hot dogs.") + result = skill.act(ctx, request) + + assert not engine.calls, "a single task list must not need a decision" + assert "Eat hot dogs" in result.action_log, result.action_log + assert "Tasks" in result.action_log, result.action_log + assert "uid-1" in result.action_log, result.action_log + + assert len(llm_seen) == 1, llm_seen + chat = llm_seen[0] + assert chat["method"] == "POST", chat + assert chat["path"] == "/chat", chat + assert chat["headers"].get("x-semif-token") == "llm-secret", chat["headers"] + assert chat["body"]["messages"][1]["content"] == request.text, chat["body"] + assert "summary" in chat["body"]["messages"][0]["content"], chat["body"] + + assert [r["path"] for r in nc_seen] == ["/tasklists", "/tasks"], nc_seen + listing = nc_seen[0] + assert listing["method"] == "GET", listing + assert listing["headers"].get("x-semif-token") == "nc-secret", listing["headers"] + create = nc_seen[1] + assert create["method"] == "POST", create + assert create["headers"].get("x-semif-token") == "nc-secret", create["headers"] + assert create["body"] == { + "calendar": "tasks", + "summary": "Eat hot dogs", + "description": "Buy and eat hot dogs", + }, create["body"] + print("happy path:", result.action_log) + finally: + stop(llm_server) + stop(nc_server) + + +def test_multiple_task_lists_asks_and_omits_token_header(): + llm_routes = { + ("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'}) + } + nc_routes = { + ("GET", "/tasklists"): ( + 200, + { + "tasklists": [ + {"name": "tasks", "label": "Tasks"}, + {"name": "work", "label": "Work"}, + ] + }, + ), + ("POST", "/tasks"): (200, {"ok": True, "uid": "uid-2", "calendar": "work"}), + } + llm_server, llm_seen, llm_url = start_server(llm_routes) + nc_server, nc_seen, nc_url = start_server(nc_routes) + try: + engine = FakeEngine(choice="work") + ctx = ActionContext( + engine=engine, + config={ + "nextcloud_bridge_url": nc_url, + "nextcloud_bridge_token": "", + "llm_bridge_url": llm_url, + "llm_bridge_token": "", + }, + ) + result = skill.act( + ctx, Request("Add a task in next cloud for eating hot dogs.") + ) + + assert len(engine.calls) == 1, "two task lists must trigger one decision" + decision = engine.calls[0] + assert [o.id for o in decision.options] == ["tasks", "work"], decision.options + assert result.decisions, "the decision must be recorded on the result" + + assert "x-semif-token" not in llm_seen[0]["headers"], llm_seen[0]["headers"] + create = nc_seen[-1] + assert create["path"] == "/tasks", create + assert create["body"]["calendar"] == "work", create["body"] + assert create["body"]["description"] == "", create["body"] + assert "x-semif-token" not in create["headers"], create["headers"] + assert "Work" in result.action_log, result.action_log + print("decision path:", result.action_log) + finally: + stop(llm_server) + stop(nc_server) + + +def test_llm_bridge_failure_leaves_nextcloud_untouched(): + llm_routes = {("POST", "/chat"): (502, {"error": "model down"})} + nc_routes = { + ("GET", "/tasklists"): (200, {"tasklists": [{"name": "tasks"}]}) + } + llm_server, _llm_seen, llm_url = start_server(llm_routes) + nc_server, nc_seen, nc_url = start_server(nc_routes) + try: + ctx = ActionContext( + engine=FakeEngine(), + config={ + "nextcloud_bridge_url": nc_url, + "llm_bridge_url": llm_url, + }, + ) + result = skill.act(ctx, Request("Add a task in next cloud for hot dogs.")) + assert "could not phrase the task" in result.action_log, result.action_log + assert "model down" in result.action_log, result.action_log + assert nc_seen == [], "Nextcloud must not be touched when phrasing fails" + print("llm failure:", result.action_log) + finally: + stop(llm_server) + stop(nc_server) + + +def test_llm_reply_without_task_text(): + llm_routes = {("POST", "/chat"): (200, {"text": "I cannot help with that."})} + nc_routes = { + ("GET", "/tasklists"): (200, {"tasklists": [{"name": "tasks"}]}) + } + llm_server, _llm_seen, llm_url = start_server(llm_routes) + nc_server, nc_seen, nc_url = start_server(nc_routes) + try: + ctx = ActionContext( + engine=FakeEngine(), + config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url}, + ) + result = skill.act(ctx, Request("do something vague")) + assert "no usable task text" in result.action_log, result.action_log + assert nc_seen == [], "Nextcloud must not be touched without a task title" + print("unusable llm reply:", result.action_log) + finally: + stop(llm_server) + stop(nc_server) + + +def test_no_task_lists_available(): + llm_routes = { + ("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'}) + } + nc_routes = {("GET", "/tasklists"): (200, {"tasklists": []})} + llm_server, _llm_seen, llm_url = start_server(llm_routes) + nc_server, nc_seen, nc_url = start_server(nc_routes) + try: + ctx = ActionContext( + engine=FakeEngine(), + config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url}, + ) + result = skill.act(ctx, Request("Add a task in next cloud for hot dogs.")) + assert "no Nextcloud task lists" in result.action_log, result.action_log + assert [r["path"] for r in nc_seen] == ["/tasklists"], nc_seen + print("no task lists:", result.action_log) + finally: + stop(llm_server) + stop(nc_server) + + +def test_unreachable_nextcloud_bridge(): + llm_routes = { + ("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'}) + } + llm_server, _llm_seen, llm_url = start_server(llm_routes) + try: + ctx = ActionContext( + engine=FakeEngine(), + config={ + "nextcloud_bridge_url": closed_port_url(), + "llm_bridge_url": llm_url, + }, + ) + result = skill.act(ctx, Request("Add a task in next cloud for hot dogs.")) + assert "could not list Nextcloud task lists" in result.action_log, result.action_log + print("unreachable nextcloud:", result.action_log) + finally: + stop(llm_server) + + +def test_task_creation_failure_is_reported(): + llm_routes = { + ("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'}) + } + nc_routes = { + ("GET", "/tasklists"): ( + 200, + {"tasklists": [{"name": "tasks", "label": "Tasks"}]}, + ), + ("POST", "/tasks"): (502, {"error": "CalDAV rejected the VTODO"}), + } + llm_server, _llm_seen, llm_url = start_server(llm_routes) + nc_server, nc_seen, nc_url = start_server(nc_routes) + try: + ctx = ActionContext( + engine=FakeEngine(), + config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url}, + ) + result = skill.act(ctx, Request("Add a task in next cloud for hot dogs.")) + assert "failed to add task" in result.action_log, result.action_log + assert "CalDAV rejected the VTODO" in result.action_log, result.action_log + assert [r["path"] for r in nc_seen] == ["/tasklists", "/tasks"], nc_seen + print("creation failure:", result.action_log) + finally: + stop(llm_server) + stop(nc_server) + + +def main(): + test_happy_path_single_task_list() + test_multiple_task_lists_asks_and_omits_token_header() + test_llm_bridge_failure_leaves_nextcloud_untouched() + test_llm_reply_without_task_text() + test_no_task_lists_available() + test_unreachable_nextcloud_bridge() + test_task_creation_failure_is_reported() + print("ok") + + +if __name__ == "__main__": + main() diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 80b6b39..034129b 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -668,6 +668,10 @@ CATEGORY_DESCRIPTIONS: dict[str, str] = { "Time and date utilities: telling the current time or date, setting " "countdown timers, and setting alarms." ), + "productivity_management": ( + "Personal productivity: creating and managing the user's to-do tasks " + "and task lists." + ), "housekeeping": ( "Agent self-maintenance: deleting, reconfiguring, regenerating, and " "cancelling the agent's own skills." diff --git a/tests/test_seed_skills.py b/tests/test_seed_skills.py index b35ddc7..9480638 100644 --- a/tests/test_seed_skills.py +++ b/tests/test_seed_skills.py @@ -38,6 +38,7 @@ def test_expected_seeds_exist(): assert "time.date" in ids assert "time.set_timer" in ids assert "time.set_alarm" in ids + assert "productivity_management.create_nextcloud_task" in ids @pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])