gamai-plugins 0.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ """Portable GAMA plugins: trust, protean and team."""
2
+ __version__ = "0.2.2"
gamai_plugins/cli.py ADDED
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env python3
2
+ """One CLI for all portable GAMA plugins."""
3
+ import json
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ ROOT = Path(__file__).resolve().parent / "plugins"
9
+ PLUGINS = ("trust", "protean", "team")
10
+
11
+
12
+ def manifest(plugin):
13
+ with open(ROOT / plugin / "plugin.json", encoding="utf-8") as fh:
14
+ return json.load(fh)
15
+
16
+
17
+ def _public_name(plugin, tool_name):
18
+ return tool_name if tool_name.startswith(plugin + "_") else "%s_%s" % (plugin, tool_name)
19
+
20
+
21
+ def tools():
22
+ out = []
23
+ for plugin in PLUGINS:
24
+ m = manifest(plugin)
25
+ for tool in m.get("tools", []):
26
+ out.append({
27
+ "name": _public_name(plugin, tool["name"]),
28
+ "plugin": plugin,
29
+ "tool": tool["name"],
30
+ "description": tool.get("description", ""),
31
+ "inputSchema": tool.get("parameters", {"type": "object"}),
32
+ "timeout_s": tool.get("timeout_s", 90),
33
+ })
34
+ return out
35
+
36
+
37
+ def call(plugin, tool, args, timeout=None):
38
+ if plugin not in PLUGINS:
39
+ return {"ok": False, "err": "unknown plugin %r" % plugin}
40
+ path = ROOT / plugin / "run.py"
41
+ if not path.is_file():
42
+ return {"ok": False, "err": "plugin entrypoint missing"}
43
+ if timeout is None:
44
+ timeout = 90
45
+ for entry in tools():
46
+ if entry["plugin"] == plugin and entry["tool"] == tool:
47
+ timeout = int(entry.get("timeout_s") or 90)
48
+ break
49
+ try:
50
+ p = subprocess.run(
51
+ [sys.executable, str(path), tool],
52
+ input=json.dumps(args, ensure_ascii=False),
53
+ text=True, encoding="utf-8", errors="replace",
54
+ capture_output=True, timeout=timeout,
55
+ cwd=str(ROOT / plugin),
56
+ )
57
+ except subprocess.TimeoutExpired:
58
+ return {"ok": False, "err": "timeout after %ss" % timeout}
59
+ raw = (p.stdout or "").strip().splitlines()
60
+ for line in reversed(raw):
61
+ try:
62
+ return json.loads(line)
63
+ except Exception:
64
+ continue
65
+ return {"ok": False, "err": (p.stderr or p.stdout or "empty output").strip()[:500]}
66
+
67
+
68
+ def _print(obj):
69
+ print(json.dumps(obj, ensure_ascii=False, indent=2))
70
+
71
+
72
+ def main(argv=None):
73
+ argv = list(sys.argv[1:] if argv is None else argv)
74
+ if not argv or argv[0] in ("-h", "--help", "help"):
75
+ print("usage: gamai-plugins list | call <plugin> <tool> [json] | mcp")
76
+ return 0
77
+ cmd = argv[0]
78
+ if cmd == "list":
79
+ _print({"ok": True, "tools": tools()})
80
+ return 0
81
+ if cmd == "call":
82
+ if len(argv) < 3:
83
+ _print({"ok": False, "err": "usage: call <plugin> <tool> [json]"})
84
+ return 2
85
+ plugin, tool = argv[1], argv[2]
86
+ try:
87
+ args = json.loads(argv[3]) if len(argv) > 3 else {}
88
+ except Exception as exc:
89
+ _print({"ok": False, "err": "invalid json: %s" % exc})
90
+ return 2
91
+ if not isinstance(args, dict):
92
+ _print({"ok": False, "err": "arguments must be a JSON object"})
93
+ return 2
94
+ res = call(plugin, tool, args)
95
+ _print(res)
96
+ return 0 if res.get("ok") and res.get("allowed") is not False else 1
97
+ if cmd == "mcp":
98
+ from .mcp import main as mcp_main
99
+ return mcp_main()
100
+ _print({"ok": False, "err": "unknown command %r" % cmd})
101
+ return 2
102
+
103
+
104
+ def _plugin_main(plugin, argv=None):
105
+ argv = list(sys.argv[1:] if argv is None else argv)
106
+ if not argv:
107
+ _print({"ok": False, "err": "usage: gamai-%s <tool> [json]" % plugin})
108
+ return 2
109
+ args = {}
110
+ if len(argv) > 1:
111
+ try:
112
+ args = json.loads(argv[1])
113
+ except Exception as exc:
114
+ _print({"ok": False, "err": "invalid json: %s" % exc})
115
+ return 2
116
+ res = call(plugin, argv[0], args)
117
+ _print(res)
118
+ return 0 if res.get("ok") and res.get("allowed") is not False else 1
119
+
120
+
121
+ def trust_main(argv=None):
122
+ return _plugin_main("trust", argv)
123
+
124
+
125
+ def protean_main(argv=None):
126
+ return _plugin_main("protean", argv)
127
+
128
+
129
+ def team_main(argv=None):
130
+ return _plugin_main("team", argv)
131
+
132
+
133
+ if __name__ == "__main__":
134
+ raise SystemExit(main())
gamai_plugins/mcp.py ADDED
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env python3
2
+ """Minimal stdio MCP server for the portable GAMA plugins (stdlib only)."""
3
+ import json
4
+ import sys
5
+
6
+ from . import __version__
7
+ from .cli import call, tools
8
+
9
+ PROTOCOL = "2024-11-05"
10
+
11
+
12
+ def _tool_list():
13
+ return [{
14
+ "name": t["name"],
15
+ "description": "[%s] %s" % (t["plugin"], t["description"]),
16
+ "inputSchema": t["inputSchema"],
17
+ } for t in tools()]
18
+
19
+
20
+ def _find(name):
21
+ for t in tools():
22
+ if t["name"] == name:
23
+ return t
24
+ return None
25
+
26
+
27
+ def handle(req):
28
+ if not isinstance(req, dict):
29
+ return None
30
+ rid = req.get("id")
31
+ method = req.get("method")
32
+ if method == "initialize":
33
+ return {"jsonrpc": "2.0", "id": rid, "result": {
34
+ "protocolVersion": PROTOCOL,
35
+ "capabilities": {"tools": {}},
36
+ "serverInfo": {"name": "gamai-plugins", "version": __version__},
37
+ }}
38
+ if "id" not in req:
39
+ return None
40
+ if method == "notifications/initialized":
41
+ return None
42
+ if method == "ping":
43
+ return {"jsonrpc": "2.0", "id": rid, "result": {}}
44
+ if method == "tools/list":
45
+ return {"jsonrpc": "2.0", "id": rid, "result": {"tools": _tool_list()}}
46
+ if method == "tools/call":
47
+ params = req.get("params") or {}
48
+ name = params.get("name") or ""
49
+ args = params.get("arguments") or {}
50
+ t = _find(name)
51
+ if t is None:
52
+ return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": "unknown tool %r" % name}}
53
+ res = call(t["plugin"], t["tool"], args, t.get("timeout_s"))
54
+ text = json.dumps(res, ensure_ascii=False, indent=2)
55
+ return {"jsonrpc": "2.0", "id": rid, "result": {
56
+ "content": [{"type": "text", "text": text}],
57
+ "isError": bool(res.get("ok") is False or res.get("allowed") is False),
58
+ }}
59
+ return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": "unknown method %r" % method}}
60
+
61
+
62
+ def main(argv=None):
63
+ argv = list(sys.argv[1:] if argv is None else argv)
64
+ for stream in (sys.stdin, sys.stdout):
65
+ try:
66
+ stream.reconfigure(encoding="utf-8", errors="replace")
67
+ except Exception:
68
+ pass
69
+ if "--selftest" in argv:
70
+ print(json.dumps({"ok": True, "tools": len(tools()), "names": [t["name"] for t in tools()]}, indent=2))
71
+ return 0
72
+ for line in sys.stdin:
73
+ line = line.strip()
74
+ if not line:
75
+ continue
76
+ try:
77
+ req = json.loads(line)
78
+ except Exception:
79
+ continue
80
+ requests = req if isinstance(req, list) else [req]
81
+ for item in requests:
82
+ out = handle(item)
83
+ if out is not None:
84
+ print(json.dumps(out, ensure_ascii=False), flush=True)
85
+ return 0
86
+
87
+
88
+ if __name__ == "__main__":
89
+ raise SystemExit(main())
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "protean",
3
+ "version": "0.2.2",
4
+ "apiVersion": "1",
5
+ "description": "Lease-bound sandbox runner: HMAC-SHA256 leases with TTL, risk-routed substrates (bubblewrap, Docker runc, Docker + seccomp, optional remote gVisor) and JSONL evidence. The lease is an internal consistency/evidence receipt, not caller authorization.",
6
+ "tools": [
7
+ {
8
+ "name": "run",
9
+ "description": "Run a command inside a lease-bound sandbox. risk=low -> bubblewrap with a minimal read-only root and 32 MiB /tmp; medium -> Docker runc (--network=none, cap-drop ALL, read-only, tmpfs /tmp); high -> Docker + seccomp allowlist (or gVisor if available); critical -> denied locally unless remote=true and a remote host is configured. Only the first executable token is checked; shell syntax can run other binaries inside the sandbox. Unknown risk/substrate, invalid or expired lease, TTL overflow, net=true for medium/high/critical, and executables outside the allowlist are denied (fail-closed). Returns rc, clipped stdout/stderr, ms, substrate, genome_hash, lease_id, out_sha256 and evidence path.",
10
+ "parameters": {
11
+ "type": "object",
12
+ "properties": {
13
+ "cmd": {
14
+ "type": "string",
15
+ "description": "Command to execute inside the sandbox (1..4096 chars, no NUL). Only the first executable token is checked against the allowlist."
16
+ },
17
+ "risk": {
18
+ "type": "string",
19
+ "enum": [
20
+ "low",
21
+ "medium",
22
+ "high",
23
+ "critical"
24
+ ],
25
+ "description": "Risk class selects the substrate. critical requires remote=true plus a configured remote host."
26
+ },
27
+ "net": {
28
+ "type": "boolean",
29
+ "description": "Allow network. Default false. Only risk=low supports net=true; medium/high/critical are network-isolated."
30
+ },
31
+ "timeout_s": {
32
+ "type": "integer",
33
+ "minimum": 1,
34
+ "maximum": 45,
35
+ "description": "Execution timeout in seconds (default 20). Lease TTL is derived from it and verified before execution."
36
+ },
37
+ "workdir": {
38
+ "type": [
39
+ "string",
40
+ "null"
41
+ ],
42
+ "description": "Absolute working directory inside the sandbox (default /tmp). Must not contain ..; the directory must exist in the sandbox."
43
+ },
44
+ "remote": {
45
+ "type": "boolean",
46
+ "description": "Only for risk=critical: run on the configured remote host over SSH with gVisor. Denied for lower risks."
47
+ }
48
+ },
49
+ "required": [
50
+ "cmd",
51
+ "risk"
52
+ ],
53
+ "additionalProperties": false
54
+ },
55
+ "command": [
56
+ "python3",
57
+ "run.py",
58
+ "run"
59
+ ],
60
+ "timeout_s": 60,
61
+ "side_effect": "write"
62
+ }
63
+ ]
64
+ }