securegent 0.1.0__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.
securegent/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Securegent: identity, permissions and audit for AI agents."""
2
+
3
+ from .guard import AuditLog, Blocked, Guard
4
+ from .identity import AgentRegistry, AuthError
5
+ from .policy import Policy
6
+
7
+ __all__ = ["AgentRegistry", "AuthError", "AuditLog", "Blocked", "Guard", "Policy"]
8
+ __version__ = "0.1.0"
@@ -0,0 +1,91 @@
1
+ """
2
+ Human approvals across processes, through a shared folder.
3
+
4
+ The guard (e.g. inside the MCP proxy) writes a request to <state>/approvals/pending/<id>.json
5
+ and waits. The dashboard lists pending requests and writes the answer to
6
+ <state>/approvals/decided/<id>.json. No answer before the timeout means "deny".
7
+
8
+ Stdlib only, works on Windows/macOS/Linux, and any number of proxies can share one dashboard.
9
+ """
10
+
11
+ import json
12
+ import os
13
+ import time
14
+ import uuid
15
+ from pathlib import Path
16
+
17
+ DEFAULT_STATE_DIR = Path.home() / ".securegent"
18
+
19
+
20
+ def _dirs(state_dir: str | Path) -> tuple[Path, Path]:
21
+ base = Path(state_dir) / "approvals"
22
+ pending, decided = base / "pending", base / "decided"
23
+ pending.mkdir(parents=True, exist_ok=True)
24
+ decided.mkdir(parents=True, exist_ok=True)
25
+ return pending, decided
26
+
27
+
28
+ def _write_atomic(path: Path, data: dict) -> None:
29
+ tmp = path.with_suffix(".tmp")
30
+ tmp.write_text(json.dumps(data, default=str), encoding="utf-8")
31
+ os.replace(tmp, path)
32
+
33
+
34
+ def _valid_id(request_id: str) -> bool:
35
+ return len(request_id) == 32 and all(c in "0123456789abcdef" for c in request_id)
36
+
37
+
38
+ class FileApprover:
39
+ """An approver for Guard(..., approver=FileApprover()) that waits for the dashboard."""
40
+
41
+ def __init__(self, state_dir: str | Path = DEFAULT_STATE_DIR, timeout: float = 120, poll: float = 0.5):
42
+ self.state_dir = Path(state_dir)
43
+ self.timeout = timeout
44
+ self.poll = poll
45
+
46
+ def __call__(self, request: dict) -> bool:
47
+ pending, decided = _dirs(self.state_dir)
48
+ request_id = uuid.uuid4().hex
49
+ now = time.time()
50
+ _write_atomic(pending / f"{request_id}.json",
51
+ {"id": request_id, "created": now, "expires": now + self.timeout, "request": request})
52
+ answer_file = decided / f"{request_id}.json"
53
+ try:
54
+ while time.time() < now + self.timeout:
55
+ if answer_file.exists():
56
+ try:
57
+ answer = json.loads(answer_file.read_text(encoding="utf-8"))
58
+ except (json.JSONDecodeError, OSError):
59
+ time.sleep(self.poll)
60
+ continue
61
+ return answer.get("approved") is True
62
+ time.sleep(self.poll)
63
+ return False # nobody answered in time: deny
64
+ finally:
65
+ (pending / f"{request_id}.json").unlink(missing_ok=True)
66
+ answer_file.unlink(missing_ok=True)
67
+
68
+
69
+ def list_pending(state_dir: str | Path = DEFAULT_STATE_DIR) -> list[dict]:
70
+ pending, _ = _dirs(state_dir)
71
+ items = []
72
+ for f in pending.glob("*.json"):
73
+ try:
74
+ item = json.loads(f.read_text(encoding="utf-8"))
75
+ except (json.JSONDecodeError, OSError):
76
+ continue
77
+ if item.get("expires", 0) < time.time():
78
+ continue
79
+ items.append(item)
80
+ return sorted(items, key=lambda i: i.get("created", 0))
81
+
82
+
83
+ def decide(request_id: str, approved: bool, state_dir: str | Path = DEFAULT_STATE_DIR) -> bool:
84
+ """Answer a pending request. Returns False if it no longer exists."""
85
+ if not _valid_id(request_id):
86
+ return False
87
+ pending, decided = _dirs(state_dir)
88
+ if not (pending / f"{request_id}.json").exists():
89
+ return False
90
+ _write_atomic(decided / f"{request_id}.json", {"approved": bool(approved), "decided": time.time()})
91
+ return True
@@ -0,0 +1,13 @@
1
+ """LLM backends that run a tool-calling agent loop.
2
+
3
+ Each backend exposes run_agent(system, user, tools, handlers, model, max_steps) -> str
4
+ and a DEFAULT_MODEL.
5
+ """
6
+
7
+ import importlib
8
+
9
+
10
+ def get_backend(name: str):
11
+ if name not in ("ollama", "claude"):
12
+ raise ValueError(f"unknown backend '{name}' (choose: ollama, claude)")
13
+ return importlib.import_module(f"{__name__}.{name}")
@@ -0,0 +1,62 @@
1
+ """
2
+ Claude backend: runs an agent loop on the Claude API. Needs `pip install securegent[claude]`
3
+ and an API key (ANTHROPIC_API_KEY).
4
+
5
+ Tools are given in a generic format:
6
+ {"name": str, "description": str, "parameters": <JSON schema>}
7
+ """
8
+
9
+ DEFAULT_MODEL = "claude-opus-5-5"
10
+
11
+
12
+ def run_agent(system: str, user: str, tools: list[dict], handlers: dict,
13
+ model: str = DEFAULT_MODEL, max_steps: int = 15) -> str:
14
+ """Run the tool-calling loop. handlers maps tool name -> fn(**args) -> str."""
15
+ import anthropic
16
+
17
+ client = anthropic.Anthropic()
18
+ api_tools = [{"name": t["name"], "description": t["description"],
19
+ "input_schema": t["parameters"]} for t in tools]
20
+ messages = [{"role": "user", "content": user}]
21
+
22
+ for _ in range(max_steps):
23
+ response = client.beta.messages.create(
24
+ model=model,
25
+ max_tokens=16000,
26
+ system=system,
27
+ tools=api_tools,
28
+ messages=messages,
29
+ betas=["server-side-fallback-2026-07-01"],
30
+ fallbacks="default",
31
+ )
32
+ if response.stop_reason == "refusal":
33
+ return "(model declined the task)"
34
+
35
+ messages.append({"role": "assistant", "content": response.content})
36
+
37
+ if response.stop_reason == "pause_turn":
38
+ continue
39
+ if response.stop_reason != "tool_use":
40
+ return "\n".join(b.text for b in response.content if b.type == "text")
41
+
42
+ results = []
43
+ for block in response.content:
44
+ if block.type != "tool_use":
45
+ continue
46
+ fn = handlers.get(block.name)
47
+ is_error = False
48
+ if fn is None:
49
+ out, is_error = f"Error: unknown tool '{block.name}'", True
50
+ else:
51
+ try:
52
+ out = fn(**block.input)
53
+ except TypeError as e:
54
+ out, is_error = f"Error: bad arguments for {block.name}: {e}", True
55
+ result = {"type": "tool_result", "tool_use_id": block.id, "content": str(out)}
56
+ if is_error:
57
+ result["is_error"] = True
58
+ results.append(result)
59
+ # all results for this turn go back in one user message
60
+ messages.append({"role": "user", "content": results})
61
+
62
+ return "(stopped: reached the step limit)"
@@ -0,0 +1,71 @@
1
+ """
2
+ Free local backend: runs an agent loop against a model served by Ollama
3
+ (http://localhost:11434). No API key, nothing leaves the machine.
4
+
5
+ Uses only the Python standard library.
6
+
7
+ Tools are given in a generic format:
8
+ {"name": str, "description": str, "parameters": <JSON schema>}
9
+ """
10
+
11
+ import json
12
+ import urllib.error
13
+ import urllib.request
14
+
15
+ OLLAMA_URL = "http://localhost:11434/api/chat"
16
+ DEFAULT_MODEL = "qwen2.5:3b"
17
+
18
+
19
+ def _chat(model: str, messages: list, tools: list) -> dict:
20
+ payload = json.dumps({
21
+ "model": model,
22
+ "messages": messages,
23
+ "tools": tools,
24
+ "stream": False,
25
+ "options": {"temperature": 0.2},
26
+ }).encode()
27
+ req = urllib.request.Request(OLLAMA_URL, data=payload,
28
+ headers={"Content-Type": "application/json"})
29
+ with urllib.request.urlopen(req, timeout=600) as resp:
30
+ return json.loads(resp.read())["message"]
31
+
32
+
33
+ def run_agent(system: str, user: str, tools: list[dict], handlers: dict,
34
+ model: str = DEFAULT_MODEL, max_steps: int = 15) -> str:
35
+ """Run the tool-calling loop. handlers maps tool name -> fn(**args) -> str."""
36
+ ollama_tools = [{"type": "function", "function": {
37
+ "name": t["name"], "description": t["description"], "parameters": t["parameters"],
38
+ }} for t in tools]
39
+ messages = [{"role": "system", "content": system}, {"role": "user", "content": user}]
40
+
41
+ for _ in range(max_steps):
42
+ try:
43
+ msg = _chat(model, messages, ollama_tools)
44
+ except urllib.error.URLError:
45
+ raise RuntimeError("Can't reach Ollama at localhost:11434. Open the Ollama app "
46
+ "(or run `ollama serve`) and try again.") from None
47
+ messages.append(msg)
48
+
49
+ calls = msg.get("tool_calls") or []
50
+ if not calls:
51
+ return msg.get("content", "")
52
+
53
+ for call in calls:
54
+ name = call["function"]["name"]
55
+ args = call["function"].get("arguments") or {}
56
+ if isinstance(args, str): # some models send a JSON string
57
+ try:
58
+ args = json.loads(args)
59
+ except json.JSONDecodeError:
60
+ args = {}
61
+ fn = handlers.get(name)
62
+ if fn is None:
63
+ result = f"Error: unknown tool '{name}'"
64
+ else:
65
+ try:
66
+ result = fn(**args)
67
+ except TypeError as e: # model passed wrong/missing arguments
68
+ result = f"Error: bad arguments for {name}: {e}"
69
+ messages.append({"role": "tool", "content": str(result), "tool_name": name})
70
+
71
+ return "(stopped: reached the step limit)"
@@ -0,0 +1,5 @@
1
+ """Securegent local web dashboard: live audit log, approvals, kill switch."""
2
+
3
+ from .server import DashboardState, create_server
4
+
5
+ __all__ = ["DashboardState", "create_server"]
@@ -0,0 +1,58 @@
1
+ """
2
+ Securegent dashboard.
3
+
4
+ python -m securegent.dashboard # then open the printed link
5
+ python -m securegent.dashboard --open # opens your browser too
6
+
7
+ Shows the live audit log, lets you approve/deny actions that need a human (run the
8
+ MCP proxy with --approvals), and has a kill switch that stops every agent tool call.
9
+ """
10
+
11
+ import argparse
12
+ import sys
13
+ import webbrowser
14
+ from pathlib import Path
15
+
16
+ from ..approvals import DEFAULT_STATE_DIR
17
+ from .server import DashboardState, create_server
18
+
19
+
20
+ def main(argv=None) -> int:
21
+ p = argparse.ArgumentParser(prog="python -m securegent.dashboard",
22
+ description="Local web dashboard for Securegent.")
23
+ p.add_argument("--state-dir", default=str(DEFAULT_STATE_DIR),
24
+ help=f"folder shared with the MCP proxy (default: {DEFAULT_STATE_DIR})")
25
+ p.add_argument("--audit", help="audit log to show (default: <state-dir>/audit.jsonl)")
26
+ p.add_argument("--kill-switch", help="kill-switch file (default: <state-dir>/KILL_SWITCH)")
27
+ p.add_argument("--port", type=int, default=8765, help="port on 127.0.0.1 (default: 8765)")
28
+ p.add_argument("--open", action="store_true", help="open the dashboard in your browser")
29
+ args = p.parse_args(argv)
30
+
31
+ state_dir = Path(args.state_dir)
32
+ state = DashboardState(state_dir,
33
+ Path(args.audit) if args.audit else state_dir / "audit.jsonl",
34
+ Path(args.kill_switch) if args.kill_switch else state_dir / "KILL_SWITCH")
35
+ try:
36
+ server, token = create_server(state, args.port)
37
+ except OSError as e:
38
+ print(f"Can't start on port {args.port}: {e}. Try --port 8766.", file=sys.stderr)
39
+ return 1
40
+
41
+ url = f"http://127.0.0.1:{args.port}/#token={token}"
42
+ print("Securegent dashboard running (only reachable from this computer)")
43
+ print(f" Open: {url}")
44
+ print(" The link contains a secret token. Don't share it. Ctrl+C to stop.")
45
+ print(f" Audit log: {state.audit.path}")
46
+ if args.open:
47
+ webbrowser.open(url)
48
+ try:
49
+ server.serve_forever()
50
+ except KeyboardInterrupt:
51
+ print("\nStopped.")
52
+ finally:
53
+ server.server_close()
54
+ return 0
55
+
56
+
57
+ if __name__ == "__main__":
58
+ sys.exit(main())