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,4 @@
|
||||
{
|
||||
"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."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "List the user's OneDrive files, optionally in a named folder."
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,141 @@
|
||||
"""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)
|
||||
Reference in new issue
Block a user