Abstract seeds into modular skill packs + split config
Group committed starter skills into packs (semif_agent/packs.py) that bind a
concern to its categories, bridge(s), requirements, and config schema:
- seeds/ -> packs/<name>/ with a pack.json manifest + skills/<category>/<leaf>/.
Shipped: nextcloud, simplex, outlook, browser (each owning its bridge) and
essentials (time + calculator, no bridge).
- PackRegistry discovers packs (a root with no manifest is one implicit pack);
merge_packs loads every enabled pack. Pack enable is one switch
(packs.<name>.enabled -> bridges.<bridge>.enabled -> enabled_by_default);
disabling a pack drops its categories (incl. generated bodies) and its bridge.
- CATEGORY_DESCRIPTIONS now comes from the pack manifests (built-ins stay).
Adopt a Home-Assistant-style layered config (semif_agent/config.py):
- config.json is a thin index ({"include": [...]}) over config/core.json,
config/gateway.json, config/bridges.json, config/packs/*.json, deep-merged.
- Secrets live in the gitignored secrets.json, referenced as "!secret <key>";
api_key_env is removed.
- CORE_SCHEMA + each pack's config schema own defaults and GENERATE the
committed config.example.json; new `check-config` (validate + --write-example)
and `config-init` (seed the split layout) commands.
- scripts/config_merge.py (stdlib) lets bootstrap read the merged config.
Tests: tests/test_packs.py (renamed from test_seed_skills, +enable/merge),
new tests/test_config.py. All unit tests pass (772).
This commit is contained in:
commit
7442f5bd5f
29 files changed
+2220
No files matched your search
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"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."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Compose and send an Outlook email, after confirming the message."
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
"""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
|
||||
@@ -0,0 +1,216 @@
|
||||
"""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)
|
||||
Reference in new issue
Block a user