185 lines
9.6 KiB
Python
185 lines
9.6 KiB
Python
"""``commands``: what a live plugin adds to the ``ai-agent`` CLI
|
|
(``ai-agent plugin <id> <command>``) and to the MCP server
|
|
(``plugin_<id>_<command>``) — docs/plugins.md → "Commands (CLI + MCP)"."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import types
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
|
|
"META_PATH": TMP / "meta.json", "USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects", "INTERNAL_API_TOKEN": "tok",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ.setdefault(k, str(v))
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from plugins import commands as plugin_commands # noqa: E402
|
|
from plugins.manifest import ManifestError, capability_fingerprint, capability_summary, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
|
|
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
|
|
ACTIONS = {
|
|
"index": {"script": "a.py", "readOnly": True, "description": "every row"},
|
|
"get": {"script": "a.py", "readOnly": True},
|
|
"set": {"script": "a.py"},
|
|
"wipe": {"script": "a.py", "ownerOnly": True},
|
|
}
|
|
COMMANDS = {
|
|
"ls": {"action": "index", "summary": "Every row",
|
|
"output": {"rows": "rows", "columns": ["slug", "title"]}, "mcp": True},
|
|
"show": {"action": "get", "summary": "One row's text", "description": "The long help.",
|
|
"args": [{"name": "slug", "positional": True, "required": True, "help": "Its slug."},
|
|
{"name": "full", "type": "boolean", "default": False},
|
|
{"name": "limit", "type": "integer", "default": 20},
|
|
{"name": "tags", "type": "array"},
|
|
{"name": "mode", "enum": ["a", "b"]}],
|
|
"output": {"text": "content"}, "mcp": True},
|
|
"set": {"action": "set", "summary": "Change a row", "destructive": True,
|
|
"args": [{"name": "slug", "positional": True, "required": True}]},
|
|
"wipe": {"action": "wipe", "summary": "Owner only", "mcp": True},
|
|
}
|
|
MANIFEST = {"schema": 1, "id": "rows", "name": "Rows", "actions": ACTIONS, "commands": COMMANDS}
|
|
|
|
|
|
def _write(root: pathlib.Path, manifest: dict) -> pathlib.Path:
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
|
|
(root / "a.py").write_text("print('{}')\n", encoding="utf-8")
|
|
return root
|
|
|
|
|
|
def _mf(td: str, manifest: dict, name: str = "p") -> dict:
|
|
return validate_manifest(_write(pathlib.Path(td) / name, manifest))
|
|
|
|
|
|
class TestManifest(unittest.TestCase):
|
|
def test_commands_are_normalized(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
cmds = _mf(td, MANIFEST)["commands"]
|
|
self.assertEqual(list(cmds), ["ls", "show", "set", "wipe"])
|
|
show = cmds["show"]
|
|
self.assertEqual(show["description"], "The long help.")
|
|
args = {a["name"]: a for a in show["args"]}
|
|
self.assertEqual(args["slug"], {"name": "slug", "type": "string", "help": "Its slug.",
|
|
"required": True, "positional": True})
|
|
self.assertEqual((args["full"]["default"], args["limit"]["default"]), (False, 20))
|
|
self.assertEqual(args["mode"]["enum"], ["a", "b"])
|
|
self.assertEqual(cmds["ls"]["output"], {"rows": "rows", "columns": ["slug", "title"]})
|
|
self.assertFalse(cmds["set"]["mcp"])
|
|
self.assertTrue(cmds["set"]["destructive"])
|
|
|
|
def test_a_conversation_arg(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
cmds = _mf(td, {**MANIFEST, "commands": {"add": {
|
|
"action": "index", "summary": "s",
|
|
"args": [{"name": "to", "conversation": True}]}}})["commands"]
|
|
self.assertIs(cmds["add"]["args"][0]["conversation"], True)
|
|
|
|
def test_refusals(self):
|
|
bad = [
|
|
{"x": {"action": "nope", "summary": "s"}},
|
|
{"x": {"action": "index"}},
|
|
{"Bad": {"action": "index", "summary": "s"}},
|
|
{"x": {"action": "index", "summary": "s", "args": [{"name": "json"}]}},
|
|
{"x": {"action": "index", "summary": "s", "args": [{"name": "a"}, {"name": "a"}]}},
|
|
{"x": {"action": "index", "summary": "s", "args": [{"name": "a", "type": "date"}]}},
|
|
{"x": {"action": "index", "summary": "s", "args": [{"name": "a", "type": "boolean",
|
|
"positional": True}]}},
|
|
{"x": {"action": "index", "summary": "s", "args": [
|
|
{"name": "a", "positional": True}, {"name": "b", "positional": True, "required": True}]}},
|
|
{"x": {"action": "index", "summary": "s", "args": [
|
|
{"name": "a", "positional": True, "type": "array"}, {"name": "b", "positional": True}]}},
|
|
{"x": {"action": "index", "summary": "s", "args": [{"name": "a", "type": "integer",
|
|
"default": "1"}]}},
|
|
{"x": {"action": "index", "summary": "s", "args": [{"name": "a", "enum": []}]}},
|
|
{"x": {"action": "index", "summary": "s", "output": {"rows": "r"}}},
|
|
{"x": {"action": "index", "summary": "s", "output": {"html": "x"}}},
|
|
{"a-very-long-command-name-for-mcp": {"action": "index", "summary": "s", "mcp": True}},
|
|
{"x": {"action": "index", "summary": "s", "args": [{"name": "to", "type": "array",
|
|
"conversation": True}]}},
|
|
{"x": {"action": "index", "summary": "s", "args": [{"name": "to", "conversation": "yes"}]}},
|
|
]
|
|
with tempfile.TemporaryDirectory() as td:
|
|
for i, cmds in enumerate(bad):
|
|
with self.subTest(cmds=cmds), self.assertRaises(ManifestError):
|
|
_mf(td, {**MANIFEST, "id": "a-much-longer-plugin-identifier", "commands": cmds}, f"b{i}")
|
|
|
|
def test_a_plugin_named_like_a_core_verb_declares_none(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
with self.assertRaises(ManifestError) as e:
|
|
_mf(td, {**MANIFEST, "id": "install"})
|
|
self.assertIn("core verb", str(e.exception))
|
|
self.assertNotIn("commands", _mf(td, {**MANIFEST, "id": "install", "commands": {}}, "ok"))
|
|
|
|
def test_commands_are_not_a_capability_but_the_consent_card_lists_them(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
a = _mf(td, MANIFEST, "a")
|
|
b = _mf(td, {k: v for k, v in MANIFEST.items() if k != "commands"}, "b")
|
|
self.assertEqual(capability_fingerprint(a), capability_fingerprint(b))
|
|
labels = [c["label"] for c in capability_summary(a) if c["kind"] == "commands"]
|
|
self.assertTrue(any("ai-agent plugin rows" in l and "`show`" in l for l in labels))
|
|
self.assertTrue(any("`plugin_rows_ls`" in l and "`plugin_rows_wipe`" in l
|
|
and "plugin_rows_set" not in l for l in labels))
|
|
self.assertFalse([c for c in capability_summary(b) if c["kind"] == "commands"])
|
|
|
|
|
|
class TestCatalogue(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tc = TestClient(main.app, headers=OWNER_H)
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.store = PluginStore(pathlib.Path(self.td.name) / "data")
|
|
|
|
def tearDown(self):
|
|
self.td.cleanup()
|
|
|
|
def install(self, manifest: dict, name: str = "src"):
|
|
self.store.install(OWNER_UID, str(_write(pathlib.Path(self.td.name) / name, manifest)),
|
|
is_owner=True, approve=True)
|
|
|
|
def test_the_owner_lists_every_command_with_its_tool(self):
|
|
self.install(MANIFEST)
|
|
self.install({"schema": 1, "id": "plain", "name": "Plain", "actions": ACTIONS}, "plain")
|
|
with patch.object(main.app.state.ai, "plugin_store", self.store):
|
|
r = self.tc.get("/api/plugins/commands")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
rows = {c["name"]: c for c in r.json()["commands"]}
|
|
self.assertEqual(set(rows), {"ls", "show", "set", "wipe"})
|
|
self.assertEqual({c["plugin"] for c in rows.values()}, {"rows"})
|
|
self.assertEqual((rows["ls"]["tool"], rows["ls"]["readOnly"]), ("plugin_rows_ls", True))
|
|
self.assertEqual((rows["set"]["tool"], rows["set"]["readOnly"]), (None, False))
|
|
self.assertEqual(rows["show"]["pluginName"], "Rows")
|
|
|
|
def test_a_disabled_plugin_has_no_commands(self):
|
|
self.install(MANIFEST)
|
|
self.store.update(OWNER_UID, "rows", enabled=False)
|
|
deps = types.SimpleNamespace(plugin_store=self.store)
|
|
self.assertEqual(plugin_commands.commands_for(deps, types.SimpleNamespace(is_owner=True, id="owner")), [])
|
|
|
|
def test_a_guest_gets_a_granted_managed_plugins_commands_but_not_owner_only_ones(self):
|
|
self.install({**MANIFEST, "managed": {"defaultForGuests": False}})
|
|
deps = types.SimpleNamespace(plugin_store=self.store)
|
|
dom = types.SimpleNamespace(is_owner=False, id="dom")
|
|
self.assertEqual(plugin_commands.commands_for(deps, dom), [])
|
|
self.store.set_grant("dom", "rows", enabled=True)
|
|
names = {c["name"] for c in plugin_commands.commands_for(deps, dom)}
|
|
self.assertEqual(names, {"ls", "show", "set"})
|
|
|
|
def test_an_owner_plugin_that_isnt_managed_is_never_a_guests(self):
|
|
self.install(MANIFEST)
|
|
deps = types.SimpleNamespace(plugin_store=self.store)
|
|
self.assertEqual(plugin_commands.commands_for(
|
|
deps, types.SimpleNamespace(is_owner=False, id="dom")), [])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|