Move skill packs to standalone repos (gabby/pack.<name>)

Each pack (browser, essentials, nextcloud, outlook, simplex) now lives in its
own Gitea repo and is cloned into the gitignored packs/ directory at setup.
packs/ is no longer tracked here.
This commit is contained in:
gabby committed 2026-10-13 21:13:44 +00:00
1 parent 0b02a3feac
commit faa0feaa36
90 files changed
+4 -8401

No files matched your search

+4 -1
View File
@@ -20,4 +20,7 @@ secrets.json
# of the shipped agent.
local/
*.egg-info/
*.bak.*
*.bak.*
# Skill packs live in their own repos (gabby/pack.<name>) and are cloned into
# packs/<name>/ at setup. They are not tracked here. See PACKGEN.md.
packs/
-26
View File
@@ -1,26 +0,0 @@
{
"name": "browser",
"title": "Browser",
"concern": "Real browser automation (Playwright): open a web page, read its text or links, take a screenshot, and click, type, or fill forms to carry out a task on a website.",
"categories": {
"browser": "Browser automation: opening a web page, reading its text or links, taking a screenshot, and clicking, typing, or filling forms to carry out a task on a website."
},
"bridges": ["browser"],
"requires": ["playwright"],
"enabled_by_default": false,
"config": {
"enabled": {"type": "bool", "default": false, "doc": "Load this pack's skills and run its bridge. Disabled by default: it needs the optional Playwright deps + browser binaries (scripts/bootstrap.sh --browser)."},
"host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."},
"port": {"type": "int", "default": 5232, "doc": "Bridge listen port."},
"token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."},
"engine": {"type": "str", "default": "chromium", "doc": "chromium | firefox | webkit."},
"headless": {"type": "bool", "default": true, "doc": "false shows the browser window (to sign in once)."},
"channel": {"type": "str", "default": "", "doc": "Use an already-installed browser channel (chrome/msedge) and skip Playwright's download."},
"executable_path": {"type": "str", "default": "", "doc": "Use a specific browser binary; wins over channel."},
"profile_dir": {"type": "str", "default": "", "doc": "Persistent profile directory (logins survive across calls)."},
"browsers_path": {"type": "str", "default": "", "doc": "PLAYWRIGHT_BROWSERS_PATH override."},
"screenshot_dir": {"type": "str", "default": "", "doc": "Where screenshots are saved."},
"default_timeout": {"type": "float", "default": 30.0, "doc": "Default navigation/action timeout (seconds)."},
"max_text_chars": {"type": "int", "default": 20000, "doc": "Bound on returned page text."}
}
}
@@ -1,4 +0,0 @@
{
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Open a web page in the browser bridge and report its title and readable text."
}
@@ -1,121 +0,0 @@
"""Open a web page in the browser bridge and report what is on it.
Real integration: the local browser bridge (`browser_bridge_url`,
`browser_bridge_token`); the body never drives a browser directly. It opens the
URL from the request, then reads the page's text through the bridge. The URL is
taken from the request, or asked for if the request does not contain one. A
missing URL or a bridge failure is reported honestly — never a fabricated page.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "browser",
"transport": "http",
"config_vars": ["browser_bridge_url", "browser_bridge_token"],
}
CONTRACT = {
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 60
EXCERPT_CHARS = 1200
_URL_RE = re.compile(r"https?://[^\s<>\"')]+", re.IGNORECASE)
class BrowserBridgeError(Exception):
"""A real failure talking to the local browser bridge."""
def _headers(ctx):
token = str(ctx.config.get("browser_bridge_token", "") or "").strip()
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
return headers
def _base(ctx):
base = str(ctx.config.get("browser_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BrowserBridgeError("browser_bridge_url is not configured")
return base
def _request(ctx, path, payload=None, params=None):
url = _base(ctx) + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = _headers(ctx)
data = None
method = "GET"
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
method = "POST"
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BrowserBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BrowserBridgeError(f"{method} {path}: {exc}") from exc
def _resolve_url(request):
"""The URL to open, or None. Uses the answer after a needs_input pause."""
if request.user_input is not None:
answer = (request.user_input or "").strip()
if not answer:
return None
match = _URL_RE.search(answer)
return match.group(0) if match else answer
match = _URL_RE.search(request.text or "")
return match.group(0) if match else None
def act(ctx, request):
url = _resolve_url(request)
if not url:
return ActionResult(
action_log="no web address in the request",
new_state=request.text,
needs_input="Which web address (URL) should I open?",
)
if not url.lower().startswith(("http://", "https://")):
url = "https://" + url
try:
opened = _request(ctx, "/goto", {"url": url})
page = _request(ctx, "/content", params={"format": "text", "max_chars": EXCERPT_CHARS})
except BrowserBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
title = opened.get("title") or page.get("title") or url
final_url = page.get("url") or opened.get("url") or url
status = opened.get("status")
body = (page.get("content") or "").strip()
excerpt = body[:EXCERPT_CHARS]
if len(body) > EXCERPT_CHARS or page.get("truncated"):
excerpt = excerpt.rstrip() + " …"
summary = f"Opened {title} ({final_url})"
if status is not None:
summary += f" [HTTP {status}]"
if excerpt:
report = f"{summary}:\n{excerpt}"
else:
report = f"{summary}: the page has no readable text."
return ActionResult(action_log=report, new_state=report)
@@ -1,147 +0,0 @@
"""Hermetic mechanics test for browser.open_page.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local browser bridge's `/goto` and `/content` routes. This
proves the body asks the bridge to open a URL and reports the page (and fails
honestly when the bridge is unavailable). It does NOT prove the live
integration — only a real run against a real browser does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("browser.open_page must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
title = "Example Domain"
body = "This domain is for use in illustrative examples."
status = 200
requests = []
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status):
raw = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
self.requests.append(("POST", self.path, self._read().decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path == "/goto":
self._send({"url": "https://example.com/", "title": self.title, "status": 200}, 200)
return
self._send({"error": "not found"}, 404)
def do_GET(self):
self.requests.append(("GET", self.path, ""))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/content"):
self._send(
{
"url": "https://example.com/",
"title": self.title,
"format": "text",
"content": self.body,
"truncated": False,
},
200,
)
return
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(status=200):
handler = type(
"Handler",
(BridgeHandler,),
{"status": status, "requests": []},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="open https://example.com"):
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": url, "browser_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_the_page():
server, handler, url = start_server()
try:
action = run(url)
assert "Example Domain" in action.action_log, action.action_log
assert "illustrative examples" in action.action_log, action.action_log
assert action.new_state == action.action_log
assert any(method == "POST" and path == "/goto" for method, path, _ in handler.requests)
assert any(method == "GET" and path.startswith("/content") for method, path, _ in handler.requests)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_url_asks_for_one():
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": "http://127.0.0.1:1"})
action = skill.act(ctx, Request("open a web page"))
assert action.needs_input, "a request with no URL must ask for one"
print(action.needs_input)
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "open https://example.com", "a failed open must not fake a page"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
action = run("http://127.0.0.1:1")
assert "browser.open_page" not in action.action_log, action.action_log
assert action.new_state == "open https://example.com"
print(action.action_log)
def main():
test_reports_the_page()
test_missing_url_asks_for_one()
test_bridge_error_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,4 +0,0 @@
{
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Read the readable text of a web page (a URL in the request, or the page the browser is already on) through the browser bridge."
}
@@ -1,93 +0,0 @@
"""Read the readable text of a web page through the browser bridge.
Real integration: the local browser bridge (`browser_bridge_url`,
`browser_bridge_token`); the body never drives a browser directly. If the
request names a URL it opens that page first, otherwise it reads the page the
browser is already on. A bridge failure is reported honestly — never invented
page text.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "browser",
"transport": "http",
"config_vars": ["browser_bridge_url", "browser_bridge_token"],
}
CONTRACT = {
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 60
TEXT_CHARS = 4000
_URL_RE = re.compile(r"https?://[^\s<>\"')]+", re.IGNORECASE)
class BrowserBridgeError(Exception):
"""A real failure talking to the local browser bridge."""
def _request(ctx, path, payload=None, params=None):
base = str(ctx.config.get("browser_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BrowserBridgeError("browser_bridge_url is not configured")
token = str(ctx.config.get("browser_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
data = None
method = "GET"
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
method = "POST"
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BrowserBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BrowserBridgeError(f"{method} {path}: {exc}") from exc
def _resolve_url(request):
source = request.user_input if request.user_input is not None else request.text
match = _URL_RE.search(source or "")
return match.group(0) if match else None
def act(ctx, request):
url = _resolve_url(request)
try:
if url:
_request(ctx, "/goto", {"url": url})
page = _request(ctx, "/content", params={"format": "text", "max_chars": TEXT_CHARS})
except BrowserBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
title = page.get("title") or ""
final_url = page.get("url") or url or "the current page"
text = (page.get("content") or "").strip()
if not text:
report = f"{title or final_url} ({final_url}) has no readable text."
return ActionResult(action_log=report, new_state=report)
if len(text) > TEXT_CHARS or page.get("truncated"):
text = text[:TEXT_CHARS].rstrip() + " …"
heading = f"{title} ({final_url})" if title else str(final_url)
report = f"{heading}:\n{text}"
return ActionResult(action_log=report, new_state=report)
@@ -1,138 +0,0 @@
"""Hermetic mechanics test for browser.read_page.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local browser bridge's `/goto` and `/content` routes. This
proves the body reads the page through the bridge (navigating first only when the
request names a URL) and fails honestly when the bridge is unavailable. It does
NOT prove the live integration — only a real run against a real browser does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("browser.read_page must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
body = "First line.\nSecond line."
status = 200
requests = []
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status):
raw = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
self.requests.append(("POST", self.path, self._read().decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path == "/goto":
self._send({"url": "https://example.com/", "title": "Example", "status": 200}, 200)
return
self._send({"error": "not found"}, 404)
def do_GET(self):
self.requests.append(("GET", self.path, ""))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/content"):
self._send(
{
"url": "https://example.com/",
"title": "Example",
"format": "text",
"content": self.body,
"truncated": False,
},
200,
)
return
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(status=200):
handler = type("Handler", (BridgeHandler,), {"status": status, "requests": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="read the current page"):
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": url, "browser_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reads_the_current_page_without_navigating():
server, handler, url = start_server()
try:
action = run(url)
assert "First line." in action.action_log, action.action_log
assert "Second line." in action.action_log, action.action_log
assert action.new_state == action.action_log
assert not any(path == "/goto" for _method, path, _ in handler.requests), "no URL means no navigation"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_navigates_when_the_request_names_a_url():
server, handler, url = start_server()
try:
action = run(url, "read https://example.com/")
assert "Example" in action.action_log, action.action_log
assert any(method == "POST" and path == "/goto" for method, path, _ in handler.requests)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "read the current page"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reads_the_current_page_without_navigating()
test_navigates_when_the_request_names_a_url()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,4 +0,0 @@
{
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Take a screenshot of a web page (a URL in the request, or the page the browser is already on) through the browser bridge and report the saved file."
}
@@ -1,90 +0,0 @@
"""Take a screenshot of a web page through the browser bridge.
Real integration: the local browser bridge (`browser_bridge_url`,
`browser_bridge_token`); the body never drives a browser directly. If the
request names a URL it opens that page first, otherwise it captures the page the
browser is already on, and reports the real path of the saved PNG. A bridge
failure is reported honestly — never a fabricated path.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "browser",
"transport": "http",
"config_vars": ["browser_bridge_url", "browser_bridge_token"],
}
CONTRACT = {
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 60
_URL_RE = re.compile(r"https?://[^\s<>\"')]+", re.IGNORECASE)
class BrowserBridgeError(Exception):
"""A real failure talking to the local browser bridge."""
def _request(ctx, path, payload=None, params=None):
base = str(ctx.config.get("browser_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BrowserBridgeError("browser_bridge_url is not configured")
token = str(ctx.config.get("browser_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
data = None
method = "GET"
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
method = "POST"
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BrowserBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BrowserBridgeError(f"{method} {path}: {exc}") from exc
def _resolve_url(request):
source = request.user_input if request.user_input is not None else request.text
match = _URL_RE.search(source or "")
return match.group(0) if match else None
def act(ctx, request):
url = _resolve_url(request)
try:
if url:
_request(ctx, "/goto", {"url": url})
shot = _request(ctx, "/screenshot", params={"full_page": "true"})
except BrowserBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
path = shot.get("path") or ""
title = shot.get("title") or ""
page_url = shot.get("url") or url or "the current page"
size = shot.get("bytes")
where = f"{title} ({page_url})" if title else str(page_url)
detail = f"Saved a screenshot of {where} to {path}"
if isinstance(size, int):
detail += f" ({size} bytes)"
return ActionResult(action_log=detail, new_state=detail)
@@ -1,125 +0,0 @@
"""Hermetic mechanics test for browser.screenshot.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local browser bridge's `/goto` and `/screenshot` routes.
This proves the body captures the page through the bridge and reports the saved
path (and fails honestly when the bridge is unavailable). It does NOT prove the
live integration — only a real run against a real browser does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("browser.screenshot must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
path_saved = "/home/user/.runtime/browser/screenshots/shot.png"
status = 200
requests = []
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status):
raw = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
self.requests.append(("POST", self.path, self._read().decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path == "/goto":
self._send({"url": "https://example.com/", "title": "Example", "status": 200}, 200)
return
self._send({"error": "not found"}, 404)
def do_GET(self):
self.requests.append(("GET", self.path, ""))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/screenshot"):
self._send(
{
"ok": True,
"path": self.path_saved,
"bytes": 12345,
"url": "https://example.com/",
"title": "Example",
},
200,
)
return
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(status=200):
handler = type("Handler", (BridgeHandler,), {"status": status, "requests": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="take a screenshot of https://example.com/"):
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": url, "browser_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_the_saved_screenshot():
server, handler, url = start_server()
try:
action = run(url)
assert BridgeHandler.path_saved in action.action_log, action.action_log
assert "12345 bytes" in action.action_log, action.action_log
assert action.new_state == action.action_log
assert any(method == "GET" and path.startswith("/screenshot") for method, path, _ in handler.requests)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "take a screenshot of https://example.com/"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reports_the_saved_screenshot()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-15
View File
@@ -1,15 +0,0 @@
{
"name": "essentials",
"title": "Essentials",
"concern": "The built-in local utilities the agent ships with that need no account, network, or bridge: time and date, timers and alarms, and arithmetic.",
"categories": {
"time": "Time and date utilities: telling the current time or date, setting countdown timers, and setting alarms.",
"calculator": "Arithmetic: evaluating a numeric expression the user asks for — addition, subtraction, multiplication, division, powers and exponents, squares, cubes, square roots, cube roots, fractions, and percentages."
},
"bridges": [],
"requires": [],
"enabled_by_default": true,
"config": {
"enabled": {"type": "bool", "default": true, "doc": "Load the built-in local utility skills (time, calculator)."}
}
}
@@ -1 +0,0 @@
{}
@@ -1,3 +0,0 @@
{
"description": "Evaluate a simple arithmetic request (two operands, one operator) and say the answer, e.g. \"what is 15% of 80?\", \"3/4\", or \"square root of 144\"."
}
@@ -1,460 +0,0 @@
"""Evaluate a simple arithmetic request and say the answer out loud.
Real local compute: the `compute` transport is the codebase's home for a body
that acts on the machine itself, and arithmetic is exactly that — no external
service, no configuration. The body is deliberately bounded to **two operands
and one operator**.
The decision engine (SemIf) resolves the *operator* from the request text with a
single choice over the supported operations: addition, subtraction,
multiplication, division, exponents, squares, cubes, square roots, cube roots,
fractions, and percentages. The operands are the numbers written in the request;
when the request offers more numbers than the operation consumes, SemIf chooses
which numbers are the operands (one choice per operand slot). When too few
numbers are present the body pauses and asks for them, stashing the answer in
`request.meta` so the single-phase `act` re-run does not ask twice.
The result is phrased for the ear: every number is spelled out in words and an
inexact result is announced as "approximately ...". Square, cube, square-root
and cube-root requests are unary in plain language but are still "one operator,
two operands" underneath (the base and an implied 2, 3, 1/2 or 1/3).
"""
from __future__ import annotations
import math
import re
from collections import namedtuple
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {"service": "local_calculator", "transport": "compute", "config_vars": []}
CONTRACT = {}
# operator id -> (option description for SemIf, number of operands it consumes)
OPERATIONS: dict[str, tuple[str, int]] = {
"add": (
"Add two numbers together, stated as 'plus', 'added to', 'the sum of', or '+'.",
2,
),
"subtract": (
"Subtract one number from another, stated as 'minus', 'less', 'take away', or '-'.",
2,
),
"multiply": (
"Multiply two numbers, stated as 'times', 'multiplied by', or 'the product of'.",
2,
),
"divide": (
"Divide one number by another, stated as 'divided by' or with a division sign.",
2,
),
"exponent": (
"Raise a base to a power, stated as 'to the power of' or with a caret '^'.",
2,
),
"square": ("Square a single number, stated as 'squared'.", 1),
"cube": ("Cube a single number, stated as 'cubed'.", 1),
"square_root": ("The square root of a single number, stated as 'square root of'.", 1),
"cube_root": ("The cube root of a single number, stated as 'cube root of'.", 1),
"fraction": (
"The value of a plain fraction written with a slash, such as 3/4, when the "
"request does not say 'divided by'.",
2,
),
"percent": (
"Take a percentage of a number, stated as 'X% of Y' or 'X percent of Y'.",
2,
),
}
_ASKS = {
"add": "What two numbers should I add? (e.g. '3 and 4')",
"subtract": "What two numbers should I subtract? (e.g. '9 minus 4')",
"multiply": "What two numbers should I multiply? (e.g. '6 and 7')",
"divide": "What should I divide, and by what? (e.g. '10 divided by 4')",
"exponent": "What base and what power? (e.g. '2 to the power of 10')",
"square": "What number should I square?",
"cube": "What number should I cube?",
"square_root": "What number should I take the square root of?",
"cube_root": "What number should I take the cube root of?",
"fraction": "What fraction should I evaluate? (e.g. '3/4')",
"percent": "What percentage of what number? (e.g. '20% of 50')",
}
# ---- spoken number words ----
_UNITS = {
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"eleven": 11,
"twelve": 12,
"thirteen": 13,
"fourteen": 14,
"fifteen": 15,
"sixteen": 16,
"seventeen": 17,
"eighteen": 18,
"nineteen": 19,
}
_TENS = {
"twenty": 20,
"thirty": 30,
"forty": 40,
"fifty": 50,
"sixty": 60,
"seventy": 70,
"eighty": 80,
"ninety": 90,
}
_SCALES = {
"hundred": 100,
"thousand": 1000,
"million": 1000000,
"billion": 1000000000,
"trillion": 1000000000000,
}
_UNITS_WORD = {value: word for word, value in _UNITS.items()}
_TENS_WORD = {value: word for word, value in _TENS.items()}
_SCALE_WORDS = [
(1000000000000, "trillion"),
(1000000000, "billion"),
(1000000, "million"),
(1000, "thousand"),
]
_NUMBER_WORDS = set(_UNITS) | set(_TENS) | set(_SCALES)
_WORD_TOKEN = re.compile(
r"\b(?:"
+ "|".join(
re.escape(word)
for word in sorted(_NUMBER_WORDS | {"and", "negative"}, key=len, reverse=True)
)
+ r")\b",
re.I,
)
_DIGIT = re.compile(r"(?P<sign>negative\s+)?(?P<num>\d+(?:\.\d+)?|\.\d+)", re.I)
def _int_to_words(number: int) -> str:
if number < 0:
return "negative " + _int_to_words(-number)
if number < 20:
return _UNITS_WORD[number]
if number < 100:
tens, ones = divmod(number, 10)
word = _TENS_WORD[tens * 10]
return f"{word}-{_UNITS_WORD[ones]}" if ones else word
if number < 1000:
hundreds, rest = divmod(number, 100)
word = f"{_UNITS_WORD[hundreds]} hundred"
return f"{word} {_int_to_words(rest)}" if rest else word
for scale, name in _SCALE_WORDS:
if number >= scale:
leading, rest = divmod(number, scale)
word = f"{_int_to_words(leading)} {name}"
return f"{word} {_int_to_words(rest)}" if rest else word
return str(number)
def _speak_number(value: float) -> str:
"""A number as English words, so a spoken reply is unambiguous."""
value = float(value)
if not math.isfinite(value):
return "an undefined value"
if value < 0:
return "negative " + _speak_number(-value)
if abs(value - round(value)) < 1e-9:
return _int_to_words(int(round(value)))
if value >= 1e15:
return f"{value:.6g}"
whole = int(value)
fraction_digits = f"{value:.10f}".split(".", 1)[1].rstrip("0")
words = _int_to_words(whole) if whole else "zero"
if fraction_digits:
return f"{words} point " + " ".join(_UNITS_WORD[int(d)] for d in fraction_digits)
return words
# ---- request parsing ----
_Candidate = namedtuple("_Candidate", "value phrase start end")
def _normalize_leading_sign(text: str) -> str:
"""Turn a leading '-5' into 'negative 5' so a sign at the start of the
request is not confused with a spaced-out subtraction."""
return re.sub(r"^\s*[-\u2212]\s*(?=\d)", "negative ", text, count=1)
def _parse_word_number(words: list[str]) -> float | None:
total = 0
current = 0
negative = False
seen = False
for word in words:
if word == "negative":
negative = True
elif word == "and":
continue
elif word in _UNITS:
current += _UNITS[word]
seen = True
elif word in _TENS:
current += _TENS[word]
seen = True
elif word in _SCALES:
scale = _SCALES[word]
if scale == 100:
current = (current or 1) * 100
else:
total += (current or 1) * scale
current = 0
seen = True
else:
return None
if not seen:
return None
value = total + current
return float(-value if negative else value)
def _digit_candidates(text: str) -> list[_Candidate]:
candidates = []
for match in _DIGIT.finditer(text):
value = float(match.group("num"))
if match.group("sign"):
value = -value
candidates.append(
_Candidate(value, match.group(0).strip(), match.start(), match.end())
)
return candidates
def _word_candidates(text: str) -> list[_Candidate]:
matches = list(_WORD_TOKEN.finditer(text))
groups: list[list] = []
current: list = []
for match in matches:
if current:
gap = text[current[-1].end() : match.start()]
if not re.fullmatch(r"[\s\-]*", gap):
groups.append(current)
current = []
current.append(match)
if current:
groups.append(current)
candidates = []
for group in groups:
value = _parse_word_number([match.group(0).lower() for match in group])
if value is None:
continue
start, end = group[0].start(), group[-1].end()
candidates.append(_Candidate(value, text[start:end], start, end))
return candidates
def _find_candidates(text: str) -> list[_Candidate]:
"""Every number written in the request, in the order it appears."""
text = _normalize_leading_sign(text or "")
candidates = _digit_candidates(text) + _word_candidates(text)
candidates.sort(key=lambda candidate: (candidate.start, candidate.end))
ordered: list[_Candidate] = []
last_end = -1
for candidate in candidates:
if candidate.start >= last_end:
ordered.append(candidate)
last_end = candidate.end
return ordered
# ---- SemIf decisions ----
def _decide_operator(ctx, text: str, decisions: list) -> str:
decision = DecisionRequest(
state=text,
question="Which arithmetic operation does the user's request ask for?",
options=[
Option(name, description) for name, (description, _count) in OPERATIONS.items()
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
return result.selected
def _select_operands(ctx, text, candidates, needed, decisions):
"""The operand values the operation consumes.
When the request writes exactly the numbers the operation needs they are
read in order; when it writes more, SemIf chooses which numbers are the
operands, one choice per operand slot.
"""
if len(candidates) == needed:
return [candidate.value for candidate in candidates]
pool = list(candidates)
chosen = []
for slot in range(needed):
if slot == 0:
question = (
"Which of these numbers is the first number to use in the calculation?"
)
else:
question = (
"Which of these numbers is the second number to use in the calculation?"
)
decision = DecisionRequest(
state=text,
question=question,
options=[
Option(
str(index),
f"{candidate.phrase} (equal to {_speak_number(candidate.value)})",
)
for index, candidate in enumerate(pool)
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
try:
selected = int(result.selected)
except (TypeError, ValueError):
selected = 0
if not 0 <= selected < len(pool):
selected = 0
chosen.append(pool.pop(selected).value)
return chosen
# ---- arithmetic ----
class _CalcError(Exception):
"""The request cannot be computed (bad operand, undefined result)."""
def _compute(operator: str, operands: list[float]) -> float:
first = operands[0]
second = operands[1] if len(operands) > 1 else None
if operator == "square":
return first * first
if operator == "cube":
return first * first * first
if operator == "square_root":
if first < 0:
raise _CalcError("I can't take the square root of a negative number.")
return math.sqrt(first)
if operator == "cube_root":
return math.copysign(abs(first) ** (1.0 / 3.0), first)
if operator in ("divide", "fraction"):
if second == 0:
raise _CalcError("I can't divide by zero.")
return first / second
if operator == "percent":
return (first / 100.0) * second
if operator == "exponent":
try:
result = first ** second
except (OverflowError, ValueError):
raise _CalcError("That power is too large or is not a real number.")
if isinstance(result, complex):
raise _CalcError("That power is not a real number.")
return result
if operator == "add":
return first + second
if operator == "subtract":
return first - second
if operator == "multiply":
return first * second
raise _CalcError("I don't know how to compute that.")
def _round_for_speech(value: float) -> tuple[float, bool]:
"""The value to speak and whether it had to be rounded."""
value = float(value)
if not math.isfinite(value):
return value, True
if abs(value - round(value)) < 1e-9:
return float(round(value)), False
rounded = round(value, 4)
return rounded, abs(rounded - value) > 1e-9
def _report(operator: str, operands: list[float], value: float, approximate: bool) -> str:
first = _speak_number(operands[0])
second = _speak_number(operands[1]) if len(operands) > 1 else None
result = _speak_number(value)
prefix = "approximately " if approximate else ""
sentences = {
"add": f"{first} plus {second} is {prefix}{result}.",
"subtract": f"{first} minus {second} is {prefix}{result}.",
"multiply": f"{first} times {second} is {prefix}{result}.",
"divide": f"{first} divided by {second} is {prefix}{result}.",
"exponent": f"{first} to the power of {second} is {prefix}{result}.",
"square": f"{first} squared is {prefix}{result}.",
"cube": f"{first} cubed is {prefix}{result}.",
"square_root": f"The square root of {first} is {prefix}{result}.",
"cube_root": f"The cube root of {first} is {prefix}{result}.",
"fraction": f"The fraction {first} over {second} is {prefix}{result}.",
"percent": f"{first} percent of {second} is {prefix}{result}.",
}
message = sentences.get(operator, f"The answer is {prefix}{result}.")
return message[0].upper() + message[1:]
# ---- the skill phase ----
def act(ctx, request):
answers = request.meta.setdefault("calculator_answers", {})
awaiting = request.meta.get("calculator_awaiting")
if request.user_input is not None and awaiting:
answers[awaiting] = request.user_input.strip()
request.meta.pop("calculator_awaiting", None)
text = request.text
decisions: list = []
operator = request.meta.get("calculator_operator")
if operator not in OPERATIONS:
operator = _decide_operator(ctx, text, decisions)
request.meta["calculator_operator"] = operator
needed = OPERATIONS[operator][1]
candidates = _find_candidates(text)
if answers.get("operands"):
candidates = candidates + _find_candidates(answers["operands"])
if len(candidates) < needed:
request.meta["calculator_awaiting"] = "operands"
return ActionResult(
action_log="waiting for the numbers to calculate",
new_state=request.text,
needs_input=_ASKS[operator],
decisions=decisions,
)
operands = _select_operands(ctx, text, candidates, needed, decisions)
try:
value = _compute(operator, operands)
except _CalcError as exc:
message = f"{exc}"
return ActionResult(action_log=message, new_state=message, decisions=decisions)
if not math.isfinite(value):
message = "That calculation does not have a finite answer."
return ActionResult(action_log=message, new_state=message, decisions=decisions)
rounded, approximate = _round_for_speech(value)
message = _report(operator, operands, rounded, approximate)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
@@ -1,116 +0,0 @@
"""Hermetic mechanics test for calculator.calculate.
Run from this folder: `python skill.test.py`. No external network and no
configuration — this body is pure local compute. A scripted `FakeEngine` stands
in for SemIf so the operator choice and the operand disambiguation are exercised
deterministically. This proves the body parses numbers (digits and words),
resolves one operator and up to two operands, spells the result out for the ear,
asks for missing numbers and resumes, and fails honestly on an undefined
calculation. It does NOT prove the live decision engine — only a real run does.
"""
import sys
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
"""Picks the queued option id per call (default: the first option)."""
def __init__(self, picks=None):
self.picks = list(picks or [])
self.calls = []
def call(self, decision):
self.calls.append(decision)
option_ids = [option.id for option in decision.options]
chosen = self.picks.pop(0) if self.picks else option_ids[0]
if chosen not in option_ids:
chosen = option_ids[0]
return DecisionResult(
request=decision,
option_ids=option_ids,
probabilities=[1.0 if i == chosen else 0.0 for i in option_ids],
)
def run(text, picks=None):
engine = FakeEngine(picks)
ctx = ActionContext(engine=engine, config={})
request = Request(text)
action = skill.act(ctx, request)
return action, engine, request
def check(text, picks, expected):
action, engine, _ = run(text, picks)
assert action.action_log == expected, (text, action.action_log, expected)
assert action.needs_input is None, (text, action.needs_input)
return action, engine
def main():
# The operator is a SemIf choice; the answer is spoken in words.
check("what is 3 plus 4?", ["add"], "Three plus four is seven.")
check("9 minus 4", ["subtract"], "Nine minus four is five.")
check("6 times 7", ["multiply"], "Six times seven is forty-two.")
check("10 divided by 4", ["divide"], "Ten divided by four is two point five.")
check("2 to the power of 10", ["exponent"],
"Two to the power of ten is one thousand twenty-four.")
# Squares, cubes, roots, fractions, percentages.
check("7 squared", ["square"], "Seven squared is forty-nine.")
check("3 cubed", ["cube"], "Three cubed is twenty-seven.")
check("square root of 144", ["square_root"],
"The square root of one hundred forty-four is twelve.")
check("cube root of 27", ["cube_root"],
"The cube root of twenty-seven is three.")
check("3/4", ["fraction"],
"The fraction three over four is zero point seven five.")
check("20% of 50", ["percent"], "Twenty percent of fifty is ten.")
# An inexact result is announced as approximate.
check("square root of 2", ["square_root"],
"The square root of two is approximately one point four one four two.")
# Number words are read as operands too.
check("five plus five", ["add"], "Five plus five is ten.")
check("twenty one times two", ["multiply"],
"Twenty-one times two is forty-two.")
# A sign at the start of the request is part of the number.
check("-5 plus 3", ["add"], "Negative five plus three is negative two.")
# More numbers than the operation consumes: SemIf picks the operands.
_action, engine = check("add 1 2 3", ["add", "0", "0"], "One plus two is three.")
assert len(engine.calls) == 3, "operator + two operand choices expected"
# Undefined calculations are reported honestly, not fabricated.
action, _ = check("5 divided by 0", ["divide"], "I can't divide by zero.")
assert action.needs_input is None
# Too few numbers: ask once, then finish on the resume.
engine = FakeEngine(["add"])
ctx = ActionContext(engine=engine, config={})
request = Request("what is 3 plus?")
first = skill.act(ctx, request)
assert first.needs_input, "a missing operand should be asked for"
assert first.action_log == "waiting for the numbers to calculate"
request.user_input = "4"
second = skill.act(ctx, request)
assert second.action_log == "Three plus four is seven.", second.action_log
assert second.needs_input is None
print(second.action_log)
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1 +0,0 @@
{}
@@ -1,3 +0,0 @@
{
"description": "Report today's date."
}
@@ -1,21 +0,0 @@
"""Report today's date.
Real local compute: reads the host clock and formats the calendar date in the
user's timezone — the top-level `timezone` config value (an IANA name) when set,
otherwise the host's local timezone. No external service.
"""
from __future__ import annotations
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
def act(ctx, request):
today = local_now(ctx.config).date()
message = f"Today is {today.strftime('%A, %B')} {today.day}, {today.year}."
return ActionResult(action_log=message, new_state=message)
@@ -1,29 +0,0 @@
"""Hermetic mechanics test for time.date.
Run from this folder: `python skill.test.py`. No external network, no config.
"""
import sys
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
def main():
ctx = ActionContext(engine=None, config={})
action = skill.act(ctx, Request("what is today's date?"))
assert action.new_state, "act must report the date"
assert "Today is" in action.action_log, action.action_log
assert action.needs_input is None
print(action.action_log)
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1 +0,0 @@
{}
@@ -1,3 +0,0 @@
{
"description": "Report the current local time of day."
}
-23
View File
@@ -1,23 +0,0 @@
"""Report the current local time.
Real local compute: reads the host clock and formats it in the user's
timezone — the top-level `timezone` config value (an IANA name such as
`America/Chicago`) when set, otherwise the host's local timezone. No external
service; the `compute` transport is the codebase's home for a body that acts on
the machine itself.
"""
from __future__ import annotations
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
def act(ctx, request):
now = local_now(ctx.config)
message = f"It is {now.strftime('%I:%M %p').lstrip('0')}."
return ActionResult(action_log=message, new_state=message)
@@ -1,31 +0,0 @@
"""Hermetic mechanics test for time.now.
Run from this folder: `python skill.test.py`. No external network, no config.
This proves the body reads the host clock and reports a real local time; it
does NOT prove anything about the host's timezone correctness.
"""
import sys
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
def main():
ctx = ActionContext(engine=None, config={})
action = skill.act(ctx, Request("what time is it?"))
assert action.new_state, "act must report the time"
assert "It is" in action.action_log, action.action_log
assert action.needs_input is None
print(action.action_log)
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1 +0,0 @@
{}
@@ -1,3 +0,0 @@
{
"description": "Set an alarm for a specific time of day that notifies when it goes off."
}
@@ -1,87 +0,0 @@
"""Set an alarm for a specific time of day that notifies when it goes off.
Real local compute: parses a wall-clock time out of the request and schedules it
on the in-process timer service (`ctx.timers`). The wall-clock time is read in
the user's timezone — the top-level `timezone` config value when set, otherwise
the host's local timezone. A time already past rolls to the next day. When it
fires, the front end that set it notifies the user.
If no time can be parsed the body pauses and asks for one, stashing the answer
in `request.meta` so the single-phase `act` re-run does not ask again.
"""
from __future__ import annotations
import re
from datetime import datetime, time, timedelta
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
def _parse_time(text, now):
"""The next datetime matching a wall-clock time in `text`, or None."""
text = text or ""
parsed = None
if re.search(r"\bnoon\b", text, re.I):
parsed = time(12, 0)
elif re.search(r"\bmidnight\b", text, re.I):
parsed = time(0, 0)
else:
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
if match:
hour = int(match.group(1)) % 12
minute = int(match.group(2) or 0)
if match.group(3).lower() == "p":
hour += 12
if hour < 24 and minute < 60:
parsed = time(hour, minute)
else:
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
if match:
hour, minute = int(match.group(1)), int(match.group(2))
if hour < 24 and minute < 60:
parsed = time(hour, minute)
else:
# A bare hour is only accepted when unambiguous (24-hour).
match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I)
if match and 13 <= int(match.group(1)) < 24:
parsed = time(int(match.group(1)), 0)
if parsed is None:
return None
candidate = datetime.combine(now.date(), parsed, tzinfo=now.tzinfo)
if candidate <= now:
candidate += timedelta(days=1)
return candidate
def act(ctx, request):
if request.user_input is not None and request.meta.get("alarm_awaiting"):
if request.user_input.strip():
request.meta["alarm_time_text"] = request.user_input.strip()
request.meta.pop("alarm_awaiting", None)
text = request.meta.get("alarm_time_text") or request.text
now = local_now(ctx.config)
when = _parse_time(text, now)
if when is None:
request.meta["alarm_awaiting"] = True
return ActionResult(
action_log="waiting for a time",
new_state=request.text,
needs_input="What time should the alarm go off? (e.g. '5pm')",
)
if ctx.timers is None:
return ActionResult(
action_log="no timer service is available in this front end",
new_state=request.text,
)
label = when.strftime("%H:%M")
ctx.timers.set_alarm(when, label, run_id=request.id, source=request.source)
message = f"Alarm set for {when.strftime('%H:%M')} on {when.strftime('%A')}."
return ActionResult(action_log=message, new_state=message)
@@ -1,84 +0,0 @@
"""Hermetic mechanics test for time.set_alarm.
Run from this folder: `python skill.test.py`. No external network, no real
sleeping: a fake timer service records what the body schedules. This proves the
body parses wall-clock times (am/pm, 24-hour, noon/midnight), rolls a past time
to the next day, and pauses for input when no time is present.
"""
import sys
from datetime import datetime, timedelta
from types import SimpleNamespace
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeTimers:
def __init__(self):
self.alarms = []
def set_alarm(self, at, label, run_id="", source=""):
self.alarms.append((at, label))
return SimpleNamespace(id="a1", due_at=at.timestamp())
def ctx_with_timers():
timers = FakeTimers()
return ActionContext(engine=None, config={}, timers=timers), timers
def main():
now = datetime.now().astimezone()
ctx, timers = ctx_with_timers()
action = skill.act(ctx, Request("set an alarm for 5pm"))
assert action.needs_input is None, action.needs_input
assert len(timers.alarms) == 1, timers.alarms
at, label = timers.alarms[0]
assert (at.hour, at.minute) == (17, 0), at
assert label == "17:00"
assert at > now, "an alarm must be in the future"
assert at <= now + timedelta(days=1)
print(action.action_log)
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("set an alarm for 17:30"))
assert timers.alarms[0][0].strftime("%H:%M") == "17:30", timers.alarms
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("wake me at noon"))
assert timers.alarms[0][0].strftime("%H:%M") == "12:00", timers.alarms
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("alarm at midnight"))
assert timers.alarms[0][0].strftime("%H:%M") == "00:00", timers.alarms
# An unparseable request pauses, then the answer is used on the re-run.
ctx, timers = ctx_with_timers()
request = Request("set an alarm")
action = skill.act(ctx, request)
assert action.needs_input, "an alarm with no time must ask for one"
assert timers.alarms == []
request.user_input = "6:15am"
action = skill.act(ctx, request)
assert action.needs_input is None
assert timers.alarms[0][0].strftime("%H:%M") == "06:15", timers.alarms
print(action.action_log)
# No timer service fails honestly.
ctx = ActionContext(engine=None, config={}, timers=None)
action = skill.act(ctx, Request("set an alarm for 5pm"))
assert "no timer service" in action.action_log, action.action_log
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1 +0,0 @@
{}
@@ -1,3 +0,0 @@
{
"description": "Set a countdown timer that notifies when it finishes."
}
@@ -1,128 +0,0 @@
"""Set a countdown timer that notifies the user when it finishes.
Real local compute: parses a duration out of the request (digits or words) and
schedules it on the in-process timer service (`ctx.timers`). When it fires, the
front end that set it notifies the user — the REPL prints it, the gateway sends
it back to the originating chat, the dashboard shows it. The due time is shown
in the user's timezone (the top-level `timezone` config value, else host local).
A timer lives in the process that set it and does not survive a restart.
If no duration can be parsed the body pauses and asks for one, stashing the
answer in `request.meta` so the single-phase `act` re-run does not ask again.
"""
from __future__ import annotations
import re
from semif_agent.skills import ActionResult
from semif_agent.timers import format_duration
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
_DURATION_WORDS = {
"a": 1,
"an": 1,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"eleven": 11,
"twelve": 12,
"fifteen": 15,
"twenty": 20,
"thirty": 30,
"forty": 40,
"fortyfive": 45,
"sixty": 60,
"ninety": 90,
}
_UNIT_SECONDS = {
"second": 1,
"seconds": 1,
"sec": 1,
"secs": 1,
"s": 1,
"minute": 60,
"minutes": 60,
"min": 60,
"mins": 60,
"m": 60,
"hour": 3600,
"hours": 3600,
"hr": 3600,
"hrs": 3600,
"h": 3600,
}
_DIGIT_DURATION = re.compile(
r"\b(\d+(?:\.\d+)?)\s*(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b",
re.I,
)
_WORD_DURATION = re.compile(
r"\b(" + "|".join(sorted(_DURATION_WORDS, key=len, reverse=True)) + r")\s+"
r"(seconds?|secs?|minutes?|mins?|hours?|hrs?)\b",
re.I,
)
def _parse_duration(text):
"""Seconds for a duration phrase, or None when none is present."""
text = text or ""
if re.search(r"\bhalf\s+an?\s+hour\b", text, re.I):
return 1800
if re.search(r"\bquarter\s+(?:of\s+)?an?\s+hour\b", text, re.I):
return 900
if re.search(r"\ba\s+couple\s+of\s+(?:minutes?|mins?)\b", text, re.I):
return 120
if re.search(r"\ba\s+few\s+(?:minutes?|mins?)\b", text, re.I):
return 180
match = _DIGIT_DURATION.search(text)
if match:
unit = _UNIT_SECONDS.get(match.group(2).lower())
if unit:
return int(round(float(match.group(1)) * unit))
match = _WORD_DURATION.search(text)
if match:
value = _DURATION_WORDS.get(match.group(1).lower())
unit = _UNIT_SECONDS.get(match.group(2).lower())
if value and unit:
return value * unit
return None
def act(ctx, request):
if request.user_input is not None and request.meta.get("timer_awaiting"):
if request.user_input.strip():
request.meta["timer_duration_text"] = request.user_input.strip()
request.meta.pop("timer_awaiting", None)
text = request.meta.get("timer_duration_text") or request.text
seconds = _parse_duration(text)
if seconds is None:
request.meta["timer_awaiting"] = True
return ActionResult(
action_log="waiting for a duration",
new_state=request.text,
needs_input="How long should the timer run? (e.g. '5 minutes')",
)
if ctx.timers is None:
return ActionResult(
action_log="no timer service is available in this front end",
new_state=request.text,
)
label = format_duration(seconds)
timer = ctx.timers.set_timer(seconds, label, run_id=request.id, source=request.source)
due = timer.due_datetime().strftime("%H:%M")
message = f"Timer set for {label}; it will fire at {due}."
return ActionResult(action_log=message, new_state=message)
@@ -1,90 +0,0 @@
"""Hermetic mechanics test for time.set_timer.
Run from this folder: `python skill.test.py`. No external network, no real
sleeping: a fake timer service records what the body schedules. This proves the
body parses durations (digits and words) and schedules the right number of
seconds, and that an unparseable request pauses for input; it does NOT prove
the in-process timer actually fires (tests/test_timers.py covers the service).
"""
import sys
import time
from datetime import datetime
from types import SimpleNamespace
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeTimer:
def __init__(self, seconds):
self.due_at = time.time() + seconds
def due_datetime(self):
return datetime.fromtimestamp(self.due_at).astimezone()
class FakeTimers:
def __init__(self):
self.timers = []
def set_timer(self, seconds, label, run_id="", source=""):
self.timers.append((seconds, label))
return FakeTimer(seconds)
def ctx_with_timers():
timers = FakeTimers()
return ActionContext(engine=None, config={}, timers=timers), timers
def main():
ctx, timers = ctx_with_timers()
action = skill.act(ctx, Request("please set a timer for five minutes"))
assert action.needs_input is None, action.needs_input
assert timers.timers == [(300, "5 minutes")], timers.timers
assert "300" not in action.action_log and "5 minutes" in action.action_log
print(action.action_log)
ctx, timers = ctx_with_timers()
action = skill.act(ctx, Request("set a timer for 90 seconds"))
assert timers.timers == [(90, "1 minute 30 seconds")], timers.timers
print(action.action_log)
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("timer for 1.5 hours"))
assert timers.timers == [(5400, "1 hour 30 minutes")], timers.timers
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("set a timer for half an hour"))
assert timers.timers == [(1800, "30 minutes")], timers.timers
# An unparseable request pauses, then the answer is used on the re-run.
ctx, timers = ctx_with_timers()
request = Request("set a timer")
action = skill.act(ctx, request)
assert action.needs_input, "a timer with no duration must ask for one"
assert timers.timers == []
request.user_input = "ten minutes"
action = skill.act(ctx, request)
assert action.needs_input is None
assert timers.timers == [(600, "10 minutes")], timers.timers
print(action.action_log)
# No timer service (e.g. a front end without one) fails honestly.
ctx = ActionContext(engine=None, config={}, timers=None)
action = skill.act(ctx, Request("set a timer for 5 minutes"))
assert action.needs_input is None
assert "no timer service" in action.action_log, action.action_log
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-25
View File
@@ -1,25 +0,0 @@
{
"name": "nextcloud",
"title": "Nextcloud",
"concern": "The user's Nextcloud account: calendar events and scheduling, to-do tasks, files, contacts, and notes.",
"categories": {
"nextcloud": "Nextcloud productivity: the user's calendar events and scheduling (reading or changing events and reminders) and the user's to-do tasks and task lists."
},
"bridges": ["nextcloud"],
"requires": [],
"enabled_by_default": true,
"config": {
"enabled": {"type": "bool", "default": true, "doc": "Load this pack's skills and run its bridge."},
"host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."},
"port": {"type": "int", "default": 5230, "doc": "Bridge listen port."},
"token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."},
"url": {"type": "str", "default": "", "doc": "Nextcloud base URL, e.g. https://cloud.example.com."},
"username": {"type": "str", "default": "", "doc": "Nextcloud username."},
"app_password": {"type": "str", "default": "", "secret": true, "doc": "Nextcloud app password (Settings > Security > Devices & sessions), not the account password."},
"default_calendar": {"type": "str", "default": "", "doc": "Calendar used when a request names none and the account has several."},
"default_task_calendar": {"type": "str", "default": "", "doc": "VTODO-capable task list used when a request names none."},
"default_addressbook": {"type": "str", "default": "", "doc": "Addressbook used when a request names none."},
"verify_tls": {"type": "bool", "default": true, "doc": "false skips certificate verification (self-signed hosts)."},
"timeout": {"type": "int", "default": 30, "doc": "Per-request timeout in seconds."}
}
}
@@ -1,8 +0,0 @@
{
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are used.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event 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."
}
@@ -1,3 +0,0 @@
{
"description": "Create a calendar event from a request such as \"add Ashley's dance recital for 5pm Tuesday\"."
}
@@ -1,628 +0,0 @@
"""Create a calendar event on the user's Nextcloud calendar from a request.
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details and the default calendar come from `ctx.config` (`nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
`act` reads `request.text` and derives the event's per-request arguments. The
title and description are extracted by the local LLM bridge (`llm_bridge_url`,
`llm_bridge_token`) with one generic chat call, cached in `request.meta` so a
`needs_input` resume does not re-call it; the start date/time and duration are
parsed deterministically. Missing arguments are asked one at a time and the
answer is stashed in `request.meta`; because `act` is single-phase and re-runs
from the top after a `needs_input` pause, the body never re-asks a question it
already has an answer for. Calendars are discovered over PROPFIND and the target
is resolved by a single SemIf choice over every owned calendar (state = the user
query), asking which one the request refers to; a strong winner (probability >=
`CALENDAR_WINNER_TAU`) is used, otherwise the configured default calendar is
used. The event is created with a real CalDAV PUT (iCalendar, UTC timestamps,
`If-None-Match: *`) and the real outcome is reported.
The date/time parse is deliberately bounded; the title/description come from the
model. When the model bridge is unavailable the body reports the real failure
rather than guessing.
"""
from __future__ import annotations
import base64
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import uuid
import xml.etree.ElementTree as ET
from datetime import datetime, time, timedelta, timezone
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {
"service": "nextcloud_calendar",
"transport": "caldav",
"config_vars": [
"nextcloud_url",
"nextcloud_username",
"nextcloud_app_password",
"nextcloud_default_calendar",
"llm_bridge_url",
"llm_bridge_token",
],
}
CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are used.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event 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.",
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
TIMEOUT_SECONDS = 30
DEFAULT_DURATION_MINUTES = 60
# A SemIf probability at or above this counts as a "strong winner" for the
# target calendar; below it the configured default calendar is used instead.
CALENDAR_WINNER_TAU = 0.6
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
"</d:propfind>"
).encode("utf-8")
_WEEKDAYS = {
"monday": 0,
"mon": 0,
"tuesday": 1,
"tue": 1,
"tues": 1,
"wednesday": 2,
"wed": 2,
"thursday": 3,
"thu": 3,
"thur": 3,
"thurs": 3,
"friday": 4,
"fri": 4,
"saturday": 5,
"sat": 5,
"sunday": 6,
"sun": 6,
}
_WEEKDAY_RE = re.compile(
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
)
_MONTHS = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
_MONTH_ALT = (
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
)
class CalDavError(Exception):
"""A real failure talking to the calendar service."""
class BridgeError(Exception):
"""A real failure talking to the local LLM bridge."""
def _now(ctx):
"""Current time (aware) in the user's timezone: the top-level `timezone`
config value when set, else host local. A test seam; never freezes time."""
return local_now(ctx.config)
# ---- transport ----
def _request(ctx, method, path, body=None, depth="0", content_type="application/xml; charset=utf-8", extra_headers=None):
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
password = str(ctx.config.get("nextcloud_app_password", "") or "")
if not url:
raise CalDavError("nextcloud_url is not configured")
if not username or not password:
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
headers = {"Authorization": f"Basic {token}", "Depth": depth}
if body is not None:
headers["Content-Type"] = content_type
if extra_headers:
headers.update(extra_headers)
request = urllib.request.Request(
url + path, data=body, method=method, headers=headers
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return response.status, response.read()
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, OSError) as exc:
raise CalDavError(f"{method} {path}: {exc}") from exc
# ---- CalDAV discovery ----
def _multistatus(body):
try:
root = ET.fromstring(body)
except ET.ParseError as exc:
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
if root.tag != f"{{{DAV}}}multistatus":
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
return root
def _response_prop(response):
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
def _discover_calendars(ctx):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
if not username:
raise CalDavError("nextcloud_username is not configured")
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
_status, body = _request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1")
calendars = []
for response in _multistatus(body).findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
continue
href = response.find(f"{{{DAV}}}href")
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
if not name:
continue
display = prop.find(f"{{{DAV}}}displayname")
label = (display.text or "").strip() if display is not None else ""
calendars.append({"name": name, "label": label or name})
return calendars
def _calendar_path(ctx, calendar):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
return (
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
f"{urllib.parse.quote(calendar)}/"
)
# ---- LLM field extraction ----
def _extract_fields(ctx, request):
"""Ask the LLM bridge for the event title and description.
One generic `POST /chat` call to the local LLM bridge; the reply is the JSON
object the prompt asks for. Raises `BridgeError` when the bridge is
unreachable or the reply carries no usable object.
"""
base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BridgeError("llm_bridge_url is not configured")
token = str(ctx.config.get("llm_bridge_token", "") or "").strip()
messages = [
{
"role": "system",
"content": (
"Extract the calendar event from the user's request. Reply with "
'ONLY a JSON object: {"title": "<short event title>", '
'"description": "<one short sentence, or empty>"}. The title must '
"not contain the date, the time, or words like add/schedule/create."
),
},
{"role": "user", "content": request.text},
]
payload = json.dumps({"messages": messages}).encode("utf-8")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(
base + "/chat", data=payload, method="POST", headers=headers
)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
data = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"llm bridge /chat: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"llm bridge /chat: {exc}") from exc
return _parse_fields(str(data.get("text") or ""))
def _parse_fields(text):
"""Pull the `{"title","description"}` object out of the model's reply."""
start, end = text.find("{"), text.rfind("}")
if start == -1 or end < start:
raise BridgeError("llm bridge returned no JSON object")
try:
data = json.loads(text[start : end + 1])
except ValueError as exc:
raise BridgeError(f"llm bridge returned invalid JSON: {exc}") from exc
if not isinstance(data, dict):
raise BridgeError("llm bridge returned JSON that is not an object")
return {
"title": str(data.get("title") or "").strip(),
"description": str(data.get("description") or "").strip(),
}
def _month_number(token):
return _MONTHS.get(token.lower()[:3])
def _resolve_month_day(month, day, year, now):
if not (month and 1 <= day <= 31):
return None
given_year = year is not None
year = year or now.year
try:
candidate = datetime(year, month, day).date()
except ValueError:
return None
if not given_year and candidate < now.date():
try:
candidate = datetime(year + 1, month, day).date()
except ValueError:
return None
return candidate
def _parse_when(text, now):
"""Best-effort extraction of date/time/duration from free text.
Returns a dict with `date` (datetime.date | None), `time` (datetime.time |
None), `all_day` (bool), `duration_minutes` (int | None) and `from_weekday`
(bool). The title and description come from the LLM bridge, so no matched
spans are tracked here.
"""
text = text or ""
result = {
"date": None,
"time": None,
"all_day": False,
"duration_minutes": None,
"from_weekday": False,
}
match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I)
if match:
result["all_day"] = True
match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I)
if match:
result["duration_minutes"] = int(round(float(match.group(1)) * 60))
else:
match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I)
if match:
result["duration_minutes"] = int(match.group(1))
else:
for phrase, minutes in (
(r"\bfor\s+half\s+an?\s+hour\b", 30),
(r"\bfor\s+an?\s+hour\b", 60),
(r"\bfor\s+a\s+couple\s+of\s+hours\b", 120),
):
match = re.search(phrase, text, re.I)
if match:
result["duration_minutes"] = minutes
break
date = None
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
if match:
try:
date = datetime(
int(match.group(1)), int(match.group(2)), int(match.group(3))
).date()
except ValueError:
date = None
if date is None:
match = re.search(
r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b",
text,
re.I,
)
if match:
month = _month_number(match.group(1))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(2)), year, now)
if date is None:
match = re.search(
r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?(" + _MONTH_ALT + r")(?:,?\s*(\d{4}))?\b",
text,
re.I,
)
if match:
month = _month_number(match.group(2))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(1)), year, now)
if date is None:
match = re.search(r"\b(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?\b", text)
if match:
first, second = int(match.group(1)), int(match.group(2))
month, day = (first, second) if first <= 12 else (second, first)
year = int(match.group(3)) if match.group(3) else None
if year is not None and year < 100:
year += 2000
date = _resolve_month_day(month, day, year, now)
if date is None:
match = re.search(
r"\b(today|tonight|tomorrow|tmrw|tomorow|next\s+week)\b", text, re.I
)
if match:
word = re.sub(r"\s+", " ", match.group(1).lower())
if word in ("today", "tonight"):
date = now.date()
elif word in ("tomorrow", "tmrw", "tomorow"):
date = now.date() + timedelta(days=1)
else:
date = now.date() + timedelta(days=7)
if date is None:
match = _WEEKDAY_RE.search(text)
if match:
target = _WEEKDAYS[match.group(1).lower()]
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
prefix = text[max(0, match.start() - 6):match.start()]
if re.search(r"\bnext\s*$", prefix, re.I):
date += timedelta(days=7)
result["from_weekday"] = True
parsed_time = None
match = re.search(r"\bnoon\b", text, re.I)
if match:
parsed_time = time(12, 0)
elif re.search(r"\bmidnight\b", text, re.I):
parsed_time = time(0, 0)
else:
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
if match:
hour = int(match.group(1)) % 12
minute = int(match.group(2) or 0)
if match.group(3).lower() == "p":
hour += 12
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
else:
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
if match:
hour, minute = int(match.group(1)), int(match.group(2))
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
else:
match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I)
if match and 13 <= int(match.group(1)) < 24:
parsed_time = time(int(match.group(1)), 0)
result["date"] = date
result["time"] = parsed_time
return result
# ---- calendar resolution ----
def _resolve_calendar(ctx, request, calendars, decisions):
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
default = None
for calendar in calendars:
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
default = calendar
break
if len(calendars) == 1:
return calendars[0]["name"]
decision = DecisionRequest(
state=request.text,
question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CALENDAR_WINNER_TAU:
return winner
if default is not None:
return default["name"]
return winner
# ---- iCalendar ----
def _escape_ics(value):
return (
str(value)
.replace("\\", "\\\\")
.replace(";", "\\;")
.replace(",", "\\,")
.replace("\r\n", "\\n")
.replace("\n", "\\n")
.replace("\r", "\\n")
)
def _utc_stamp(moment):
return moment.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def _build_ics(uid, summary, start, end, all_day, stamp, description=""):
lines = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//semif-agent//nextcloud.create_event//EN",
"CALSCALE:GREGORIAN",
"BEGIN:VEVENT",
f"UID:{uid}",
f"DTSTAMP:{stamp}",
]
if all_day:
lines.append(f"DTSTART;VALUE=DATE:{start.strftime('%Y%m%d')}")
lines.append(f"DTEND;VALUE=DATE:{end.strftime('%Y%m%d')}")
else:
lines.append(f"DTSTART:{_utc_stamp(start)}")
lines.append(f"DTEND:{_utc_stamp(end)}")
lines.append(f"SUMMARY:{_escape_ics(summary)}")
if description:
lines.append(f"DESCRIPTION:{_escape_ics(description)}")
lines += ["END:VEVENT", "END:VCALENDAR", ""]
return "\r\n".join(lines).encode("utf-8")
# ---- skill phases ----
def _ask(request, field, question):
request.meta["create_event_awaiting"] = field
return ActionResult(
action_log=f"waiting for {field}",
new_state=request.text,
needs_input=question,
)
def act(ctx, request):
answers = request.meta.setdefault("create_event_answers", {})
awaiting = request.meta.get("create_event_awaiting")
if request.user_input is not None and awaiting:
if answers.get(awaiting) != request.user_input.strip():
answers[awaiting] = request.user_input.strip()
request.meta.pop("create_event_awaiting", None)
fields = request.meta.get("create_event_fields")
if fields is None:
try:
fields = _extract_fields(ctx, request)
except BridgeError as exc:
return ActionResult(
action_log=str(exc),
new_state=request.text,
)
request.meta["create_event_fields"] = fields
title = fields["title"]
description = fields["description"]
now = _now(ctx)
parsed = _parse_when(request.text, now)
if answers.get("title"):
title = answers["title"].strip()
for key in ("date", "time"):
if answers.get(key):
extra = _parse_when(answers[key], now)
if extra["date"] is not None:
parsed["date"] = extra["date"]
parsed["from_weekday"] = extra["from_weekday"]
if extra["time"] is not None:
parsed["time"] = extra["time"]
if extra["all_day"]:
parsed["all_day"] = True
if extra["duration_minutes"]:
parsed["duration_minutes"] = extra["duration_minutes"]
if not title:
return _ask(request, "title", "What should I call the event?")
if parsed["date"] is None:
return _ask(request, "date", f"What day should I schedule {title!r}?")
if not parsed["all_day"] and parsed["time"] is None:
return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')")
local_tz = now.tzinfo or timezone.utc
all_day = bool(parsed["all_day"])
if all_day:
start_date = parsed["date"]
end_date = start_date + timedelta(days=1)
start = datetime.combine(start_date, time(0, 0), tzinfo=local_tz)
end = datetime.combine(end_date, time(0, 0), tzinfo=local_tz)
else:
start = datetime.combine(parsed["date"], parsed["time"], tzinfo=local_tz)
if start <= now and parsed.get("from_weekday"):
start += timedelta(days=7)
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
end = start + duration
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="no calendars found on the account",
new_state=request.text,
)
decisions = []
calendar = _resolve_calendar(ctx, request, calendars, decisions)
uid = f"{uuid.uuid4().hex}@semif-agent"
body = _build_ics(
uid, title, start, end, all_day, _utc_stamp(now), description=description
)
path = _calendar_path(ctx, calendar) + urllib.parse.quote(uid, safe="") + ".ics"
try:
_request(
ctx,
"PUT",
path,
body=body,
depth="0",
content_type="text/calendar; charset=utf-8",
extra_headers={"If-None-Match": "*"},
)
except CalDavError as exc:
return ActionResult(
action_log=(
f"could not create {title!r} on "
f"{calendar!r}: {exc}"
),
new_state=request.text,
decisions=decisions,
)
if all_day:
when_text = f"{start_date.isoformat()} (all day)"
else:
when_text = (
f"{start.strftime('%Y-%m-%d %H:%M %Z')}–"
f"{end.strftime('%H:%M %Z')}"
)
report = f"Created {title!r} on calendar {calendar!r}: {when_text} (UID {uid})."
return ActionResult(
action_log=report,
new_state=report,
decisions=decisions,
)
@@ -1,451 +0,0 @@
"""Hermetic mechanics test for nextcloud.create_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays a Nextcloud CalDAV endpoint (PROPFIND discovery + PUT create)
and the LLM bridge's `POST /chat`. This proves the body extracts the event title
and description through the LLM bridge (caching the call across a `needs_input`
resume), parses the date/time from the request, asks for a missing field and
resumes, resolves the target calendar with a SemIf choice over the owned
calendars (a strong winner is used, otherwise the configured default), writes a
real iCalendar PUT, and fails honestly when the LLM bridge or the server errors.
It does NOT prove the live integration — only a real run against the user's
Nextcloud does.
"""
import json
import sys
import threading
import urllib.parse
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
skill._now = lambda ctx: FIXED_NOW
DEFAULT_LLM_REPLY = {"title": "event", "description": ""}
def next_weekday(now, weekday):
return now.date() + timedelta(days=(weekday - now.date().weekday()) % 7)
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class CalDavHandler(BaseHTTPRequestHandler):
calendars = []
put_status = 201
requests = []
puts = []
llm_reply = DEFAULT_LLM_REPLY
llm_status = 200
llm_requests = []
def _read_body(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status, content_type):
body = payload if isinstance(payload, bytes) else payload.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_PROPFIND(self):
self._read_body()
self.requests.append(("PROPFIND", self.path))
responses = []
for calendar in self.calendars:
responses.append(
f'<d:response><d:href>/remote.php/dav/calendars/alice/'
f'{calendar["name"]}/</d:href>'
f"<d:propstat><d:prop>"
f'<d:displayname>{calendar["label"]}</d:displayname>'
f"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
f"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
f"</d:response>"
)
body = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
+ "".join(responses)
+ "</d:multistatus>"
)
self._send(body, 207, "application/xml; charset=utf-8")
def do_PUT(self):
body = self._read_body()
self.puts.append(
{"path": self.path, "body": body, "headers": dict(self.headers)}
)
self._send(b"", self.put_status, "text/plain")
def do_POST(self):
body = self._read_body()
if self.path != "/chat":
self._send(json.dumps({"error": "not found"}), 404, "application/json")
return
self.llm_requests.append(body)
if self.llm_status != 200:
self._send(json.dumps({"error": "boom"}), self.llm_status, "application/json")
return
self._send(
json.dumps({"text": json.dumps(self.llm_reply)}),
200,
"application/json",
)
def log_message(self, *args):
pass
def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200):
handler = type(
"Handler",
(CalDavHandler,),
{
"calendars": calendars
if calendars is not None
else [
{"name": "personal", "label": "Personal"},
{"name": "work", "label": "Work"},
],
"put_status": put_status,
"requests": [],
"puts": [],
"llm_reply": llm_reply if llm_reply is not None else DEFAULT_LLM_REPLY,
"llm_status": llm_status,
"llm_requests": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url, default="personal", llm_url=None):
return {
"nextcloud_url": url,
"nextcloud_username": "alice",
"nextcloud_app_password": "secret",
"nextcloud_default_calendar": default,
"llm_bridge_url": url if llm_url is None else llm_url,
"llm_bridge_token": "",
}
def run(handler, url, text, default="personal", engine=None, llm_url=None):
engine = engine or FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, default, llm_url))
request = Request(text)
action = skill.act(ctx, request)
return action, request, engine
def test_example_creates_event_on_default_calendar():
server, handler, url = start_server(
llm_reply={
"title": "Ashley's dance recital",
"description": "Dance recital at 5pm.",
}
)
try:
# The query names no calendar, so the SemIf choice is a near-tie and the
# configured default ("personal") wins.
engine = FakeEngine(probs={"personal": 0.4, "work": 0.35})
action, _request, engine = run(
handler,
url,
"add Ashley's dance recital to the calendar for 5pm Tuesday",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, "the calendar is chosen with one SemIf decision"
assert engine.decisions[0].state == (
"add Ashley's dance recital to the calendar for 5pm Tuesday"
), engine.decisions[0]
assert "referred to in the user query" in engine.decisions[0].question
assert len(handler.puts) == 1, handler.puts
put = handler.puts[0]
assert put["path"].startswith("/remote.php/dav/calendars/alice/personal/"), put
assert put["path"].endswith(".ics"), put
assert put["headers"].get("If-None-Match") == "*"
body = put["body"].decode("utf-8")
assert "SUMMARY:Ashley's dance recital" in body, body
assert "DESCRIPTION:Dance recital at 5pm." in body, body
tuesday = next_weekday(FIXED_NOW, 1)
assert f"DTSTART:{tuesday.strftime('%Y%m%d')}T170000Z" in body, body
assert f"DTEND:{tuesday.strftime('%Y%m%d')}T180000Z" in body, body
assert "Ashley's dance recital" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_time_asks_then_creates():
server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try:
action, request, engine = run(
handler, url, "add dentist appointment on 2026-11-10"
)
assert action.needs_input, "a missing start time must be asked"
assert "time" in action.needs_input.lower(), action.needs_input
assert handler.puts == []
assert len(handler.llm_requests) == 1, "the LLM is called once, then cached"
request.user_input = "2pm"
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert len(handler.puts) == 1, handler.puts
assert len(handler.llm_requests) == 1, "the resume must reuse the cached fields"
body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:dentist appointment" in body, body
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_day_asks_then_creates():
server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try:
action, request, engine = run(handler, url, "add dentist appointment at 2pm")
assert action.needs_input, "a missing day must be asked"
assert "day" in action.needs_input.lower(), action.needs_input
request.user_input = "2026-11-10"
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8")
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_title_asks():
server, handler, url = start_server(llm_reply={"title": "", "description": ""})
try:
action, _request, _engine = run(handler, url, "schedule on 2026-11-10 at 2pm")
assert action.needs_input, "a missing title must be asked"
assert "call the event" in action.needs_input.lower(), action.needs_input
assert handler.puts == []
print(action.needs_input)
finally:
server.shutdown()
server.server_close()
def test_named_calendar_is_used():
server, handler, url = start_server(
llm_reply={"title": "team sync", "description": ""}
)
try:
engine = FakeEngine(pick="work")
action, _request, engine = run(
handler,
url,
"add team sync to my work calendar on 2026-11-10 at 9am",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert [option.id for option in engine.decisions[0].options] == [
"personal",
"work",
], engine.decisions[0].options
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/work/"
), handler.puts[0]
body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:team sync" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_falls_back_to_default():
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
try:
# Work edges out personal but stays below the strong-winner threshold, so
# the configured default ("personal") is used instead.
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
action, _request, engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/personal/"
), handler.puts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unknown_default_uses_semif_decision():
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
try:
# The configured default is not among the account's calendars and the
# SemIf winner is weak: the winner is used anyway (never blocks).
engine = FakeEngine(probs={"personal": 0.3, "work": 0.4})
action, _request, engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
default="missing",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert action.decisions and len(action.decisions) == 1, action.decisions
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/work/"
), handler.puts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_all_day_event():
server, handler, url = start_server(llm_reply={"title": "conference", "description": ""})
try:
action, _request, _engine = run(
handler, url, "add conference all day on 2026-11-10"
)
assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8")
assert "DTSTART;VALUE=DATE:20261110" in body, body
assert "DTEND;VALUE=DATE:20261111" in body, body
assert "SUMMARY:conference" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_failure_is_reported_honestly():
server, handler, url = start_server()
try:
action, request, _engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
llm_url="http://127.0.0.1:1",
)
assert "llm bridge" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed extraction must not fake a result"
assert handler.puts == [], "no event is created when the LLM bridge is down"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_error_status_is_reported_honestly():
server, handler, url = start_server(llm_status=502)
try:
action, request, _engine = run(
handler, url, "add standup on 2026-11-10 at 9am"
)
assert "HTTP 502" in action.action_log, action.action_log
assert action.new_state == request.text
assert handler.puts == []
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_server_error_is_reported_honestly():
server, handler, url = start_server(
put_status=500, llm_reply={"title": "standup", "description": ""}
)
try:
action, request, _engine = run(
handler, url, "add standup on 2026-11-10 at 9am"
)
assert "500" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed create must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_server_fails_honestly():
action, request, _engine = run(
None, "http://127.0.0.1:1", "add standup on 2026-11-10 at 9am"
)
assert action.action_log and "nextcloud.create_event" not in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
def main():
test_example_creates_event_on_default_calendar()
test_missing_time_asks_then_creates()
test_missing_day_asks_then_creates()
test_missing_title_asks()
test_named_calendar_is_used()
test_weak_winner_falls_back_to_default()
test_unknown_default_uses_semif_decision()
test_all_day_event()
test_llm_bridge_failure_is_reported_honestly()
test_llm_bridge_error_status_is_reported_honestly()
test_server_error_is_reported_honestly()
test_unreachable_server_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,6 +0,0 @@
{
"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."
}
@@ -1,3 +0,0 @@
{
"description": "Add a single task to a Nextcloud task list from a request such as \"add a task to eat more hot dogs\"."
}
@@ -1,204 +0,0 @@
"""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": "<short task title>", '
'"description": "<extra detail, or an empty string>"}.'
),
},
{"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)
@@ -1,345 +0,0 @@
"""Hermetic mechanics test for nextcloud.create_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()
@@ -1,6 +0,0 @@
{
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar)."
}
@@ -1,3 +0,0 @@
{
"description": "Report the next upcoming event on the user's Nextcloud calendar."
}
@@ -1,416 +0,0 @@
"""Report the next upcoming event on the user's Nextcloud calendar.
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details and the default calendar come from `ctx.config` (`nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
`act` discovers the user's calendars over PROPFIND and resolves which one the
request means with a single SemIf choice over every owned calendar (state = the
user query): a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used,
otherwise the configured default calendar is used; with no configured default
the weak winner stands. It then issues a `calendar-query` REPORT with
server-side recurrence expansion and reports the earliest instance that has not
ended yet.
Recurring events are expanded by the server (`<c:expand>`), so no RRULE engine
lives here; a server that ignores expansion is reported honestly rather than
guessed at.
"""
from __future__ import annotations
import base64
import re
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {
"service": "nextcloud_calendar",
"transport": "caldav",
"config_vars": [
"nextcloud_url",
"nextcloud_username",
"nextcloud_app_password",
"nextcloud_default_calendar",
],
}
CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar).",
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
LOOKAHEAD_DAYS = 60
TIMEOUT_SECONDS = 30
# A SemIf probability at or above this counts as a "strong winner" for the
# target calendar; below it the configured default calendar is used instead.
CALENDAR_WINNER_TAU = 0.6
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
"</d:propfind>"
).encode("utf-8")
PROPERTY_RE = re.compile(r"^(?P<name>[A-Za-z-]+)(?P<params>(?:;[^:]*)?):(?P<value>.*)$")
DURATION_RE = re.compile(
r"^(?P<sign>[+-])?P"
r"(?:(?P<weeks>\d+)W)?(?:(?P<days>\d+)D)?"
r"(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$"
)
class CalDavError(Exception):
"""A real failure talking to the calendar service."""
def _now(ctx):
"""Current time (aware) in the user's timezone: the top-level `timezone`
config value when set, else host local. A test seam; never freezes time."""
return local_now(ctx.config)
# ---- transport ----
def _request(ctx, method, path, body=None, depth="0"):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
password = str(ctx.config.get("nextcloud_app_password", "") or "")
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
if not url:
raise CalDavError("nextcloud_url is not configured")
if not username or not password:
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
request = urllib.request.Request(
url + path,
data=body,
method=method,
headers={
"Authorization": f"Basic {token}",
"Depth": depth,
"Content-Type": "application/xml; charset=utf-8",
},
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return response.read()
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, OSError) as exc:
raise CalDavError(f"{method} {path}: {exc}") from exc
# ---- CalDAV discovery + query ----
def _multistatus(body):
try:
root = ET.fromstring(body)
except ET.ParseError as exc:
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
if root.tag != f"{{{DAV}}}multistatus":
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
return root
def _response_prop(response):
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
def _discover_calendars(ctx):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
if not username:
raise CalDavError("nextcloud_username is not configured")
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
root = _multistatus(_request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1"))
calendars = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
continue
href = response.find(f"{{{DAV}}}href")
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
if not name:
continue
display = prop.find(f"{{{DAV}}}displayname")
label = (display.text or "").strip() if display is not None else ""
calendars.append({"name": name, "label": label or name})
return calendars
def _calendar_path(ctx, calendar):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
return (
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
f"{urllib.parse.quote(calendar)}/"
)
def _report_body(start, end):
start_text = start.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
end_text = end.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
return (
'<?xml version="1.0" encoding="utf-8"?>'
'<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop>"
f'<c:calendar-data><c:expand start="{start_text}" end="{end_text}"/>'
"</c:calendar-data>"
"</d:prop>"
"<c:filter>"
'<c:comp-filter name="VCALENDAR">'
'<c:comp-filter name="VEVENT">'
f'<c:time-range start="{start_text}" end="{end_text}"/>'
"</c:comp-filter>"
"</c:comp-filter>"
"</c:filter>"
"</c:calendar-query>"
).encode("utf-8")
def _calendar_payloads(body):
root = _multistatus(body)
payloads = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
for data in prop.findall(f"{{{CALDAV}}}calendar-data"):
if data.text:
payloads.append(data.text)
return payloads
# ---- calendar resolution ----
def _default_calendar(ctx, calendars):
"""The configured default calendar, if it is one of the account's."""
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
for calendar in calendars:
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
return calendar
return None
def _resolve_calendar(ctx, request, calendars, decisions):
"""Resolve which calendar the request means, mirroring nextcloud.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default calendar, and with no configured default the weak winner stands.
"""
default = _default_calendar(ctx, calendars)
if len(calendars) == 1:
return calendars[0]["name"]
decision = DecisionRequest(
state=request.text,
question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CALENDAR_WINNER_TAU:
return winner
if default is not None:
return default["name"]
return winner
# ---- iCalendar parsing ----
def _unfold(text):
lines = []
for raw in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
if raw[:1] in (" ", "\t") and lines:
lines[-1] += raw[1:]
else:
lines.append(raw)
return lines
def _parse_property(line):
match = PROPERTY_RE.match(line)
if match is None:
return "", {}, ""
name = match.group("name").upper()
params = {}
for chunk in match.group("params").strip(";").split(";"):
key, _, value = chunk.partition("=")
if key:
params[key.strip().upper()] = value.strip().strip('"')
return name, params, match.group("value")
def _parse_datetime(value, params, default_tz):
value = value.strip()
if params.get("VALUE") == "DATE" or (len(value) == 8 and value.isdigit()):
return datetime.strptime(value, "%Y%m%d").replace(tzinfo=default_tz), True
tz = default_tz
if value.endswith("Z"):
tz = timezone.utc
value = value[:-1]
elif params.get("TZID"):
try:
tz = ZoneInfo(params["TZID"])
except Exception:
tz = default_tz
return datetime.strptime(value, "%Y%m%dT%H%M%S").replace(tzinfo=tz), False
def _parse_duration(value):
match = DURATION_RE.match(value.strip().upper())
if match is None:
return None
total = timedelta(
weeks=int(match.group("weeks") or 0),
days=int(match.group("days") or 0),
hours=int(match.group("hours") or 0),
minutes=int(match.group("minutes") or 0),
seconds=int(match.group("seconds") or 0),
)
return -total if match.group("sign") == "-" else total
def _parse_events(payloads, default_tz):
events = []
for payload in payloads:
current = None
for line in _unfold(payload):
name, params, value = _parse_property(line)
if name == "BEGIN" and value.strip().upper() == "VEVENT":
current = {}
continue
if name == "END" and value.strip().upper() == "VEVENT":
if current is not None:
events.append(current)
current = None
continue
if current is None:
continue
if name == "DTSTART":
current["start"], current["all_day"] = _parse_datetime(
value, params, default_tz
)
elif name == "DTEND":
current["end"] = _parse_datetime(value, params, default_tz)[0]
elif name == "DURATION":
current["duration"] = _parse_duration(value)
elif name == "SUMMARY":
current["summary"] = value.strip()
elif name == "LOCATION":
current["location"] = value.strip()
elif name == "STATUS" and value.strip().upper() == "CANCELLED":
current["cancelled"] = True
if current is not None:
events.append(current)
return [
event for event in events if "start" in event and not event.get("cancelled")
]
def _event_end(event):
if event.get("end") is not None:
return event["end"]
duration = event.get("duration")
if duration is not None:
return event["start"] + duration
if event.get("all_day"):
return event["start"] + timedelta(days=1)
return event["start"]
def _pick_next(events, now):
current_or_future = [event for event in events if _event_end(event) >= now]
if not current_or_future:
return None
return min(current_or_future, key=lambda event: event["start"])
def _format_when(event):
start = event["start"]
if event.get("all_day"):
return start.strftime("%Y-%m-%d (all day)")
return start.strftime("%Y-%m-%d %H:%M %Z")
# ---- skill phases ----
def act(ctx, request):
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="calendar discovery failed: no calendars found",
new_state=request.text,
)
decisions = []
calendar = _resolve_calendar(ctx, request, calendars, decisions)
if not calendar:
return ActionResult(
action_log="aborted: no calendar resolved.",
new_state=request.text,
decisions=decisions,
)
now = _now(ctx)
local_tz = now.tzinfo or timezone.utc
window_start = now - timedelta(days=1)
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
try:
body = _request(
ctx,
"REPORT",
_calendar_path(ctx, calendar),
_report_body(window_start, window_end),
depth="1",
)
events = _parse_events(_calendar_payloads(body), local_tz)
except CalDavError as exc:
return ActionResult(
action_log=f"failed on {calendar!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
next_event = _pick_next(events, now)
if next_event is None:
message = (
f"No events on calendar {calendar!r} through "
f"{window_end.strftime('%Y-%m-%d')}."
)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
summary = next_event.get("summary") or "(no title)"
when = _format_when(next_event)
message = f"Next event on {calendar!r}: {summary} — {when}"
if next_event.get("location"):
message += f" at {next_event['location']}"
return ActionResult(action_log=message, new_state=message, decisions=decisions)
@@ -1,259 +0,0 @@
"""Hermetic mechanics test for nextcloud.next_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
real CalDAV requests, discovers calendars, resolves the calendar through a
SemIf sub-decision (a strong winner is used, otherwise the configured default,
otherwise the weak winner), parses expanded iCalendar events, and fails honestly
when the service errors. It does NOT prove the live integration — only a real
run against the user's Nextcloud does.
"""
import base64
import sys
import threading
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
CALENDARS = [("personal", "Personal"), ("work", "Work")]
ICS = ""
def build_ics():
"""Fixture events relative to now, so the test never rots."""
now = datetime.now(timezone.utc)
past = now - timedelta(days=2)
soon = now + timedelta(hours=2)
all_day = (now + timedelta(days=2)).date()
def stamp(value):
return value.strftime("%Y%m%dT%H%M%SZ")
return (
"BEGIN:VCALENDAR\nVERSION:2.0\n"
"BEGIN:VEVENT\nUID:past@example\n"
f"DTSTART:{stamp(past)}\nDTEND:{stamp(past + timedelta(hours=1))}\n"
"SUMMARY:Already happened\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:soon@example\n"
f"DTSTART:{stamp(soon)}\nDTEND:{stamp(soon + timedelta(hours=1))}\n"
"SUMMARY:Team sync\nLOCATION:Room 3\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:allday@example\n"
f"DTSTART;VALUE=DATE:{all_day.strftime('%Y%m%d')}\n"
"SUMMARY:Offsite\nEND:VEVENT\n"
"END:VCALENDAR"
)
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class CalDavHandler(BaseHTTPRequestHandler):
requests = []
calendar_count = 2
report_status = 207
def _record(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
self.requests.append(
{
"command": self.command,
"path": self.path,
"depth": self.headers.get("Depth"),
"authorization": self.headers.get("Authorization"),
"body": body.decode("utf-8", "replace"),
}
)
def _multistatus(self, payload):
body = payload.encode("utf-8")
self.send_response(207)
self.send_header("Content-Type", "application/xml; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_PROPFIND(self):
self._record()
responses = "".join(
f"<d:response><d:href>/remote.php/dav/calendars/testuser/{name}/</d:href>"
"<d:propstat><d:prop>"
f"<d:displayname>{label}</d:displayname>"
"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
for name, label in CALENDARS[: self.calendar_count]
)
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
f"{responses}</d:multistatus>"
)
def do_REPORT(self):
self._record()
if self.report_status != 207:
self.send_response(self.report_status)
self.end_headers()
return
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:response>"
"<d:href>/remote.php/dav/calendars/testuser/work/event.ics</d:href>"
"<d:propstat><d:prop>"
f"<c:calendar-data>{ICS}</c:calendar-data>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
"</d:response></d:multistatus>"
)
def log_message(self, *args):
pass
def start_server(**overrides):
handler = type("Handler", (CalDavHandler,), {"requests": [], **overrides})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def fixture_config(url, default="personal"):
return {
"nextcloud_url": url,
"nextcloud_username": "testuser",
"nextcloud_app_password": "app-pw",
"nextcloud_default_calendar": default,
}
def main():
global ICS
ICS = build_ics()
# A strong winner is used even though a default is configured.
server, handler, url = start_server()
try:
engine = FakeEngine(pick="work")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my work calendar?")
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the calendar choice"
assert len(engine.decisions) == 1
assert [option.id for option in engine.decisions[0].options] == [
"personal",
"work",
], engine.decisions[0].options
assert "Team sync" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
commands = [entry["command"] for entry in handler.requests]
assert commands == ["PROPFIND", "REPORT"], commands
report = handler.requests[1]
assert report["path"] == "/remote.php/dav/calendars/testuser/work/", report["path"]
assert report["depth"] == "1", report["depth"]
expected_auth = "Basic " + base64.b64encode(b"testuser:app-pw").decode("ascii")
assert report["authorization"] == expected_auth, report["authorization"]
assert "<c:expand" in report["body"], "recurrence expansion must be requested"
assert "c:time-range" in report["body"], "the query must bound a time range"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A weak winner falls back to the configured default calendar.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default="personal"))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/", handler.requests[1]["path"]
assert "Team sync" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A weak winner with no configured default stands.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default=""))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/work/", handler.requests[1]["path"]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A single calendar needs no SemIf decision.
server, handler, url = start_server(calendar_count=1)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert engine.decisions == [], "a single calendar needs no SemIf decision"
assert "Team sync" in action.action_log, action.action_log
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A failing REPORT is reported honestly.
server, handler, url = start_server(report_status=500)
try:
engine = FakeEngine(pick="personal")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert "failed" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed query must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-26
View File
@@ -1,26 +0,0 @@
{
"name": "outlook",
"title": "Outlook",
"concern": "The user's Microsoft account (Outlook / Microsoft 365) through Microsoft Graph: mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files.",
"categories": {
"outlook": "Outlook / Microsoft 365: the user's mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files."
},
"bridges": ["outlook"],
"requires": [],
"enabled_by_default": false,
"config": {
"enabled": {"type": "bool", "default": false, "doc": "Load this pack's skills and run its bridge. Disabled by default: it needs an Entra ID client id and an authorization run first."},
"host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."},
"port": {"type": "int", "default": 5231, "doc": "Bridge listen port."},
"token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."},
"client_id": {"type": "str", "default": "", "doc": "Entra ID public-client app id (not a secret)."},
"tenant": {"type": "str", "default": "common", "doc": "Entra tenant: common | organizations | consumers | a tenant id."},
"token_path": {"type": "str", "default": ".runtime/outlook/token.json", "doc": "Where scripts/outlook-auth.py stores the tokens (0600)."},
"default_calendar": {"type": "str", "default": "", "doc": "Calendar used when a request names none."},
"default_task_list": {"type": "str", "default": "", "doc": "Microsoft To Do list used when a request names none."},
"default_mail_folder": {"type": "str", "default": "inbox", "doc": "Mail folder read by default."},
"default_timezone": {"type": "str", "default": "UTC", "doc": "IANA zone for created events/tasks whose start has no offset."},
"verify_tls": {"type": "bool", "default": true, "doc": "false skips certificate verification."},
"timeout": {"type": "int", "default": 30, "doc": "Per-request timeout in seconds."}
}
}
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Create an Outlook calendar event from a request such as \"add dentist appointment on 2026-11-10 at 2pm\"."
}
@@ -1,334 +0,0 @@
"""Create an event on the user's Outlook calendar from a request.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. `act` derives the event's title, date, time and
duration from `request.text`; missing pieces are asked one at a time and the
answers are stashed in `request.meta` (act re-runs from the top after a
`needs_input` pause, so a question is never asked twice). The event is created
with a real `POST /calendars/events` and the real outcome reported. The user's
IANA timezone (the top-level `timezone` config value, when set) labels the start.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, time, timedelta
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
DEFAULT_DURATION_MINUTES = 60
_WEEKDAYS = {
"monday": 0,
"mon": 0,
"tuesday": 1,
"tue": 1,
"tues": 1,
"wednesday": 2,
"wed": 2,
"thursday": 3,
"thu": 3,
"thur": 3,
"thurs": 3,
"friday": 4,
"fri": 4,
"saturday": 5,
"sat": 5,
"sunday": 6,
"sun": 6,
}
_WEEKDAY_RE = re.compile(
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
)
_MONTHS = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
_MONTH_ALT = (
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
)
_COMMAND_WORDS = re.compile(
r"\b(add|create|new|put|make|set\s*up|set|schedule|book|"
r"i\s+need\s+to|i\s+have\s+to|calendar|"
r"for|on|at|from|my|the|a|an|to)\b",
re.I,
)
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _now(ctx):
return local_now(ctx.config)
def _post(ctx, path, payload):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
data = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json", "Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(base + path, data=data, method="POST", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"POST {path}: {exc}") from exc
def _month_number(token):
return _MONTHS.get(token.lower()[:3])
def _resolve_month_day(month, day, year, now):
if not (month and 1 <= day <= 31):
return None
given_year = year is not None
year = year or now.year
try:
candidate = datetime(year, month, day).date()
except ValueError:
return None
if not given_year and candidate < now.date():
try:
candidate = datetime(year + 1, month, day).date()
except ValueError:
return None
return candidate
def _parse_when(text, now):
"""`{"date","date_span","time","time_span","all_day","duration_minutes","from_weekday"}`."""
text = text or ""
result = {
"date": None,
"date_span": None,
"time": None,
"time_span": None,
"all_day": False,
"duration_minutes": None,
"from_weekday": False,
}
match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I)
if match:
result["all_day"] = True
match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I)
if match:
result["duration_minutes"] = int(round(float(match.group(1)) * 60))
else:
match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I)
if match:
result["duration_minutes"] = int(match.group(1))
else:
for phrase, minutes in (
(r"\bfor\s+half\s+an?\s+hour\b", 30),
(r"\bfor\s+an?\s+hour\b", 60),
):
match = re.search(phrase, text, re.I)
if match:
result["duration_minutes"] = minutes
break
date = None
span = None
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
if match:
try:
date = datetime(int(match.group(1)), int(match.group(2)), int(match.group(3))).date()
span = match.span()
except ValueError:
date = None
if date is None:
match = re.search(
r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b", text, re.I
)
if match:
month = _month_number(match.group(1))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(2)), year, now)
span = match.span() if date else None
if date is None:
match = re.search(
r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?(" + _MONTH_ALT + r")(?:,?\s*(\d{4}))?\b",
text,
re.I,
)
if match:
month = _month_number(match.group(2))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(1)), year, now)
span = match.span() if date else None
if date is None:
match = re.search(r"\b(today|tonight|tomorrow|tmrw|tomorow|next\s+week)\b", text, re.I)
if match:
word = re.sub(r"\s+", " ", match.group(1).lower())
if word in ("today", "tonight"):
date = now.date()
elif word in ("tomorrow", "tmrw", "tomorow"):
date = now.date() + timedelta(days=1)
else:
date = now.date() + timedelta(days=7)
span = match.span()
if date is None:
match = _WEEKDAY_RE.search(text)
if match:
target = _WEEKDAYS[match.group(1).lower()]
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
prefix = text[max(0, match.start() - 6) : match.start()]
if re.search(r"\bnext\s*$", prefix, re.I):
date += timedelta(days=7)
result["from_weekday"] = True
span = match.span()
parsed_time = None
time_span = None
match = re.search(r"\bnoon\b", text, re.I)
if match:
parsed_time = time(12, 0)
time_span = match.span()
elif re.search(r"\bmidnight\b", text, re.I):
parsed_time = time(0, 0)
time_span = re.search(r"\bmidnight\b", text, re.I).span()
else:
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
if match:
hour = int(match.group(1)) % 12
minute = int(match.group(2) or 0)
if match.group(3).lower() == "p":
hour += 12
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
time_span = match.span()
else:
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
if match:
hour, minute = int(match.group(1)), int(match.group(2))
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
time_span = match.span()
result["date"] = date
result["date_span"] = span
result["time"] = parsed_time
result["time_span"] = time_span
return result
def _title(text, parsed):
remove = [parsed.get("date_span"), parsed.get("time_span")]
out = text
for span in sorted((s for s in remove if s), key=lambda s: s[0], reverse=True):
out = out[: span[0]] + " " + out[span[1] :]
phrase = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", out, re.I)
if phrase:
out = out[: phrase.start()] + " " + out[phrase.end() :]
cleaned = re.sub(r"\s+", " ", _COMMAND_WORDS.sub(" ", out)).strip(" .,:;-")
return cleaned
def _ask(request, field, question):
request.meta["create_event_awaiting"] = field
return ActionResult(action_log=f"waiting for {field}", new_state=request.text, needs_input=question)
def act(ctx, request):
answers = request.meta.setdefault("create_event_answers", {})
awaiting = request.meta.get("create_event_awaiting")
if request.user_input is not None and awaiting:
answers[awaiting] = request.user_input.strip()
request.meta.pop("create_event_awaiting", None)
now = _now(ctx)
parsed = _parse_when(request.text, now)
title = _title(request.text, parsed)
if answers.get("title"):
title = answers["title"].strip()
for key in ("date", "time"):
if answers.get(key):
extra = _parse_when(answers[key], now)
if extra["date"] is not None:
parsed["date"] = extra["date"]
if extra["time"] is not None:
parsed["time"] = extra["time"]
if extra["all_day"]:
parsed["all_day"] = True
if extra["duration_minutes"]:
parsed["duration_minutes"] = extra["duration_minutes"]
if not title:
return _ask(request, "title", "What should I call the event?")
if parsed["date"] is None:
return _ask(request, "date", f"What day should I schedule {title!r}?")
if not parsed["all_day"] and parsed["time"] is None:
return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')")
all_day = bool(parsed["all_day"])
if all_day:
start = datetime.combine(parsed["date"], time(0, 0))
else:
start = datetime.combine(parsed["date"], parsed["time"])
if start <= now.replace(tzinfo=None) and parsed.get("from_weekday"):
start += timedelta(days=7)
timezone_name = str(ctx.config.get("timezone", "") or "").strip()
payload = {
"subject": title,
"start": start.strftime("%Y-%m-%dT%H:%M:%S"),
"all_day": all_day,
}
if not all_day:
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
payload["end"] = (start + duration).strftime("%Y-%m-%dT%H:%M:%S")
if timezone_name:
payload["timezone"] = timezone_name
try:
data = _post(ctx, "/calendars/events", payload)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
if all_day:
when_text = f"{start.date().isoformat()} (all day)"
else:
when_text = start.strftime("%Y-%m-%d %H:%M")
report = f"Created {title!r} on {when_text}."
return ActionResult(action_log=report, new_state=report)
@@ -1,162 +0,0 @@
"""Hermetic mechanics test for outlook.create_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/calendars/events` route and records
the payload. This proves the body derives the title/date/time, asks for a missing
piece and resumes, creates the event with a real POST, and fails honestly when
the bridge errors. It does NOT prove the live integration — only a real run
against the user's Microsoft account does.
"""
import json
import sys
import threading
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
skill._now = lambda ctx: FIXED_NOW
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.create_event must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
status = 200
posts = []
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
if self.path != "/calendars/events":
self._send({"error": "not found"}, 404)
return
self.posts.append(json.loads(body.decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
self._send({"ok": True, "id": "e1", "subject": self.posts[-1].get("subject")}, 201)
def _send(self, payload, status):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def start_server(status=200):
handler = type("Handler", (BridgeHandler,), {"status": status, "posts": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def context(url, tz=""):
config = {"outlook_bridge_url": url, "outlook_bridge_token": ""}
if tz:
config["timezone"] = tz
return ActionContext(engine=FakeEngine(), config=config)
def test_explicit_datetime():
server, handler, url = start_server()
try:
action = skill.act(context(url), Request("add dentist appointment on 2026-11-10 at 2pm"))
assert action.needs_input is None, action.needs_input
post = handler.posts[0]
assert post["subject"] == "dentist appointment", post
assert post["start"] == "2026-11-10T14:00:00", post
assert post["end"] == "2026-11-10T15:00:00", post
assert post["all_day"] is False, post
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_timezone_is_sent():
server, handler, url = start_server()
try:
skill.act(
context(url, tz="America/Chicago"),
Request("add lunch on 2026-11-10 at noon"),
)
assert handler.posts[0]["timezone"] == "America/Chicago", handler.posts[0]
print(handler.posts[0])
finally:
server.shutdown()
server.server_close()
def test_all_day_event():
server, handler, url = start_server()
try:
skill.act(context(url), Request("add conference all day on 2026-11-10"))
post = handler.posts[0]
assert post["all_day"] is True, post
assert "end" not in post, post
assert post["subject"] == "conference", post
print(post)
finally:
server.shutdown()
server.server_close()
def test_missing_time_asks_then_creates():
server, handler, url = start_server()
try:
ctx = context(url)
request = Request("add dentist appointment on 2026-11-10")
action = skill.act(ctx, request)
assert action.needs_input, "a missing start time must be asked"
assert handler.posts == []
request.user_input = "2pm"
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert handler.posts[0]["start"] == "2026-11-10T14:00:00", handler.posts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
request = Request("add dentist appointment on 2026-11-10 at 2pm")
action = skill.act(context(url), request)
assert "502" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed create must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_explicit_datetime()
test_timezone_is_sent()
test_all_day_event()
test_missing_time_asks_then_creates()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Add a task to the user's Microsoft To Do list, e.g. \"remind me to call the dentist tomorrow\"."
}
@@ -1,193 +0,0 @@
"""Add a task to the user's Microsoft To Do list.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. `act` derives the task title and an optional due
date from `request.text`; a missing title is asked one at a time and the answer
is stashed in `request.meta` (act re-runs from the top after a `needs_input`
pause, so a question is never asked twice). The task is created with a real
`POST /tasks` and the real outcome reported.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
_WEEKDAYS = {
"monday": 0,
"mon": 0,
"tuesday": 1,
"tue": 1,
"tues": 1,
"wednesday": 2,
"wed": 2,
"thursday": 3,
"thu": 3,
"thur": 3,
"thurs": 3,
"friday": 4,
"fri": 4,
"saturday": 5,
"sat": 5,
"sunday": 6,
"sun": 6,
}
_WEEKDAY_RE = re.compile(
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
)
_MONTHS = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
_MONTH_ALT = (
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
)
_COMMAND_WORDS = re.compile(
r"\b(add|create|new|put|make|set\s*up|set|schedule|remind\s+me(?:\s+to)?|"
r"i\s+need\s+to|i\s+have\s+to|tasks|task|to-?dos|to-?do|todo|lists|list|for|by|due|on|"
r"my|the|a|an|to)\b",
re.I,
)
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _now(ctx):
return local_now(ctx.config)
def _post(ctx, path, payload):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
data = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json", "Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(base + path, data=data, method="POST", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"POST {path}: {exc}") from exc
def _match_due(text, now):
"""Return `(due_date | None, matched_span | None)` for the due date."""
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
if match:
try:
return datetime(int(match.group(1)), int(match.group(2)), int(match.group(3))).date(), match.span()
except ValueError:
return None, None
match = re.search(r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b", text, re.I)
if match:
month = _MONTHS.get(match.group(1).lower()[:3])
year = int(match.group(3)) if match.group(3) else now.year
try:
candidate = datetime(year, month, int(match.group(2))).date()
except (TypeError, ValueError):
return None, None
if not match.group(3) and candidate < now.date():
candidate = candidate.replace(year=year + 1)
return candidate, match.span()
match = re.search(r"\b(today|tonight|tomorrow|tmrw|next\s+week)\b", text, re.I)
if match:
word = re.sub(r"\s+", " ", match.group(1).lower())
if word in ("today", "tonight"):
return now.date(), match.span()
if word in ("tomorrow", "tmrw"):
return now.date() + timedelta(days=1), match.span()
return now.date() + timedelta(days=7), match.span()
match = _WEEKDAY_RE.search(text)
if match:
target = _WEEKDAYS[match.group(1).lower()]
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
return date, match.span()
return None, None
def _title(text, span):
stripped = text
if span is not None:
stripped = text[: span[0]] + " " + text[span[1] :]
cleaned = re.sub(r"\s+", " ", _COMMAND_WORDS.sub(" ", stripped)).strip(" .,:;-")
return cleaned
def _ask(request, field, question):
request.meta["create_task_awaiting"] = field
return ActionResult(action_log=f"waiting for {field}", new_state=request.text, needs_input=question)
def act(ctx, request):
answers = request.meta.setdefault("create_task_answers", {})
awaiting = request.meta.get("create_task_awaiting")
if request.user_input is not None and awaiting:
answers[awaiting] = request.user_input.strip()
request.meta.pop("create_task_awaiting", None)
now = _now(ctx)
due, span = _match_due(request.text, now)
title = _title(request.text, span)
if answers.get("title"):
title = answers["title"].strip()
if answers.get("due"):
extra_due, _ = _match_due(answers["due"], now)
if extra_due is not None:
due = extra_due
if not title:
return _ask(request, "title", "What's the task?")
payload = {"title": title}
if due is not None:
payload["due"] = f"{due.isoformat()}T00:00:00"
try:
data = _post(ctx, "/tasks", payload)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
when = f" due {due.isoformat()}" if due is not None else ""
report = f"Added task {title!r}{when}."
return ActionResult(action_log=report, new_state=report)
@@ -1,144 +0,0 @@
"""Hermetic mechanics test for outlook.create_task.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/tasks` route and records the
payload. This proves the body derives a title + due date, asks for a missing
title and resumes, creates the task with a real POST, and fails honestly when the
bridge errors. It does NOT prove the live integration — only a real run against
the user's Microsoft account does.
"""
import json
import sys
import threading
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
skill._now = lambda ctx: FIXED_NOW
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.create_task must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
status = 200
posts = []
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
if self.path != "/tasks":
self._send({"error": "not found"}, 404)
return
self.posts.append(json.loads(body.decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
self._send({"ok": True, "id": "t1", "title": self.posts[-1].get("title")}, 201)
def _send(self, payload, status):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def start_server(status=200):
handler = type("Handler", (BridgeHandler,), {"status": status, "posts": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url):
return {"outlook_bridge_url": url, "outlook_bridge_token": ""}
def test_plain_task():
server, handler, url = start_server()
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
action = skill.act(ctx, Request("add buy milk to my tasks"))
assert action.needs_input is None, action.needs_input
assert handler.posts[0]["title"] == "buy milk", handler.posts[0]
assert "due" not in handler.posts[0], handler.posts[0]
assert "buy milk" in action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_task_with_due_date():
server, handler, url = start_server()
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
action = skill.act(ctx, Request("remind me to call the dentist tomorrow"))
assert action.needs_input is None, action.needs_input
assert handler.posts[0]["title"] == "call dentist", handler.posts[0]
assert handler.posts[0]["due"] == "2026-10-08T00:00:00", handler.posts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_title_asks_then_creates():
server, handler, url = start_server()
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
request = Request("add a task")
action = skill.act(ctx, request)
assert action.needs_input, "a missing title must be asked"
assert handler.posts == []
request.user_input = "water the plants"
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert handler.posts[0]["title"] == "water the plants", handler.posts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
request = Request("add buy milk to my tasks")
action = skill.act(ctx, request)
assert "502" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed create must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_plain_task()
test_task_with_due_date()
test_missing_title_asks_then_creates()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Look up a person in the user's Outlook contacts by name, email, or company."
}
@@ -1,86 +0,0 @@
"""Look up a person in the user's Outlook contacts.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. It searches the contacts for the words in the
request and reports the matches, or the real failure honestly.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
_STOPWORDS = re.compile(
r"\b(find|search|look\s*up|show|get|whats|what's|contact|contacts|email|e-?mail|"
r"address|phone|number|details|for|my|me|the|of|a|an)\b",
re.I,
)
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _get(ctx, path, params=None):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, method="GET", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
def _query(text):
return re.sub(r"\s+", " ", _STOPWORDS.sub(" ", text or "")).strip()
def act(ctx, request):
try:
data = _get(ctx, "/contacts", {"query": _query(request.text)})
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
contacts = data.get("contacts") or []
if not contacts:
return ActionResult(action_log="No matching contacts.", new_state="No matching contacts.")
lines = []
for contact in contacts[:5]:
name = contact.get("display_name") or "(no name)"
emails = ", ".join(contact.get("emails") or [])
phones = ", ".join(contact.get("phones") or [])
bits = " | ".join(part for part in (emails, phones) if part)
lines.append(f"- {name}: {bits}" if bits else f"- {name}")
report = "Contacts:\n" + "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
@@ -1,132 +0,0 @@
"""Hermetic mechanics test for outlook.list_contacts.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/contacts` route and records the
query it received. This proves the body searches the contacts and reports the
matches (and fails honestly when the bridge is unavailable). It does NOT prove
the live integration — only a real run against the user's Microsoft account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.list_contacts must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
contacts = []
status = 200
queries = []
def do_GET(self):
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
parsed = urlparse(self.path)
if parsed.path == "/contacts":
self.queries.append(parse_qs(parsed.query).get("query", [""])[0])
self._send({"contacts": self.contacts}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def start_server(contacts=None, status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"contacts": contacts
if contacts is not None
else [
{
"id": "c1",
"display_name": "Bob Smith",
"emails": ["bob@example.com"],
"phones": ["555-1234"],
}
],
"status": status,
"queries": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="find Bob's email"):
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_matching_contacts():
server, handler, url = start_server()
try:
action = run(url)
assert "Bob Smith" in action.action_log, action.action_log
assert "bob@example.com" in action.action_log, action.action_log
assert handler.queries and "Bob" in handler.queries[0], handler.queries
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_no_matches_is_reported():
server, _handler, url = start_server(contacts=[])
try:
action = run(url)
assert "no matching contacts" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "find Bob's email"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reports_matching_contacts()
test_no_matches_is_reported()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "List the user's OneDrive files, optionally in a named folder."
}
@@ -1,92 +0,0 @@
"""List the user's OneDrive files.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. It lists a OneDrive folder (root by default) and
reports the entries, or the real failure honestly.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
_STOPWORDS = re.compile(
r"\b(list|show|what'?s|whats|in|my|the|onedrive|files|file|folder|drive|of|me)\b",
re.I,
)
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _get(ctx, path, params=None):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, method="GET", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
def _folder(text):
cleaned = re.sub(r"\s+", " ", _STOPWORDS.sub(" ", text or "")).strip()
return cleaned or "/"
def act(ctx, request):
path = _folder(request.text)
try:
data = _get(ctx, "/files", {"path": path})
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
entries = data.get("entries") or []
if not entries:
return ActionResult(
action_log=f"{data.get('path') or path} is empty.",
new_state=f"{data.get('path') or path} is empty.",
)
lines = []
for entry in entries[:20]:
name = entry.get("name") or "(unnamed)"
kind = "folder" if entry.get("is_folder") else "file"
size = entry.get("size")
detail = f"{kind}"
if kind == "file" and size is not None:
detail += f", {size} bytes"
lines.append(f"- {name} ({detail})")
report = f"Files in {data.get('path') or path}:\n" + "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
@@ -1,141 +0,0 @@
"""Hermetic mechanics test for outlook.list_files.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/files` route and records the path
it received. This proves the body lists OneDrive and reports the entries (and
fails honestly when the bridge is unavailable). It does NOT prove the live
integration — only a real run against the user's Microsoft account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.list_files must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
entries = []
status = 200
paths = []
def do_GET(self):
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
parsed = urlparse(self.path)
if parsed.path == "/files":
path = parse_qs(parsed.query).get("path", ["/"])[0]
self.paths.append(path)
self._send({"path": path, "entries": self.entries}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def start_server(entries=None, status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"entries": entries
if entries is not None
else [
{"id": "d1", "name": "Docs", "is_folder": True, "size": 0},
{"id": "f1", "name": "notes.txt", "is_folder": False, "size": 5},
],
"status": status,
"paths": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="list my files"):
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_lists_root_files():
server, handler, url = start_server()
try:
action = run(url)
assert "Docs (folder)" in action.action_log, action.action_log
assert "notes.txt (file, 5 bytes)" in action.action_log, action.action_log
assert handler.paths and handler.paths[0] == "/", handler.paths
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_named_folder_is_requested():
server, handler, url = start_server()
try:
run(url, "list files in Documents")
assert handler.paths and handler.paths[0] == "Documents", handler.paths
print(handler.paths)
finally:
server.shutdown()
server.server_close()
def test_empty_folder_is_reported():
server, _handler, url = start_server(entries=[])
try:
action = run(url)
assert "empty" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "list my files"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_lists_root_files()
test_named_folder_is_requested()
test_empty_folder_is_reported()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Read the user's upcoming Outlook calendar events."
}
@@ -1,89 +0,0 @@
"""Read the user's upcoming Outlook calendar events.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. It asks the bridge for the upcoming events and
reports them, or reports the real failure honestly.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
DEFAULT_COUNT = 5
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _get(ctx, path, params=None):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, method="GET", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
def act(ctx, request):
try:
data = _get(ctx, "/calendars/events")
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
events = data.get("events") or []
if not events:
return ActionResult(action_log="There are no upcoming events.", new_state="No upcoming events.")
lines = []
for event in events[:DEFAULT_COUNT]:
subject = event.get("subject") or "(no subject)"
start = event.get("start") or ""
when = _describe_when(start, bool(event.get("all_day")))
location = event.get("location") or ""
where = f" at {location}" if location else ""
lines.append(f"- {subject}{where} — {when}")
report = "Upcoming events:\n" + "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
def _describe_when(start, all_day):
"""A short human time: the date (all-day) or date + time."""
text = str(start or "").strip()
if not text:
return "time unknown"
date, _, rest = text.partition("T")
if all_day or not rest:
return f"{date} (all day)" if all_day else date
return f"{date} {rest[:5]}"
@@ -1,136 +0,0 @@
"""Hermetic mechanics test for outlook.next_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/calendars/events` route. This
proves the body asks the bridge for upcoming events and reports them (and fails
honestly when the bridge is unavailable). It does NOT prove the live
integration — only a real run against the user's Microsoft account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.next_event must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
events = []
status = 200
def do_GET(self):
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/calendars/events"):
self._send({"calendar": "", "events": self.events}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def start_server(events=None, status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"events": events
if events is not None
else [
{
"id": "e1",
"subject": "Standup",
"start": "2026-10-08T09:00:00.0000000",
"end": "2026-10-08T09:30:00.0000000",
"all_day": False,
"location": "Room 1",
}
],
"status": status,
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="what's on my calendar"):
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_upcoming_events():
server, url = start_server()
try:
action = run(url)
assert "Standup" in action.action_log, action.action_log
assert "Room 1" in action.action_log, action.action_log
assert "2026-10-08 09:00" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_no_events_is_reported():
server, url = start_server(events=[])
try:
action = run(url)
assert "no upcoming events" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "what's on my calendar"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
action = run("http://127.0.0.1:1")
assert action.new_state == "what's on my calendar"
print(action.action_log)
def main():
test_reports_upcoming_events()
test_no_events_is_reported()
test_bridge_error_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Read the latest messages from the user's Outlook inbox."
}
@@ -1,77 +0,0 @@
"""Read the latest messages from the user's Outlook inbox.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. It asks the bridge for the newest inbox messages
and reports them, or reports the real failure honestly.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
DEFAULT_COUNT = 5
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _get(ctx, path, params=None):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, method="GET", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
def act(ctx, request):
try:
data = _get(ctx, "/mail/messages", {"folder": "inbox", "count": DEFAULT_COUNT})
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
messages = data.get("messages") or []
if not messages:
return ActionResult(action_log="The inbox is empty.", new_state="The inbox is empty.")
lines = []
for message in messages[:DEFAULT_COUNT]:
sender = message.get("from") or "unknown sender"
subject = message.get("subject") or "(no subject)"
received = message.get("received") or ""
flag = " (unread)" if not message.get("is_read") else ""
lines.append(f"- {sender}: {subject}{flag} [{received}]")
report = "Recent inbox messages:\n" + "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
@@ -1,140 +0,0 @@
"""Hermetic mechanics test for outlook.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/mail/messages` route. This proves
the body asks the bridge for the inbox and reports the messages (and fails
honestly when the bridge is unavailable). It does NOT prove the live
integration — only a real run against the user's Microsoft account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.next_message must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
messages = []
requests = []
status = 200
def do_GET(self):
self.requests.append(self.path)
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/mail/messages"):
self._send({"folder": "inbox", "messages": self.messages}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def start_server(messages=None, status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"messages": messages
if messages is not None
else [
{
"id": "m1",
"subject": "Lunch?",
"from": "Sam <sam@example.com>",
"received": "2026-10-08T12:00:00Z",
"is_read": False,
}
],
"requests": [],
"status": status,
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="check my email"):
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_recent_messages():
server, handler, url = start_server()
try:
action = run(url)
assert "Lunch?" in action.action_log, action.action_log
assert "sam@example.com" in action.action_log, action.action_log
assert action.new_state == action.action_log
assert handler.requests, "the bridge must be called"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_inbox_is_reported():
server, _handler, url = start_server(messages=[])
try:
action = run(url)
assert "empty" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "check my email", "a failed read must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
action = run("http://127.0.0.1:1")
assert "outlook.next_message" not in action.action_log, action.action_log
assert action.new_state == "check my email"
print(action.action_log)
def main():
test_reports_recent_messages()
test_empty_inbox_is_reported()
test_bridge_error_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,6 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook 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 compose the message.",
"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."
}
@@ -1,3 +0,0 @@
{
"description": "Compose and send an Outlook email, after confirming the message."
}
@@ -1,201 +0,0 @@
"""Send an Outlook email on the user's behalf, after a confirmation.
Real integration: the local Outlook bridge (Microsoft Graph) to resolve the
recipient and send, and the local LLM bridge to turn the request into a
`{recipient, subject, body}` draft. Connection comes from `ctx.config`
(`outlook_bridge_url`, `outlook_bridge_token`, `llm_bridge_url`,
`llm_bridge_token`); the body never speaks Graph, OAuth, or the model's protocol
directly.
Because sending is irreversible, the body **asks for confirmation before it
sends**: it composes the message, resolves the recipient (an explicit address is
used as-is; otherwise the contacts are searched and, when several match, a SemIf
choice picks one), then pauses with "Send ...? (yes/no)". A `yes` sends for real;
anything else cancels. A missing recipient is asked for.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": [
"outlook_bridge_url",
"outlook_bridge_token",
"llm_bridge_url",
"llm_bridge_token",
],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook 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 compose the message.",
"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.",
}
TIMEOUT_SECONDS = 30
_YES = {"y", "yes", "send", "ok", "okay", "sure", "confirm"}
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook or LLM bridge."""
def _request(ctx, service, path, *, method="GET", params=None, payload=None):
if service == "llm":
base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
token = str(ctx.config.get("llm_bridge_token", "") or "").strip()
else:
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
if not base:
raise OutlookBridgeError(f"the {service} bridge URL is not configured")
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
data = json.dumps(payload).encode("utf-8") if payload is not None else None
headers = {"Accept": "application/json"}
if data is not None:
headers["Content-Type"] = "application/json"
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"{method} {path}: {exc}") from exc
def _compose(ctx, request):
"""Ask the LLM bridge for the recipient, subject, and body."""
messages = [
{
"role": "system",
"content": (
"Turn the user's request into an email. Reply with ONLY a JSON "
'object: {"recipient": "<name or email address>", '
'"subject": "<short subject>", "body": "<the message>"}.'
),
},
{"role": "user", "content": request.text},
]
data = _request(ctx, "llm", "/chat", method="POST", payload={"messages": messages})
text = str(data.get("text") or "")
start, end = text.find("{"), text.rfind("}")
if start == -1 or end < start:
raise OutlookBridgeError("the LLM bridge returned no JSON object")
try:
draft = json.loads(text[start : end + 1])
except ValueError as exc:
raise OutlookBridgeError(f"the LLM bridge returned invalid JSON: {exc}") from exc
if not isinstance(draft, dict):
raise OutlookBridgeError("the LLM bridge returned JSON that is not an object")
return {
"recipient": str(draft.get("recipient") or "").strip(),
"subject": str(draft.get("subject") or "").strip(),
"body": str(draft.get("body") or "").strip(),
}
def _resolve_address(ctx, decisions, recipient):
"""An email address for `recipient`: used directly, or chosen from contacts."""
if "@" in recipient:
return recipient
data = _request(ctx, "outlook", "/contacts", params={"query": recipient})
contacts = [c for c in (data.get("contacts") or []) if c.get("emails")]
if not contacts:
return None
if len(contacts) == 1:
return str(contacts[0]["emails"][0])
options = [
Option(str(contact["emails"][0]), str(contact.get("display_name") or contact["emails"][0]))
for contact in contacts
]
decision = DecisionRequest(
state=recipient,
question="Which contact should the message be sent to?",
options=options,
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
return str(result.selected)
def _ask(request, question):
return ActionResult(action_log="waiting for input", new_state=request.text, needs_input=question)
def act(ctx, request):
meta = request.meta
awaiting = meta.get("send_message_awaiting")
decisions = []
# Resume: the user answered the recipient/address/confirmation question.
if request.user_input is not None and awaiting:
if awaiting == "confirm":
ready = meta.get("send_message_ready") or {}
meta.pop("send_message_awaiting", None)
if request.user_input.strip().lower() not in _YES:
return ActionResult(
action_log="Cancelled; the message was not sent.",
new_state="cancelled",
)
try:
result = _request(
ctx,
"outlook",
"/mail/send",
method="POST",
payload={"to": [ready.get("to", "")], "subject": ready.get("subject", ""), "body": ready.get("body", "")},
)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
report = f"Sent {ready.get('subject')!r} to {ready.get('to')}."
meta.pop("send_message_ready", None)
return ActionResult(action_log=report, new_state=report)
meta.setdefault("send_message_answers", {})[awaiting] = request.user_input.strip()
meta.pop("send_message_awaiting", None)
answers = meta.get("send_message_answers") or {}
draft = meta.get("send_message_composed")
if draft is None:
try:
draft = _compose(ctx, request)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
meta["send_message_composed"] = draft
recipient = answers.get("recipient") or draft["recipient"]
if not recipient:
meta["send_message_awaiting"] = "recipient"
return _ask(request, "Who should I send the message to?")
address = answers.get("address")
if not address:
try:
address = _resolve_address(ctx, decisions, recipient)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
if not address:
meta["send_message_awaiting"] = "address"
return _ask(request, f"What's the email address for {recipient!r}?")
meta["send_message_ready"] = {"to": address, "subject": draft["subject"], "body": draft["body"]}
meta["send_message_awaiting"] = "confirm"
action = _ask(request, f"Send {draft['subject']!r} to {address}? (yes/no)")
action.decisions = decisions
return action
@@ -1,216 +0,0 @@
"""Hermetic mechanics test for outlook.send_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local LLM bridge (`POST /chat`), the Outlook bridge's
contact lookup, and `POST /mail/send`. This proves the body composes a draft,
resolves the recipient, asks for confirmation BEFORE sending, sends for real on
`yes`, cancels otherwise, and fails honestly when the LLM bridge is down. It does
NOT prove the live integration — only a real run against the user's Microsoft
account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
"""Picks `pick` (else the first option) with full confidence."""
def __init__(self, pick=None):
self.pick = pick
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
ids = [option.id for option in decision.options]
chosen = self.pick if self.pick in ids else ids[0]
probs = [1.0 if option_id == chosen else 0.0 for option_id in ids]
return DecisionResult(request=decision, option_ids=ids, probabilities=probs)
class BridgeHandler(BaseHTTPRequestHandler):
draft = {"recipient": "Sam", "subject": "Lunch", "body": "Tomorrow?"}
contacts = [{"id": "c1", "display_name": "Sam", "emails": ["sam@example.com"]}]
llm_status = 200
sends = []
queries = []
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def do_POST(self):
body = self._read()
if self.path == "/chat":
if self.llm_status != 200:
self._send({"error": "boom"}, self.llm_status)
return
self._send({"text": json.dumps(self.draft)}, 200)
return
if self.path == "/mail/send":
self.sends.append(json.loads(body.decode("utf-8")))
self._send({"ok": True, "to": self.sends[-1].get("to")}, 200)
return
self._send({"error": "not found"}, 404)
def do_GET(self):
parsed = urlparse(self.path)
if parsed.path == "/contacts":
self.queries.append(parse_qs(parsed.query).get("query", [""])[0])
self._send({"contacts": self.contacts}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def start_server(**overrides):
attrs = {
"draft": {"recipient": "Sam", "subject": "Lunch", "body": "Tomorrow?"},
"contacts": [{"id": "c1", "display_name": "Sam", "emails": ["sam@example.com"]}],
"llm_status": 200,
"sends": [],
"queries": [],
}
attrs.update(overrides)
handler = type("Handler", (BridgeHandler,), attrs)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def context(url, engine):
return ActionContext(
engine=engine,
config={
"outlook_bridge_url": url,
"outlook_bridge_token": "",
"llm_bridge_url": url,
"llm_bridge_token": "",
},
)
def test_confirms_then_sends():
server, handler, url = start_server()
try:
ctx = context(url, FakeEngine())
request = Request("email Sam that lunch is tomorrow")
action = skill.act(ctx, request)
assert action.needs_input and "send" in action.needs_input.lower(), action.needs_input
assert handler.sends == [], "nothing may be sent before confirmation"
request.user_input = "yes"
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert handler.sends[0]["to"] == ["sam@example.com"], handler.sends
assert handler.sends[0]["subject"] == "Lunch", handler.sends
assert "sent" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_cancel_does_not_send():
server, handler, url = start_server()
try:
ctx = context(url, FakeEngine())
request = Request("email Sam that lunch is tomorrow")
skill.act(ctx, request)
request.user_input = "no"
action = skill.act(ctx, request)
assert handler.sends == [], "a cancelled message must not be sent"
assert "cancel" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_multiple_contacts_use_semif_choice():
contacts = [
{"id": "c1", "display_name": "Sam A", "emails": ["sam.a@example.com"]},
{"id": "c2", "display_name": "Sam B", "emails": ["sam.b@example.com"]},
]
server, handler, url = start_server(contacts=contacts)
try:
engine = FakeEngine(pick="sam.b@example.com")
ctx = context(url, engine)
request = Request("email Sam that lunch is tomorrow")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1, engine.decisions
assert "sam.b@example.com" in action.needs_input, action.needs_input
request.user_input = "yes"
action = skill.act(ctx, request)
assert handler.sends[0]["to"] == ["sam.b@example.com"], handler.sends
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_explicit_address_is_used():
server, handler, url = start_server(
draft={"recipient": "bob@example.com", "subject": "Late", "body": "I'll be late"}
)
try:
ctx = context(url, FakeEngine(pick="sam@example.com"))
request = Request("email bob@example.com that I'll be late")
skill.act(ctx, request)
request.user_input = "yes"
skill.act(ctx, request)
assert handler.sends[0]["to"] == ["bob@example.com"], handler.sends
# No contact lookup is needed for an explicit address.
assert handler.queries == [], handler.queries
print(handler.sends[0])
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_failure_is_reported_honestly():
server, handler, url = start_server(llm_status=502)
try:
ctx = context(url, FakeEngine())
request = Request("email Sam that lunch is tomorrow")
action = skill.act(ctx, request)
assert "502" in action.action_log, action.action_log
assert handler.sends == []
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_confirms_then_sends()
test_cancel_does_not_send()
test_multiple_contacts_use_semif_choice()
test_explicit_address_is_used()
test_llm_bridge_failure_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-26
View File
@@ -1,26 +0,0 @@
{
"name": "simplex",
"title": "SimpleX",
"concern": "SimpleX messaging through the forwarding bridge: reading incoming messages, sending messages to contacts, and showing the user's contact link.",
"categories": {
"simplex": "SimpleX messaging: reading incoming messages, sending messages to contacts, and showing the user's contact link."
},
"bridges": ["simplex"],
"requires": [],
"enabled_by_default": true,
"config": {
"enabled": {"type": "bool", "default": true, "doc": "Load this pack's skills and run its bridge."},
"host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."},
"port": {"type": "int", "default": 5227, "doc": "Bridge listen port."},
"token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."},
"max_inbox": {"type": "int", "default": 100, "doc": "Bound on the in-memory inbound-message buffer."},
"ws_url": {"type": "str", "default": "ws://127.0.0.1:5228", "doc": "The bridge's OWN simplex-chat daemon WebSocket URL (must match simplex_chat.forward_port)."},
"user_id": {"type": "int", "default": 1, "doc": "Daemon user id the bridge acts as."},
"auto_accept": {"type": "bool", "default": true, "doc": "Auto-accept inbound contact requests."},
"reconnect": {
"initial": {"type": "float", "default": 1.0, "doc": "Initial reconnect delay (seconds)."},
"max": {"type": "float", "default": 60.0, "doc": "Maximum reconnect delay (seconds)."},
"jitter": {"type": "float", "default": 0.2, "doc": "Reconnect jitter fraction."}
}
}
}
@@ -1,4 +0,0 @@
{
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Show (creating if needed) the SimpleX contact link others use to connect to this agent."
}
@@ -1,107 +0,0 @@
"""Show the SimpleX contact link others use to connect to this agent.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`, `simplex_bridge_token`). The bridge's own connection to
the `simplex-chat` daemon is the only thing that can read (or create) the
forwarding bot's *user contact address*; this body asks the bridge for it and
reports the link honestly. It never opens a WebSocket to the daemon and never
invents a link: if the bridge is not running or has no address, it says so.
`act` health-checks the bridge, then `GET /address` shows the existing link and
creates one on first call, returning `{short_link, full_link, created}`.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
class BridgeError(Exception):
"""The SimpleX forwarding bridge is unreachable or returned an error."""
# ---- transport ----
def _base(ctx):
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
if not url:
raise BridgeError("simplex_bridge_url is not configured")
return url
def _headers(ctx):
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
return {"X-Semif-Token": token} if token else {}
def _get(ctx, path):
request = urllib.request.Request(
_base(ctx) + path, headers=_headers(ctx)
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"GET {path}: {exc}") from exc
# ---- skill phases ----
def act(ctx, request):
try:
payload = _get(ctx, "/health")
except BridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
if not payload.get("ok"):
return ActionResult(
action_log="simplex forwarding bridge is not healthy",
new_state=request.text,
)
try:
payload = _get(ctx, "/address")
except BridgeError as exc:
return ActionResult(
action_log=f"reading the contact link failed: {exc}",
new_state=request.text,
)
short = str(payload.get("short_link") or "").strip()
full = str(payload.get("full_link") or "").strip()
if not (short or full):
return ActionResult(
action_log=(
"the bridge returned no SimpleX "
"contact link; the bot has no address yet."
),
new_state=request.text,
)
verb = "created" if payload.get("created") else "current"
lines = [f"SimpleX contact link ({verb}): {short or full}"]
if short and full:
lines.append(f"Full link: {full}")
lines.append(
"Share this link with someone so they can add the agent and message it."
)
report = "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
@@ -1,174 +0,0 @@
"""Hermetic mechanics test for simplex.connect_link.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body health-
checks the bridge, fetches the contact link, reports a freshly created link, and
fails honestly when the bridge has no provider or is unreachable. It does NOT
prove the live integration — only a real run against the bridge and a real
simplex-chat daemon does.
"""
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class BridgeHandler(BaseHTTPRequestHandler):
address = {}
address_status = 200
requests = []
tokens = []
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.requests.append(self.path)
self.tokens.append(self.headers.get("X-Semif-Token"))
url = urllib.parse.urlparse(self.path)
if url.path == "/health":
self._send({"ok": True, "platform": "simplex"})
elif url.path == "/address":
self._send(self.address, self.address_status)
else:
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(address=None, address_status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"address": address or {},
"address_status": address_status,
"requests": [],
"tokens": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url, token=""):
return {"simplex_bridge_url": url, "simplex_bridge_token": token}
def test_reports_existing_link():
server, handler, url = start_server(
{"short_link": "simplex:/contact#abc", "full_link": "https://smp/short", "created": False}
)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert "https://smp/short" in action.action_log, action.action_log
assert "current" in action.action_log, action.action_log
assert handler.requests == ["/health", "/address"], handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_reports_freshly_created_link():
server, handler, url = start_server(
{"short_link": "simplex:/contact#new", "full_link": "", "created": True}
)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("create a simplex invitation link")
action = skill.act(ctx, request)
assert "simplex:/contact#new" in action.action_log, action.action_log
assert "created" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_no_provider_is_reported_honestly():
server, handler, url = start_server({"error": "address lookup is not available"}, 503)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "503" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed lookup must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_link_is_reported_honestly():
server, handler, url = start_server({"short_link": "", "full_link": "", "created": False})
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "no SimpleX" in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1"))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert action.action_log and "simplex.connect_link" not in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
def test_auth_token_is_sent_when_configured():
server, handler, url = start_server(
{"short_link": "simplex:/contact#abc", "full_link": "", "created": False}
)
try:
ctx = ActionContext(engine=None, config=config(url, token="sekret"))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reports_existing_link()
test_reports_freshly_created_link()
test_no_provider_is_reported_honestly()
test_empty_link_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
test_auth_token_is_sent_when_configured()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,5 +0,0 @@
{
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate."
}
@@ -1,3 +0,0 @@
{
"description": "Read the next unread SimpleX message."
}
@@ -1,303 +0,0 @@
"""Read the next unread SimpleX message through the forwarding bridge.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
`act` peeks that inbox, finds which conversations have unread messages, and
resolves which one to read with a SemIf choice over them (state = the user
query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise
the configured default contact is used; with no configured default (or a default
with no unread message) the weak winner stands. It then pops and reports the
oldest unread message for that conversation.
When the live buffer is empty it falls back to the daemon's persistent unread
(`/unread` + `/history`), so a message that arrived before the bridge started is
still reported. After reporting a message, that single item is marked read on
the daemon through the bridge (`POST /read`), so the next call advances to the
next unread message instead of re-reporting the same one.
The bridge owns the read cursor, so this skill keeps no state of its own. It
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
messaging surface it uses.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": [
"simplex_bridge_url",
"simplex_bridge_token",
"simplex_default_contact",
],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate.",
}
TIMEOUT_SECONDS = 20
# A SemIf probability at or above this counts as a "strong winner" for the
# conversation; below it the configured default contact is used instead.
CONTACT_WINNER_TAU = 0.6
class BridgeError(Exception):
"""The SimpleX forwarding bridge is unreachable or returned an error."""
# ---- transport ----
def _base(ctx):
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
if not url:
raise BridgeError("simplex_bridge_url is not configured")
return url
def _headers(ctx):
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
return {"X-Semif-Token": token} if token else {}
def _get(ctx, path):
request = urllib.request.Request(
_base(ctx) + path, headers=_headers(ctx)
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"GET {path}: {exc}") from exc
def _post(ctx, path, payload):
data = json.dumps(payload).encode("utf-8")
headers = {**_headers(ctx), "Content-Type": "application/json"}
request = urllib.request.Request(
_base(ctx) + path, data=data, headers=headers, method="POST"
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"POST {path}: {exc}") from exc
def _mark_read(ctx, contact, item_id):
"""Mark one just-reported item read via the bridge.
Returns None on success, or a short honest reason string on failure. The
message was still reported, so a failed consume is surfaced as a note rather
than fabricated into a read failure.
"""
item = str(item_id or "").strip()
if not item:
return None
try:
payload = _post(ctx, "/read", {"contact": contact, "item_ids": [item]})
except BridgeError as exc:
return str(exc)
if not payload.get("ok"):
return payload.get("error") or "the bridge did not mark it read"
return None
# ---- conversation resolution ----
def _senders(messages):
"""Distinct conversations with buffered messages, in arrival order."""
senders = []
seen = set()
for message in messages:
contact = str(message.get("contact_id") or "")
if not contact or contact in seen:
continue
seen.add(contact)
senders.append(
{"id": contact, "display_name": message.get("display_name") or contact}
)
return senders
def _is_healthy(sender):
"""A conversation is healthy when its connection is not known-bad.
`connected` is absent when the source did not report it (treat as unknown);
`auth_errors` counts failed sends on the connection and marks a stale peer.
"""
if sender.get("connected") is False:
return False
try:
return int(sender.get("auth_errors") or 0) == 0
except (TypeError, ValueError):
return True
def _default_sender(ctx, senders):
"""The configured default contact, if it has unread messages."""
default = str(ctx.config.get("simplex_default_contact", "") or "").strip()
if not default:
return None
for sender in senders:
if sender["id"] == default or sender["display_name"] == default:
return sender
return None
def _resolve_contact(ctx, request, senders, decisions):
"""Resolve which conversation to read, mirroring nextcloud.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default contact, and with no configured default the weak winner stands.
"""
default = _default_sender(ctx, senders)
if len(senders) == 1:
return senders[0]["id"]
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CONTACT_WINNER_TAU:
return winner
if default is not None:
return default["id"]
return winner
# ---- skill phases ----
def act(ctx, request):
try:
payload = _get(ctx, "/inbox")
except BridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
senders = _senders(payload.get("messages") or [])
if senders:
return _read_live(ctx, request, senders)
# The live buffer only holds messages that arrived while the bridge was
# connected; fall back to the daemon's persistent unread so a message that
# landed before the bridge started is not silently missed.
return _read_persistent(ctx, request)
def _read_live(ctx, request, senders):
decisions = []
contact = _resolve_contact(ctx, request, senders, decisions)
try:
payload = _get(
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
)
except BridgeError as exc:
return ActionResult(
action_log=f"failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
message = payload.get("message")
if not message:
return ActionResult(
action_log=f"no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
read_note = _mark_read(ctx, contact, message.get("item_id"))
return _report(
message.get("display_name") or contact,
message.get("text"),
decisions,
read_note,
)
def _read_persistent(ctx, request):
try:
payload = _get(ctx, "/unread")
except BridgeError as exc:
return ActionResult(
action_log=f"no unread SimpleX messages ({exc}).",
new_state="no unread SimpleX messages",
)
chats = [c for c in (payload.get("chats") or []) if c.get("unread")]
if not chats:
return ActionResult(
action_log="no unread SimpleX messages.",
new_state="no unread SimpleX messages",
)
senders = [
{
"id": str(chat.get("contact_id") or ""),
"display_name": chat.get("display_name") or str(chat.get("contact_id") or ""),
"connected": chat.get("connected"),
"auth_errors": chat.get("auth_errors"),
}
for chat in chats
if chat.get("contact_id")
]
decisions = []
healthy = [s for s in senders if _is_healthy(s)]
if len(healthy) == 1:
# Exactly one conversation is on a healthy connection (the rest are
# stale duplicates): read it without a coin-flip decision.
contact = healthy[0]["id"]
else:
contact = _resolve_contact(ctx, request, senders, decisions)
try:
history = _get(
ctx, f"/history?contact={urllib.parse.quote(contact)}&count=50"
)
except BridgeError as exc:
return ActionResult(
action_log=f"failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
messages = [m for m in (history.get("messages") or []) if m.get("unread")]
if not messages:
# Fall back to the previewed unread messages from /unread.
chat = next(
(c for c in chats if str(c.get("contact_id")) == str(contact)), {}
)
messages = [m for m in (chat.get("messages") or []) if m.get("unread")]
if not messages:
return ActionResult(
action_log=f"no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
sender = next(
(s["display_name"] for s in senders if s["id"] == str(contact)), str(contact)
)
read_note = _mark_read(ctx, contact, messages[0].get("item_id"))
return _report(sender, messages[0].get("text"), decisions, read_note)
def _report(sender, body, decisions, read_note=None):
report = f"SimpleX message from {sender}: {str(body or '')}"
if read_note:
report += f" (could not mark it read: {read_note})"
return ActionResult(action_log=report, new_state=report, decisions=decisions)
@@ -1,425 +0,0 @@
"""Hermetic mechanics test for simplex.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body
peeks the inbox, resolves the conversation through a SemIf sub-decision (a
strong winner is used, otherwise the configured default, otherwise the weak
winner), pops the real `next` message, and fails honestly when the bridge is
unreachable. It does NOT prove the live integration — only a real run against
the bridge and a real contact does.
"""
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class BridgeHandler(BaseHTTPRequestHandler):
messages = []
unread_chats = []
history = {}
requests = []
tokens = []
read_calls = []
read_ok = True
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.requests.append(self.path)
self.tokens.append(self.headers.get("X-Semif-Token"))
url = urllib.parse.urlparse(self.path)
if url.path == "/inbox":
self._send({"messages": list(self.messages)})
elif url.path == "/inbox/next":
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
found = None
for index, message in enumerate(self.messages):
if contact is None or message["contact_id"] == str(contact):
found = self.messages.pop(index)
break
self._send({"message": found})
elif url.path == "/unread":
self._send({"chats": list(self.unread_chats)})
elif url.path == "/history":
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
self._send(
{"contact_id": contact, "messages": list(self.history.get(str(contact), []))}
)
else:
self._send({"error": "not found"}, 404)
def do_POST(self):
url = urllib.parse.urlparse(self.path)
length = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(length).decode("utf-8") or "{}")
if url.path != "/read":
self._send({"error": "not found"}, 404)
return
self.read_calls.append(payload)
if self.read_ok:
self._send(
{
"ok": True,
"contact_id": payload.get("contact"),
"item_ids": payload.get("item_ids"),
"status": "read",
}
)
else:
self._send({"ok": False, "error": "the daemon rejected the read"})
def log_message(self, *args):
pass
def start_server(messages, unread_chats=None, history=None, read_ok=True):
handler = type(
"Handler",
(BridgeHandler,),
{
"messages": list(messages),
"unread_chats": list(unread_chats or []),
"history": dict(history or {}),
"requests": [],
"tokens": [],
"read_calls": [],
"read_ok": read_ok,
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def message(identifier, contact, name, text):
return {
"id": identifier,
"item_id": str(identifier),
"contact_id": contact,
"display_name": name,
"text": text,
"received_at": 1.0,
}
def config(url, default="", token=""):
return {
"simplex_bridge_url": url,
"simplex_default_contact": default,
"simplex_bridge_token": token,
}
def test_multiple_senders_uses_semif_decision():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(pick="7")
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the conversation choice"
assert len(engine.decisions) == 1
assert "Bob" in action.action_log, action.action_log
assert "shipment arrived" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
assert handler.requests[0] == "/inbox", handler.requests
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
assert [m["id"] for m in handler.messages] == ["m1"], "the popped message must be consumed"
assert handler.read_calls == [{"contact": "7", "item_ids": ["m2"]}], (
"the reported item must be marked read, and only it"
)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_strong_winner_overrides_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(probs={"4": 0.1, "7": 0.9})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message from Bob")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1, "the conversation is chosen with one SemIf decision"
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_falls_back_to_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
# Bob edges out Alice but stays below the strong-winner threshold, so the
# configured default ("Alice") is used instead.
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
assert "hello there" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_without_default_stands():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_single_sender_needs_no_decision():
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert engine.decisions == []
assert "hi" in action.action_log, action.action_log
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_inbox_is_reported_honestly():
server, handler, url = start_server([])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert "no unread" in action.action_log, action.action_log
# An empty live buffer falls back to the daemon's persistent unread.
assert handler.requests == ["/inbox", "/unread"], handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_live_inbox_falls_back_to_persistent_unread():
server, handler, url = start_server(
[],
unread_chats=[
{
"contact_id": "3",
"display_name": "pepper",
"unread_count": 2,
"min_unread_item_id": "8",
"unread": True,
"messages": [],
}
],
history={
"3": [
{"item_id": "8", "text": "hello", "status": "rcvNew", "unread": True},
{"item_id": "9", "text": "hey yo", "status": "rcvNew", "unread": True},
]
},
)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert engine.decisions == [], "a single unread chat needs no decision"
assert "hello" in action.action_log, action.action_log
assert "pepper" in action.action_log, action.action_log
assert handler.requests == ["/inbox", "/unread", "/history?contact=3&count=50"], (
handler.requests
)
assert handler.read_calls == [{"contact": "3", "item_ids": ["8"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_persistent_unread_prefers_a_healthy_conversation():
server, handler, url = start_server(
[],
unread_chats=[
{
"contact_id": "3",
"display_name": "pepper",
"unread_count": 1,
"unread": True,
"connected": True,
"auth_errors": 2,
"messages": [],
},
{
"contact_id": "4",
"display_name": "pepper",
"unread_count": 1,
"unread": True,
"connected": True,
"auth_errors": 0,
"messages": [],
},
],
history={
"3": [{"item_id": "8", "text": "stale hello", "status": "rcvNew", "unread": True}],
"4": [{"item_id": "20", "text": "fresh hello", "status": "rcvNew", "unread": True}],
},
)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, Request("read my next simplex message"))
assert engine.decisions == [], "one healthy chat must win without a decision"
assert "fresh hello" in action.action_log, action.action_log
assert handler.requests == ["/inbox", "/unread", "/history?contact=4&count=50"], (
handler.requests
)
assert handler.read_calls == [{"contact": "4", "item_ids": ["20"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert action.action_log and "simplex.next_message" not in action.action_log, action.action_log
assert action.new_state == request.text, "a failed read must not fake a result"
print(action.action_log)
def test_auth_token_is_sent_when_configured():
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, token="sekret"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert "hi" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_failed_read_marking_is_surfaced_honestly():
"""A message is still reported when consuming it fails, with an honest note
instead of a fabricated failure of the read."""
server, handler, url = start_server(
[message("m1", "4", "Alice", "hi")], read_ok=False
)
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
action = skill.act(ctx, Request("read my next simplex message"))
assert "hi" in action.action_log, action.action_log
assert "could not mark it read" in action.action_log, action.action_log
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_multiple_senders_uses_semif_decision()
test_strong_winner_overrides_default_contact()
test_weak_winner_falls_back_to_default_contact()
test_weak_winner_without_default_stands()
test_single_sender_needs_no_decision()
test_empty_inbox_is_reported_honestly()
test_empty_live_inbox_falls_back_to_persistent_unread()
test_persistent_unread_prefers_a_healthy_conversation()
test_unreachable_bridge_fails_honestly()
test_auth_token_is_sent_when_configured()
test_failed_read_marking_is_surfaced_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,7 +0,0 @@
{
"simplex_bridge_url": "Base URL of the local SimpleX forwarding bridge that fronts the user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the SimpleX bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not clearly name a recipient; leave blank to always use the strongest candidate.",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to write the message text when the request does not state it.",
"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."
}
@@ -1,3 +0,0 @@
{
"description": "Send a SimpleX message to a contact through the forwarding bridge."
}
@@ -1,482 +0,0 @@
"""Send a text message to a SimpleX contact through the local SimpleX bridge.
Real integration: the simplex bridge over HTTP. The bridge owns the SimpleX
daemon connection and its credentials; this body only calls the bridge's HTTP
API with the base URL and token resolved from `ctx.config`.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, last_result
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": [
"simplex_bridge_url",
"simplex_bridge_token",
"simplex_default_contact",
"llm_bridge_url",
"llm_bridge_token",
],
}
CONTRACT = {
"simplex_bridge_url": (
"Base URL of the local SimpleX forwarding bridge that fronts the "
"user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash "
"needed)."
),
"simplex_bridge_token": (
"Shared secret for the SimpleX bridge, if one is configured; sent as "
"the X-Semif-Token header. Leave blank when the bridge requires no auth."
),
"simplex_default_contact": (
"Default SimpleX contact (contact id or display name) used when the "
"request does not clearly name a recipient; leave blank to always use "
"the strongest candidate."
),
"llm_bridge_url": (
"Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no "
"trailing slash needed); used to write the message text when the "
"request does not state it."
),
"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."
),
}
# A contact sub-decision winner is used only when its conditional probability
# clears this bar; otherwise the configured default contact wins.
CONFIDENCE_THRESHOLD = 0.5
_HTTP_TIMEOUT = 20
# Ordered: the literal message text the user dictated wins over anything else.
_MESSAGE_PATTERNS = (
r"\b(?:saying|say|that says|which says|that reads|reads)\b\s*[:\-]?\s*(.+)$",
r'["\u201c](.+?)["\u201d]',
r"\b(?:message|text)\s*(?:is|:)\s*(.+)$",
)
# --------------------------------------------------------------------------
# bridge transport
# --------------------------------------------------------------------------
def _headers(token: str, has_body: bool) -> dict:
headers = {"Accept": "application/json"}
if has_body:
headers["Content-Type"] = "application/json"
if token:
headers["X-Semif-Token"] = token
return headers
def _http_json(url: str, token: str, payload=None):
"""GET the url, or POST the payload as JSON, and decode the JSON reply."""
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
url,
data=data,
headers=_headers(token, data is not None),
method="POST" if data is not None else "GET",
)
with urllib.request.urlopen(request, timeout=_HTTP_TIMEOUT) as response:
raw = response.read().decode("utf-8")
if not raw.strip():
return {}
return json.loads(raw)
def _error_detail(exc) -> str:
"""Best-effort human-readable detail from an HTTP error response."""
try:
raw = exc.read().decode("utf-8", "replace")
except Exception:
raw = ""
if raw:
try:
parsed = json.loads(raw)
except ValueError:
parsed = None
if isinstance(parsed, dict) and parsed.get("error"):
return str(parsed["error"])
return raw.strip()
return str(getattr(exc, "reason", "") or exc)
# --------------------------------------------------------------------------
# contacts
# --------------------------------------------------------------------------
def _contact_id(contact) -> str:
return str(contact.get("id") or contact.get("display_name") or "").strip()
def _display(contact) -> str:
return str(contact.get("display_name") or contact.get("id") or "").strip()
def _label(contact) -> str:
"""The unique name for a contact: the daemon's local name when known.
Two peers can share a profile display name; the local name is unique, so it
is the right label for a SemIf option and the right thing to match on.
"""
return str(
contact.get("local_name") or _display(contact) or contact.get("id") or ""
).strip()
def _is_healthy(contact) -> bool:
"""A contact is healthy when its connection is not known-bad.
`connected` is absent when the source did not report it (treat as unknown,
i.e. not disqualifying); `auth_errors` counts failed sends on the connection
and marks a stale/duplicate peer.
"""
if contact.get("connected") is False:
return False
try:
return int(contact.get("auth_errors") or 0) == 0
except (TypeError, ValueError):
return True
def _mentions(query: str, name: str) -> bool:
if not name:
return False
pattern = r"(?<!\w)" + re.escape(name.lower()) + r"(?!\w)"
return re.search(pattern, query.lower()) is not None
def _match_contact(contacts, ref: str):
"""Resolve an id or display name against the bridge's contact list."""
ref = (ref or "").strip()
if not ref:
return None
lowered = ref.lower()
for contact in contacts:
if _contact_id(contact).lower() == lowered:
return contact
exact = [
c
for c in contacts
if _label(c).lower() == lowered or _display(c).lower() == lowered
]
if exact:
return _preferred(exact)
matches = [
c
for c in contacts
if lowered in _display(c).lower() or lowered in _label(c).lower()
]
if len(matches) == 1:
return matches[0]
if matches:
return _preferred(matches)
return None
def _preferred(candidates):
"""Prefer a healthy candidate (the others are likely stale duplicates)."""
healthy = [c for c in candidates if _is_healthy(c)]
return (healthy or candidates)[0]
def _find_by_id(contacts, contact_id):
wanted = str(contact_id or "")
for contact in contacts:
if _contact_id(contact) == wanted:
return contact
return None
def _confidence(result, option_id) -> float:
prob = getattr(result, "prob", None)
if callable(prob):
try:
return float(prob(option_id))
except Exception:
return 0.0
probs = getattr(result, "probs", None)
if isinstance(probs, dict):
try:
return float(probs.get(option_id, 0.0))
except (TypeError, ValueError):
return 0.0
return 0.0
# --------------------------------------------------------------------------
# message text
# --------------------------------------------------------------------------
def _message_from_query(query: str) -> str:
"""Pull the literal message text out of the user's request, if stated."""
for pattern in _MESSAGE_PATTERNS:
match = re.search(pattern, query, flags=re.IGNORECASE | re.DOTALL)
if match:
text = match.group(1).strip().strip("\"'\u201c\u201d").strip()
if text:
return text
return ""
def _llm_message_text(ctx, query: str):
"""Ask the LLM bridge to write the message body. Returns (text, reason)."""
base_url = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
if not base_url:
return None, "no llm bridge is configured"
token = str(ctx.config.get("llm_bridge_token", "") or "")
payload = {
"messages": [
{
"role": "system",
"content": (
"You write the exact text of a chat message a user wants to "
"send. Reply with the message text only: no quotes, no "
"preamble, no explanation."
),
},
{"role": "user", "content": query},
],
"max_tokens": 256,
}
try:
reply = _http_json(f"{base_url}/chat", token, payload)
except urllib.error.HTTPError as exc:
return None, f"the llm bridge returned HTTP {exc.code} {_error_detail(exc)}"
except (urllib.error.URLError, ValueError, OSError) as exc:
return None, f"could not reach the llm bridge: {exc}"
if not isinstance(reply, dict):
return None, "the llm bridge returned an unexpected reply"
text = str(reply.get("text", "")).strip().strip('"').strip()
if not text:
return None, "the llm bridge returned no text"
return text, ""
# --------------------------------------------------------------------------
# action
# --------------------------------------------------------------------------
def act(ctx, request) -> ActionResult:
"""Send the requested message to the requested SimpleX contact."""
base_url = str(ctx.config["simplex_bridge_url"]).strip().rstrip("/")
token = str(ctx.config.get("simplex_bridge_token", "") or "")
default_ref = str(ctx.config.get("simplex_default_contact", "") or "").strip()
query = (request.text or "").strip()
user_input = str(getattr(request, "user_input", "") or "").strip()
decisions = []
# --- the bridge's real contact list ------------------------------------
try:
payload = _http_json(f"{base_url}/contacts", token)
except urllib.error.HTTPError as exc:
return ActionResult(
action_log=(
f"the simplex bridge at {base_url} returned HTTP {exc.code} "
f"while listing contacts: {_error_detail(exc)}"
),
new_state=request.text,
)
except (urllib.error.URLError, ValueError, OSError) as exc:
return ActionResult(
action_log=(
f"could not reach the simplex bridge at {base_url} to list "
f"contacts: {exc}"
),
new_state=request.text,
)
raw_contacts = payload.get("contacts") if isinstance(payload, dict) else None
contacts = (
[c for c in raw_contacts if isinstance(c, dict)]
if isinstance(raw_contacts, list)
else []
)
# --- resolve the recipient --------------------------------------------
default_contact = _match_contact(contacts, default_ref)
named = [
c
for c in contacts
if _mentions(query, _display(c)) or _mentions(query, _label(c))
]
chosen = None
used_input_for_contact = False
if named or default_contact is not None:
candidates = list(named)
if default_contact is not None and all(
_contact_id(c) != _contact_id(default_contact) for c in candidates
):
candidates.append(default_contact)
healthy = [c for c in candidates if _is_healthy(c)]
if len(candidates) == 1:
chosen = candidates[0]
elif len(healthy) == 1:
# Exactly one candidate's connection is healthy (the rest are stale
# duplicates): pick it deterministically rather than coin-flipping.
chosen = healthy[0]
else:
decision = DecisionRequest(
state=query,
question="Which SimpleX contact should the message be sent to?",
options=[
Option(_contact_id(c), _label(c) or _contact_id(c))
for c in candidates
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
selected_id = getattr(result, "selected", None)
selected = _find_by_id(candidates, selected_id)
if (
selected is not None
and _confidence(result, selected_id) >= CONFIDENCE_THRESHOLD
):
chosen = selected
elif default_contact is not None:
chosen = default_contact
else:
chosen = selected if selected is not None else candidates[0]
elif user_input:
# The human answered the question asked on the previous pass.
chosen = _match_contact(contacts, user_input) or {
"id": user_input,
"display_name": user_input,
}
used_input_for_contact = True
if chosen is None:
known = ", ".join(_display(c) for c in contacts if _display(c)) or "none"
return ActionResult(
action_log=(
"the request does not identify a SimpleX contact to message; "
f"the bridge knows these contacts: {known}"
),
new_state=request.text,
needs_input="Which SimpleX contact should I message?",
decisions=decisions,
)
recipient = _contact_id(chosen) or _display(chosen)
display_name = _display(chosen) or recipient
# --- resolve the message text -----------------------------------------
# Prefer the literal text the user dictated; then the result of the previous
# step of a chain (never re-derive a computed value with the LLM); only then
# ask the LLM bridge for genuinely new text.
message_text = _message_from_query(query)
if not message_text and user_input and not used_input_for_contact:
message_text = user_input
if not message_text:
message_text = last_result(request)
if not message_text:
written, reason = _llm_message_text(ctx, query)
if written:
message_text = written
else:
return ActionResult(
action_log=(
f"the request does not state what the message to "
f"{display_name} should say and no message text could be "
f"written ({reason})"
),
new_state=request.text,
needs_input=f"What should the message to {display_name} say?",
decisions=decisions,
)
# --- send it through the bridge ---------------------------------------
try:
response = _http_json(
f"{base_url}/send", token, {"recipient": recipient, "text": message_text}
)
except urllib.error.HTTPError as exc:
return ActionResult(
action_log=(
f"the simplex bridge refused to send to {display_name}: "
f"HTTP {exc.code} {_error_detail(exc)}"
),
new_state=request.text,
decisions=decisions,
)
except (urllib.error.URLError, ValueError, OSError) as exc:
return ActionResult(
action_log=(
f"could not reach the simplex bridge at {base_url} to send the "
f"message to {display_name}: {exc}"
),
new_state=request.text,
decisions=decisions,
)
if not isinstance(response, dict):
return ActionResult(
action_log=(
f"the simplex bridge returned an unexpected reply while sending "
f"to {display_name}"
),
new_state=request.text,
decisions=decisions,
)
contact_id = str(response.get("contact_id") or recipient)
status = str(response.get("status") or "")
if not response.get("ok"):
detail = str(response.get("error") or "").strip() or json.dumps(response)
return ActionResult(
action_log=(
f"the message to {display_name} (contact {contact_id}) did not "
f"send (status {status or 'unknown'}: {detail})"
),
new_state=json.dumps(
{
"sent": False,
"contact_id": contact_id,
"display_name": display_name,
"status": status,
"error": detail,
"text": message_text,
}
),
decisions=decisions,
)
return ActionResult(
action_log=(
f"sent the message {message_text!r} to {display_name} "
f"(contact {contact_id}, status {status or 'ok'}) through the "
f"simplex bridge"
),
new_state=json.dumps(
{
"sent": True,
"contact_id": contact_id,
"display_name": display_name,
"status": status,
"text": message_text,
}
),
decisions=decisions,
)
@@ -1,416 +0,0 @@
"""Hermetic mechanics test for simplex.send_message.
Stands up loopback HTTP servers that imitate the simplex and llm bridges,
points the fixture config at them, and drives the body's real `act` so the
request construction, recipient/message resolution and error paths are
exercised without leaving the machine.
"""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import skill
from semif_agent.skills import ActionContext
# ---------------------------------------------------------------------------
# inline fixtures
# ---------------------------------------------------------------------------
CONTACTS = [
{"id": "c-pepper", "display_name": "pepper"},
{"id": "c-salt", "display_name": "salt"},
]
SIMPLEX_TOKEN = "s3cret-simplex-token"
LLM_TOKEN = "s3cret-llm-token"
LLM_REPLY = "a friendly hello"
class FakeRequest:
"""Minimal stand-in for the agent's Request object (test-only)."""
def __init__(self, text, user_input="", run_ledger=None):
self.text = text
self.user_input = user_input
self.run_ledger = list(run_ledger or [])
class FakeResult:
"""Stand-in for a decision result: exposes `selected` and `prob(id)`."""
def __init__(self, selected, confidence):
self.selected = selected
self._confidence = confidence
def prob(self, option_id):
return float(self._confidence) if option_id == self.selected else 0.0
class FakeEngine:
"""Test-only decision engine."""
def __init__(self, selected=None, confidence=1.0):
self.selected = selected
self.confidence = confidence
self.calls = []
def call(self, decision):
self.calls.append(decision)
selected = self.selected
if selected is None:
options = list(decision.options)
selected = options[0].id if options else None
return FakeResult(selected, self.confidence)
class _BaseHandler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def _send_json(self, code, obj):
body = json.dumps(obj).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _read_body(self):
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b""
if not raw:
return None
try:
return json.loads(raw.decode("utf-8"))
except ValueError:
return None
class SimplexHandler(_BaseHandler):
contacts = []
send_error = False
seen = []
def do_GET(self):
SimplexHandler.seen.append(
{
"method": "GET",
"path": self.path,
"token": self.headers.get("X-Semif-Token"),
}
)
if self.path == "/contacts":
self._send_json(200, {"contacts": SimplexHandler.contacts})
else:
self._send_json(404, {"error": "not found"})
def do_POST(self):
body = self._read_body()
SimplexHandler.seen.append(
{
"method": "POST",
"path": self.path,
"token": self.headers.get("X-Semif-Token"),
"body": body,
}
)
if self.path != "/send":
self._send_json(404, {"error": "not found"})
return
if SimplexHandler.send_error:
self._send_json(400, {"error": "unknown recipient"})
return
recipient = (body or {}).get("recipient", "")
self._send_json(200, {"ok": True, "contact_id": recipient})
class LlmHandler(_BaseHandler):
reply = LLM_REPLY
seen = []
def do_POST(self):
body = self._read_body()
LlmHandler.seen.append(
{
"path": self.path,
"token": self.headers.get("X-Semif-Token"),
"body": body,
}
)
if self.path == "/chat":
self._send_json(200, {"text": LlmHandler.reply})
else:
self._send_json(404, {"error": "not found"})
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
def start_server(handler):
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
def base_url(server):
return f"http://127.0.0.1:{server.server_address[1]}"
def reset(contacts=None, send_error=False):
SimplexHandler.contacts = [dict(c) for c in (contacts if contacts is not None else CONTACTS)]
SimplexHandler.send_error = send_error
SimplexHandler.seen = []
LlmHandler.seen = []
LlmHandler.reply = LLM_REPLY
# ---------------------------------------------------------------------------
# tests
# ---------------------------------------------------------------------------
def test_happy_path():
"""A named contact plus an explicit message: GET /contacts then POST /send."""
reset()
server = start_server(SimplexHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={
"simplex_bridge_url": base_url(server),
"simplex_bridge_token": SIMPLEX_TOKEN,
},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper on simplex saying hey")
)
assert result.action_log, "act must log what it did"
assert not result.needs_input, result.action_log
assert "sent" in result.action_log.lower(), result.action_log
gets = [r for r in SimplexHandler.seen if r["method"] == "GET"]
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert any(r["path"] == "/contacts" for r in gets), SimplexHandler.seen
assert len(posts) == 1, SimplexHandler.seen
assert posts[0]["path"] == "/send", SimplexHandler.seen
assert posts[0]["body"] == {"recipient": "c-pepper", "text": "hey"}, posts[0]
for seen in SimplexHandler.seen:
assert seen["token"] == SIMPLEX_TOKEN, seen
state = json.loads(result.new_state)
assert state["sent"] is True, state
assert state["contact_id"] == "c-pepper", state
assert state["text"] == "hey", state
finally:
server.shutdown()
server.server_close()
def test_ambiguous_contact_uses_engine():
"""Two named contacts: the body must ask the engine and honour the pick."""
reset()
server = start_server(SimplexHandler)
try:
engine = FakeEngine(selected="c-salt", confidence=0.9)
ctx = ActionContext(
engine=engine,
config={"simplex_bridge_url": base_url(server)},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper and salt saying hi")
)
assert not result.needs_input, result.action_log
assert len(engine.calls) == 1, engine.calls
option_ids = [o.id for o in engine.calls[0].options]
assert set(option_ids) == {"c-pepper", "c-salt"}, option_ids
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert len(posts) == 1, SimplexHandler.seen
assert posts[0]["body"] == {"recipient": "c-salt", "text": "hi"}, posts[0]
finally:
server.shutdown()
server.server_close()
def test_message_written_by_llm_bridge():
"""No literal text: the body must ask the llm bridge, then send its reply."""
reset()
simplex = start_server(SimplexHandler)
llm = start_server(LlmHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={
"simplex_bridge_url": base_url(simplex),
"simplex_bridge_token": SIMPLEX_TOKEN,
"llm_bridge_url": base_url(llm),
"llm_bridge_token": LLM_TOKEN,
},
)
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
assert not result.needs_input, result.action_log
assert len(LlmHandler.seen) == 1, LlmHandler.seen
chat = LlmHandler.seen[0]
assert chat["path"] == "/chat", chat
assert chat["token"] == LLM_TOKEN, chat
assert chat["body"]["messages"], chat
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert len(posts) == 1, SimplexHandler.seen
assert posts[0]["body"] == {"recipient": "c-pepper", "text": LLM_REPLY}, posts[0]
finally:
simplex.shutdown()
simplex.server_close()
llm.shutdown()
llm.server_close()
def test_chained_result_is_sent():
"""As the later step of a chain, no literal text: send the prior step's result."""
reset()
simplex = start_server(SimplexHandler)
llm = start_server(LlmHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={
"simplex_bridge_url": base_url(simplex),
"simplex_bridge_token": SIMPLEX_TOKEN,
"llm_bridge_url": base_url(llm),
},
)
request = FakeRequest(
"send the result of 22 * 10 to pepper on simplex",
run_ledger=[
{
"query": "send the result of 22 * 10 to pepper on simplex",
"skill": "calculator.calculate",
"outcome": "Twenty-two times ten is two hundred twenty.",
}
],
)
result = skill.act(ctx, request)
assert not result.needs_input, result.action_log
# The prior result is used verbatim; the LLM bridge must NOT be asked to
# recompute it.
assert LlmHandler.seen == [], LlmHandler.seen
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert len(posts) == 1, SimplexHandler.seen
assert posts[0]["body"] == {
"recipient": "c-pepper",
"text": "Twenty-two times ten is two hundred twenty.",
}, posts[0]
finally:
simplex.shutdown()
simplex.server_close()
llm.shutdown()
llm.server_close()
def test_missing_text_without_llm_asks():
"""A clear recipient but no message text and no llm bridge: ask the user."""
reset()
server = start_server(SimplexHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={"simplex_bridge_url": base_url(server)},
)
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
assert result.needs_input, result.action_log
assert "say" in result.needs_input.lower(), result.needs_input
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert posts == [], SimplexHandler.seen
finally:
server.shutdown()
server.server_close()
def test_unknown_contact_asks():
"""No matching contact in the bridge list: ask which contact to message."""
reset(contacts=[])
server = start_server(SimplexHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={"simplex_bridge_url": base_url(server)},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper on simplex saying hey")
)
assert result.needs_input, result.action_log
assert "contact" in result.needs_input.lower(), result.needs_input
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert posts == [], SimplexHandler.seen
finally:
server.shutdown()
server.server_close()
def test_send_refused_is_reported():
"""A 400 from POST /send must be surfaced, not silently swallowed."""
reset(send_error=True)
server = start_server(SimplexHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={"simplex_bridge_url": base_url(server)},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper on simplex saying hey")
)
assert not result.needs_input, result.action_log
assert "refused" in result.action_log.lower(), result.action_log
assert "400" in result.action_log, result.action_log
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert len(posts) == 1, SimplexHandler.seen
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_is_reported():
"""A dead bridge must produce a plain failure log, not an exception."""
reset()
server = start_server(SimplexHandler)
url = base_url(server)
server.shutdown()
server.server_close()
ctx = ActionContext(
engine=FakeEngine(),
config={"simplex_bridge_url": url},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper on simplex saying hey")
)
assert not result.needs_input, result.action_log
assert "could not reach" in result.action_log.lower(), result.action_log
def main():
test_happy_path()
test_ambiguous_contact_uses_engine()
test_message_written_by_llm_bridge()
test_chained_result_is_sent()
test_missing_text_without_llm_asks()
test_unknown_contact_asks()
test_send_refused_is_reported()
test_unreachable_bridge_is_reported()
print("ok")
if __name__ == "__main__":
main()