backend/ship/ (store, service, routes), /api/ship/* (authz + golden matrix), DEPS.deploy_hosts, the guard's ship-deploy catch (_SHIP / ship()) and the guest prompt's hardcoded ship-deploy line are gone: the managed ship plugin (ai-agent-plugins) decides who deploys where and its skill supplies the instructions. carryover.ship copies /data/deploy-hosts.json into the plugin's shared dir once (then ….migrated). GUARD_SHIP_TIMEOUT_S becomes GUARD_BROKER_TIMEOUT_S — the ai-agent CLI broker still needs it. Kept: sidecar/ship.py (the ship.run bridge's /ship/deploy), deploycmd.py, DeployWidget / DeployGizmo, the ship project level. openapi.json is not re-dumped here (the coordinator does it after Batch 1). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
384 lines
19 KiB
Python
384 lines
19 KiB
Python
"""Tests for Stage 1 plugin primitives:
|
|
* plugin-to-plugin dependencies (requires, exports, emits, plugin:<dep>:<event>);
|
|
* cross-plugin action calls and call-depth cap;
|
|
* declarative agents[] + default+override prefs + user.modelFamilies clamping;
|
|
* clarifier carryover migration;
|
|
* additive provides: composer.shortcuts.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import types
|
|
import unittest
|
|
|
|
BACKEND = pathlib.Path(__file__).resolve().parent
|
|
if str(BACKEND) not in sys.path:
|
|
sys.path.insert(0, str(BACKEND))
|
|
|
|
_TMP = tempfile.TemporaryDirectory()
|
|
_DATA = pathlib.Path(_TMP.name)
|
|
os.environ.setdefault("DB_PATH", str(_DATA / "ai-agent.db"))
|
|
os.environ.setdefault("TRANSCRIPTS_DIR", str(_DATA / "transcripts"))
|
|
os.environ.setdefault("WORKSPACE", str(_DATA / "workspace"))
|
|
os.environ.setdefault("REPO_DIR", str(_DATA / "workspace"))
|
|
os.environ.setdefault("PLUGINS_DIR", str(_DATA / "plugins"))
|
|
os.environ.setdefault("UI_STATE_PATH", str(_DATA / "ui-state.json"))
|
|
os.environ.setdefault("USERS_PATH", str(_DATA / "users.json"))
|
|
os.environ.setdefault("AUTH_PATH", str(_DATA / "auth.json"))
|
|
os.environ.setdefault("TOOLS_TOKEN_KEY", str(_DATA / "tools.key"))
|
|
os.environ.setdefault("INTERNAL_API_TOKEN", "tok") # OWNER_H: the owner on /api/*
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
import main # noqa: E402
|
|
from plugins import agents as plugin_agents # noqa: E402
|
|
from plugins import carryover # noqa: E402
|
|
from plugins import shortcuts as plugin_shortcuts # noqa: E402
|
|
from plugins.manifest import ManifestError, capability_fingerprint, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, DependencyError, PluginStore # noqa: E402
|
|
from toolproxy import access # noqa: E402
|
|
|
|
OWNER_H = {"X-Internal-Auth": os.environ.get("INTERNAL_API_TOKEN", "")}
|
|
|
|
|
|
def _write_plugin(root: pathlib.Path, mf: dict, files: dict[str, str] | None = None) -> pathlib.Path:
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(mf, indent=2), encoding="utf-8")
|
|
for rel, content in (files or {}).items():
|
|
p = root / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
p.write_text(content, encoding="utf-8")
|
|
return root
|
|
|
|
|
|
class ManifestDepsTest(unittest.TestCase):
|
|
def test_requires_exports_emits_and_plugin_events(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
d = pathlib.Path(td)
|
|
# Self-require refused
|
|
_write_plugin(d / "self", {
|
|
"schema": 1, "id": "self", "name": "Self", "requires": ["self"],
|
|
})
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(d / "self")
|
|
|
|
# Undeclared export refused
|
|
_write_plugin(d / "badexp", {
|
|
"schema": 1, "id": "badexp", "name": "Bad", "exports": ["missing"],
|
|
})
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(d / "badexp")
|
|
|
|
# Plugin event without matching require refused
|
|
_write_plugin(d / "badev", {
|
|
"schema": 1, "id": "badev", "name": "BadEv",
|
|
"actions": {"on": {"script": "h.py"}},
|
|
"events": [{"id": "e1", "on": ["plugin:ask-form:form.submitted"], "action": "on"}],
|
|
}, {"h.py": "print('{}')\n"})
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(d / "badev")
|
|
|
|
# Valid consumer plugin
|
|
_write_plugin(d / "ok", {
|
|
"schema": 1, "id": "ok", "name": "Ok",
|
|
"requires": ["ask-form"],
|
|
"actions": {"on": {"script": "h.py"}},
|
|
"events": [{"id": "e1", "on": ["plugin:ask-form:form.submitted"], "action": "on"}],
|
|
}, {"h.py": "print('{}')\n"})
|
|
mf = validate_manifest(d / "ok")
|
|
self.assertEqual(mf["requires"], ["ask-form"])
|
|
self.assertEqual(mf["events"][0]["on"], ["plugin:ask-form:form.submitted"])
|
|
|
|
def test_fingerprint_unchanged_without_new_keys(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
d = pathlib.Path(td)
|
|
_write_plugin(d / "plain", {"schema": 1, "id": "plain", "name": "Plain"})
|
|
mf = validate_manifest(d / "plain")
|
|
self.assertNotIn("requires", mf)
|
|
self.assertNotIn("exports", mf)
|
|
self.assertNotIn("emits", mf)
|
|
self.assertNotIn("agents", mf)
|
|
fp1 = capability_fingerprint(mf)
|
|
# Adding requires changes fingerprint
|
|
mf2 = {**mf, "requires": ["ask-form"]}
|
|
self.assertNotEqual(fp1, capability_fingerprint(mf2))
|
|
|
|
|
|
class StoreDepsAndCrossCallsTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.root = pathlib.Path(self.td.name)
|
|
self.deps = main.app.state.ai
|
|
self.orig_store = self.deps.plugin_store
|
|
self.store = PluginStore(self.root / "plugins-data")
|
|
self.deps.plugin_store = self.store
|
|
plugin_shortcuts.invalidate()
|
|
self.client = TestClient(main.app)
|
|
|
|
def tearDown(self):
|
|
self.deps.plugin_store = self.orig_store
|
|
plugin_shortcuts.invalidate()
|
|
self.td.cleanup()
|
|
|
|
def test_install_disable_uninstall_dependency_guards(self):
|
|
base = _write_plugin(self.root / "base", {
|
|
"schema": 1, "id": "base", "name": "Base",
|
|
"actions": {
|
|
"echo": {"script": "echo.py"},
|
|
"secret_act": {"script": "echo.py"},
|
|
},
|
|
"exports": ["echo"],
|
|
"emits": ["ping"],
|
|
}, {"echo.py": "import json, os, sys; p=json.load(sys.stdin); u=json.loads(os.environ['AIA_USER_CONTEXT']); print(json.dumps({'echo': p, 'caller': u.get('callerPlugin'), 'depth': int(os.environ.get('AIA_PLUGIN_CALL_DEPTH','0'))}))\n"})
|
|
|
|
consumer = _write_plugin(self.root / "consumer", {
|
|
"schema": 1, "id": "consumer", "name": "Consumer",
|
|
"requires": ["base"],
|
|
"actions": {"on_ping": {"script": "on_ping.py"}},
|
|
"events": [{"id": "e", "on": ["plugin:base:ping"], "action": "on_ping"}],
|
|
}, {"on_ping.py": "import json, os, pathlib, sys; p=json.load(sys.stdin); (pathlib.Path(os.environ['AIA_PLUGIN_DATA_DIR'])/'got.json').write_text(json.dumps(p)); print('{\"ok\":true}')\n"})
|
|
|
|
# Installing consumer before base fails with DependencyError (409 via route)
|
|
with self.assertRaises(DependencyError) as cm:
|
|
self.store.install(OWNER_UID, str(consumer), is_owner=True)
|
|
self.assertEqual(cm.exception.missing, ["base"])
|
|
|
|
self.store.install(OWNER_UID, str(base), is_owner=True)
|
|
self.store.install(OWNER_UID, str(consumer), is_owner=True)
|
|
|
|
# Cannot disable or uninstall base while consumer is enabled
|
|
with self.assertRaises(DependencyError) as cm2:
|
|
self.store.update(OWNER_UID, "base", enabled=False)
|
|
self.assertEqual(cm2.exception.dependents, ["consumer"])
|
|
with self.assertRaises(DependencyError):
|
|
self.store.uninstall(OWNER_UID, "base")
|
|
|
|
# Cross-plugin call: consumer handler token -> base exported action succeeds
|
|
tok = access.mint_handler(OWNER_UID, "consumer", ttl=300)
|
|
r = self.client.post("/proxy/tools/plugins/base/actions/echo",
|
|
json={"x": 42}, headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json(), {"echo": {"x": 42}, "caller": "consumer", "depth": 1})
|
|
|
|
# Unexported action refused
|
|
r2 = self.client.post("/proxy/tools/plugins/base/actions/secret_act",
|
|
json={}, headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r2.status_code, 403)
|
|
|
|
# Exceeding call depth refused with 508
|
|
r3 = self.client.post("/proxy/tools/plugins/base/actions/echo",
|
|
json={}, headers={"Authorization": f"Bearer {tok}", "X-Plugin-Call-Depth": "4"})
|
|
self.assertEqual(r3.status_code, 508)
|
|
|
|
# Emitting plugin event invokes consumer action handler
|
|
base_tok = access.mint_handler(OWNER_UID, "base", ttl=300)
|
|
r4 = self.client.post("/proxy/tools/plugins/base/hub/emit",
|
|
json={"event": "ping", "payload": {"hello": "world"}},
|
|
headers={"Authorization": f"Bearer {base_tok}"})
|
|
self.assertEqual(r4.status_code, 200, r4.text)
|
|
got_file = self.store.user_data_dir(OWNER_UID, "consumer") / "got.json"
|
|
deadline = time.time() + 5.0
|
|
while not got_file.is_file() and time.time() < deadline:
|
|
time.sleep(0.05)
|
|
self.assertTrue(got_file.is_file(), "dependent plugin event handler did not fire")
|
|
ev = json.loads(got_file.read_text())
|
|
self.assertEqual(ev["event"], "plugin:base:ping")
|
|
self.assertEqual(ev["source"], "base")
|
|
self.assertEqual(ev["data"], {"hello": "world"})
|
|
|
|
# Disabling consumer lets base be disabled
|
|
self.store.update(OWNER_UID, "consumer", enabled=False)
|
|
self.store.update(OWNER_UID, "base", enabled=False)
|
|
|
|
def test_declarative_agents_default_override_and_model_clamping(self):
|
|
clar = _write_plugin(self.root / "clarifier", {
|
|
"schema": 1, "id": "clarifier", "name": "Clarifier",
|
|
"managed": {"defaultForGuests": True},
|
|
"ui": {
|
|
"prefs": [
|
|
{"key": "enabled", "type": "switch", "label": "Enabled", "default": True, "scope": "default+override"},
|
|
{"key": "model", "type": "select", "label": "Model", "default": "haiku",
|
|
"optionsFrom": "user.modelFamilies", "scope": "default+override"},
|
|
{"key": "effort", "type": "select", "label": "Effort", "default": "medium",
|
|
"options": ["inherit", "low", "medium", "high"], "scope": "default+override"},
|
|
],
|
|
},
|
|
"agents": [{
|
|
"name": "clarifier",
|
|
"description": "Ask forms",
|
|
"promptFile": "prompts/clarifier.md",
|
|
"tools": ["Bash", "Read"],
|
|
"omitClaudeMd": True,
|
|
"enabledPref": "enabled",
|
|
"modelPref": "model",
|
|
"effortPref": "effort",
|
|
}],
|
|
}, {"prompts/clarifier.md": "You are the clarifier."})
|
|
self.store.install(OWNER_UID, str(clar), is_owner=True)
|
|
|
|
# Seed owner default = opus / high
|
|
self.deps.ui_state.set("ai-agent-settings", json.dumps({
|
|
"state": {"pluginPrefs": {"clarifier": {"enabled": True, "model": "opus", "effort": "high"}}},
|
|
"version": 6,
|
|
}))
|
|
owner_agents = plugin_agents.agent_definitions_for(self.deps, None)
|
|
self.assertEqual(owner_agents["clarifier"]["model"], "opus")
|
|
self.assertEqual(owner_agents["clarifier"]["effort"], "high")
|
|
self.assertTrue(owner_agents["clarifier"]["omitClaudeMd"])
|
|
|
|
# Guest allowed only sonnet: owner default opus clamps to sonnet
|
|
fake_deps = types.SimpleNamespace(
|
|
plugin_store=self.store,
|
|
ui_state=self.deps.ui_state,
|
|
users=types.SimpleNamespace(get=lambda u: {"id": u, "models": ["claude-sonnet-5-5"]}),
|
|
)
|
|
guest_agents = plugin_agents.agent_definitions_for(fake_deps, "alice")
|
|
self.assertEqual(guest_agents["clarifier"]["model"], "sonnet")
|
|
self.assertEqual(guest_agents["clarifier"]["effort"], "high")
|
|
|
|
# Guest overrides enabled=False -> agent omitted
|
|
self.deps.ui_state.set("u.alice.ai-agent-settings", json.dumps({
|
|
"state": {"pluginPrefs": {"clarifier": {"enabled": False}}},
|
|
"version": 6,
|
|
}))
|
|
self.assertEqual(plugin_agents.agent_definitions_for(fake_deps, "alice"), {})
|
|
|
|
def test_clarifier_carryover(self):
|
|
legacy = self.root / "clarifier.json"
|
|
legacy.write_text(json.dumps({"enabled": True, "model": "sonnet", "effort": "low"}))
|
|
self.deps.ui_state.delete("ai-agent-settings")
|
|
moved = carryover.clarifier(self.deps.ui_state, None, legacy=str(legacy))
|
|
self.assertTrue(moved)
|
|
self.assertFalse(legacy.exists())
|
|
self.assertTrue((self.root / "clarifier.json.migrated").is_file())
|
|
self.assertEqual(plugin_agents.owner_prefs(self.deps, "clarifier"),
|
|
{"enabled": True, "model": "sonnet", "effort": "low"})
|
|
|
|
def test_approvals_carryover(self):
|
|
legacy = self.root / "approvals.json"
|
|
data = {"requests": {"apr_1": {"id": "apr_1", "status": "done", "key": "k"}},
|
|
"rules": {"rul_1": {"id": "rul_1", "requester": "alice", "key": "k"}}}
|
|
legacy.write_text(json.dumps(data))
|
|
dst = self.store.shared_data_dir("approvals") / "approvals.json"
|
|
self.assertTrue(carryover.approvals(self.store, legacy=str(legacy)))
|
|
self.assertEqual(json.loads(dst.read_text()), data)
|
|
self.assertFalse(legacy.exists())
|
|
self.assertTrue((self.root / "approvals.json.migrated").is_file())
|
|
# a no-op once done
|
|
self.assertFalse(carryover.approvals(self.store, legacy=str(legacy)))
|
|
# never overwrites what the plugin already holds
|
|
legacy.write_text(json.dumps({"requests": {}, "rules": {}}))
|
|
self.assertTrue(carryover.approvals(self.store, legacy=str(legacy)))
|
|
self.assertEqual(json.loads(dst.read_text()), data)
|
|
|
|
def test_ship_carryover(self):
|
|
legacy = self.root / "deploy-hosts.json"
|
|
data = {"projects": {"blog": ["blog.dev.gabvdl.xyz"]}, "seeded": True}
|
|
legacy.write_text(json.dumps(data))
|
|
dst = self.store.shared_data_dir("ship") / "deploy-hosts.json"
|
|
self.assertTrue(carryover.ship(self.store, legacy=str(legacy)))
|
|
self.assertEqual(json.loads(dst.read_text()), data)
|
|
self.assertFalse(legacy.exists())
|
|
self.assertTrue((self.root / "deploy-hosts.json.migrated").is_file())
|
|
self.assertFalse(carryover.ship(self.store, legacy=str(legacy)))
|
|
# never overwrites what the plugin already holds
|
|
legacy.write_text(json.dumps({"projects": {}, "seeded": False}))
|
|
self.assertTrue(carryover.ship(self.store, legacy=str(legacy)))
|
|
self.assertEqual(json.loads(dst.read_text()), data)
|
|
|
|
def test_run_exit_dispatches_conversation_finished(self):
|
|
from unittest import mock
|
|
from runs import sidecar_client
|
|
sid = "11111111-2222-3333-4444-555555555555"
|
|
fake = types.SimpleNamespace(
|
|
meta_store=types.SimpleNamespace(get=lambda s: {"state": "running"},
|
|
update=lambda s, p: None),
|
|
hub=types.SimpleNamespace(publish=lambda e: None))
|
|
with mock.patch("plugins.scheduler.dispatch_event") as disp:
|
|
sidecar_client._mark_run_exited(fake, sid)
|
|
disp.assert_called_once()
|
|
args, kw = disp.call_args
|
|
self.assertEqual(args[1], "conversation.finished")
|
|
self.assertEqual(args[2]["sessionId"], sid)
|
|
self.assertEqual(kw["owner_uid"], OWNER_UID)
|
|
|
|
def test_read_only_actions_answer_a_get(self):
|
|
plug = _write_plugin(self.root / "ro", {
|
|
"schema": 1, "id": "ro", "name": "RO",
|
|
"actions": {"list": {"script": "echo.py", "readOnly": True},
|
|
"write": {"script": "echo.py"}},
|
|
}, {"echo.py": "import json, sys; print(json.dumps({'echo': json.load(sys.stdin)}))\n"})
|
|
self.store.install(OWNER_UID, str(plug), is_owner=True)
|
|
acts = self.store.get_raw(OWNER_UID, "ro")["manifest"]["actions"]
|
|
self.assertTrue(acts["list"]["readOnly"])
|
|
self.assertNotIn("readOnly", acts["write"])
|
|
r = self.client.get("/api/plugins/ro/actions/list", headers=OWNER_H, params={"payload": json.dumps({"q": 1})})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json(), {"echo": {"q": 1}})
|
|
self.assertEqual(self.client.get("/api/plugins/ro/actions/list", headers=OWNER_H).json(), {"echo": {}})
|
|
# only a readOnly action answers a GET; a bad payload is refused
|
|
self.assertEqual(self.client.get("/api/plugins/ro/actions/write", headers=OWNER_H).status_code, 405)
|
|
self.assertEqual(self.client.get("/api/plugins/ro/actions/list", headers=OWNER_H,
|
|
params={"payload": "[1]"}).status_code, 400)
|
|
self.assertEqual(self.client.get("/api/plugins/ro/actions/list", headers=OWNER_H,
|
|
params={"payload": "{"}).status_code, 400)
|
|
# POST is unchanged, for both
|
|
self.assertEqual(self.client.post("/api/plugins/ro/actions/write", json={"a": 2}, headers=OWNER_H).json(),
|
|
{"echo": {"a": 2}})
|
|
|
|
def test_run_start_dispatches_conversation_started(self):
|
|
from unittest import mock
|
|
from runs import service as run_service
|
|
sid = "11111111-2222-3333-4444-555555555555"
|
|
prompt = "Implement the plan `data/plans/x.md` — X.\n\n" + "y" * 9000
|
|
with mock.patch("plugins.scheduler.dispatch_event") as disp:
|
|
run_service._dispatch_started(types.SimpleNamespace(), sid, prompt, ["homelab"],
|
|
None, {"origin": "app"})
|
|
disp.assert_called_once()
|
|
args, kw = disp.call_args
|
|
self.assertEqual(args[1], "conversation.started")
|
|
ev = args[2]
|
|
self.assertEqual((ev["sessionId"], ev["projects"], ev["worker"], ev["owner"], ev["origin"]),
|
|
(sid, ["homelab"], "local", OWNER_UID, "app"))
|
|
self.assertTrue(ev["prompt"].startswith("Implement the plan `data/plans/x.md`"))
|
|
self.assertEqual(len(ev["prompt"]), 4000)
|
|
self.assertEqual(kw["owner_uid"], OWNER_UID)
|
|
# a plugin's failure never holds a launch up
|
|
with mock.patch("plugins.scheduler.dispatch_event", side_effect=RuntimeError("boom")):
|
|
run_service._dispatch_started(types.SimpleNamespace(), sid, "p", [], "mac",
|
|
{"owner": "dom"})
|
|
|
|
def test_conversation_row_names_its_machine(self):
|
|
from plugins import proxyroutes
|
|
self.assertEqual(proxyroutes._conv_row("x.jsonl", {"sessionId": "s"}, {})["worker"], "local")
|
|
self.assertEqual(proxyroutes._conv_row("x.jsonl", {"sessionId": "s"},
|
|
{"worker": "orus-mac"})["worker"], "orus-mac")
|
|
|
|
def test_new_project_carryover_reads_the_retired_permission_raw(self):
|
|
self.assertTrue(carryover._had_create_projects({"allow": ["cli.use", "projects.create"]}))
|
|
self.assertTrue(carryover._had_create_projects({"createProjects": True}))
|
|
self.assertFalse(carryover._had_create_projects({"allow": ["cli.use"]}))
|
|
self.assertFalse(carryover._had_create_projects({}))
|
|
|
|
def test_composer_shortcuts_provider(self):
|
|
sc_plug = _write_plugin(self.root / "scplug", {
|
|
"schema": 1, "id": "scplug", "name": "SC",
|
|
"actions": {"chips": {"script": "chips.py"}},
|
|
"provides": {"composer.shortcuts": "chips"},
|
|
}, {"chips.py": 'import json; print(json.dumps({"shortcuts": [{"id": "demo-chip", "label": "Demo", "icon": "Sparkles", "guideline": "Do demo.", "defaultOn": True}]}))\n'})
|
|
self.store.install(OWNER_UID, str(sc_plug), is_owner=True)
|
|
owner = types.SimpleNamespace(is_owner=True, id="owner")
|
|
got = plugin_shortcuts.shortcuts_for(self.deps, owner)
|
|
self.assertEqual(len(got), 1)
|
|
self.assertEqual(got[0]["id"], "demo-chip")
|
|
self.assertEqual(got[0]["pluginId"], "scplug")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|