modus-ai 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.
Files changed (71) hide show
  1. modus/__init__.py +3 -0
  2. modus/actions/__init__.py +12 -0
  3. modus/actions/base.py +145 -0
  4. modus/actions/compaction.py +12 -0
  5. modus/actions/local.py +47 -0
  6. modus/actions/mcp/__init__.py +3 -0
  7. modus/actions/mcp/_stdio.py +79 -0
  8. modus/actions/mcp/client.py +103 -0
  9. modus/actions/mcp/transport.py +10 -0
  10. modus/actions/registry.py +63 -0
  11. modus/agent.py +355 -0
  12. modus/cli/__init__.py +3 -0
  13. modus/cli/_memory_cli.py +134 -0
  14. modus/core/__init__.py +4 -0
  15. modus/core/_validate.py +58 -0
  16. modus/core/protocols.py +49 -0
  17. modus/core/types.py +24 -0
  18. modus/deploy/__init__.py +4 -0
  19. modus/deploy/_scheduler.py +116 -0
  20. modus/deploy/_server.py +76 -0
  21. modus/memory/__init__.py +4 -0
  22. modus/memory/_chat.py +77 -0
  23. modus/memory/_memory.py +376 -0
  24. modus/memory/analysis/__init__.py +22 -0
  25. modus/memory/analysis/_analyzer.py +157 -0
  26. modus/memory/analysis/_vector.py +198 -0
  27. modus/memory/analysis/embeddings.py +159 -0
  28. modus/memory/bridges/__init__.py +8 -0
  29. modus/memory/bridges/_bridges.py +93 -0
  30. modus/memory/bridges/_langchain_memory.py +45 -0
  31. modus/memory/search/__init__.py +3 -0
  32. modus/memory/search/_scoring.py +76 -0
  33. modus/memory/storage/__init__.py +4 -0
  34. modus/memory/storage/_fts5.py +108 -0
  35. modus/memory/storage/_store.py +276 -0
  36. modus/orchestration/__init__.py +14 -0
  37. modus/orchestration/_state.py +90 -0
  38. modus/orchestration/_step.py +49 -0
  39. modus/orchestration/_team.py +154 -0
  40. modus/orchestration/_types.py +13 -0
  41. modus/orchestration/_workflow.py +458 -0
  42. modus/planner/__init__.py +4 -0
  43. modus/planner/_planner.py +98 -0
  44. modus/planner/_types.py +24 -0
  45. modus/providers/__init__.py +6 -0
  46. modus/providers/_factory.py +55 -0
  47. modus/providers/anthropic.py +92 -0
  48. modus/providers/gemini.py +187 -0
  49. modus/providers/openai.py +115 -0
  50. modus/safety/__init__.py +4 -0
  51. modus/safety/_interceptor.py +93 -0
  52. modus/safety/_policy.py +17 -0
  53. modus/skills/__init__.py +8 -0
  54. modus/skills/apply.py +90 -0
  55. modus/skills/loader.py +155 -0
  56. modus/skills/registry.py +74 -0
  57. modus/skills/types.py +27 -0
  58. modus/vision/__init__.py +4 -0
  59. modus/vision/_anthropic.py +66 -0
  60. modus/vision/_base.py +9 -0
  61. modus/vision/_gemini.py +42 -0
  62. modus/vision/_image.py +115 -0
  63. modus/vision/_ollama.py +65 -0
  64. modus/vision/_openai.py +53 -0
  65. modus/vision/_tesseract.py +35 -0
  66. modus/vision/_vision.py +89 -0
  67. modus_ai-0.1.0.dist-info/METADATA +169 -0
  68. modus_ai-0.1.0.dist-info/RECORD +71 -0
  69. modus_ai-0.1.0.dist-info/WHEEL +5 -0
  70. modus_ai-0.1.0.dist-info/licenses/LICENSE +21 -0
  71. modus_ai-0.1.0.dist-info/top_level.txt +1 -0
modus/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from modus.agent import Agent
2
+
3
+ __all__ = ["Agent"]
@@ -0,0 +1,12 @@
1
+ from modus.actions.base import Actions
2
+ from modus.actions.local import EchoTool, FunctionTool, tool
3
+ from modus.actions.registry import LocalToolRegistry, ToolRegistry
4
+
5
+ __all__ = [
6
+ "Actions",
7
+ "EchoTool",
8
+ "FunctionTool",
9
+ "LocalToolRegistry",
10
+ "ToolRegistry",
11
+ "tool",
12
+ ]
modus/actions/base.py ADDED
@@ -0,0 +1,145 @@
1
+ import hashlib
2
+ import json
3
+ import logging
4
+ import time
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from modus.actions.compaction import compact_result
9
+ from modus.actions.mcp.client import MCPClientManager
10
+ from modus.actions.registry import ToolRegistry
11
+ from modus.core.protocols import Tool
12
+ from modus.core.types import ToolDefinition
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def _validate_args(parameters: dict[str, Any] | None, args: dict[str, Any]) -> None:
18
+ if not parameters:
19
+ return
20
+ required = parameters.get("required", [])
21
+ missing = [field for field in required if field not in args]
22
+ if missing:
23
+ raise ValueError(f"Missing required arguments: {', '.join(missing)}")
24
+
25
+
26
+ def _normalize_result(result: Any) -> str:
27
+ if isinstance(result, str):
28
+ return result
29
+ return json.dumps(result, default=str)
30
+
31
+
32
+ class Actions:
33
+ def __init__(
34
+ self,
35
+ on_tool_call: Callable[[str, dict[str, Any]], None] | None = None,
36
+ on_approval: Callable[[str, dict[str, Any]], bool] | None = None,
37
+ ) -> None:
38
+ self._registry = ToolRegistry()
39
+ self._mcp = MCPClientManager()
40
+ self._cache: dict[str, dict[str, Any]] = {}
41
+ self._on_tool_call = on_tool_call
42
+ self._on_approval = on_approval
43
+ self._middleware: list[Callable] = []
44
+
45
+ def use(self, middleware_fn: Callable) -> None:
46
+ self._middleware.append(middleware_fn)
47
+
48
+ def register(self, tool: Tool) -> None:
49
+ self._registry.register(tool)
50
+
51
+ def connect(
52
+ self,
53
+ server: str,
54
+ *,
55
+ command: str | None = None,
56
+ args: list[str] | None = None,
57
+ url: str | None = None,
58
+ **kwargs: Any,
59
+ ) -> None:
60
+ self._mcp.connect(
61
+ server,
62
+ command=command,
63
+ args=args,
64
+ url=url,
65
+ **kwargs,
66
+ )
67
+
68
+ def list_tools(self) -> list[ToolDefinition]:
69
+ tools = self._registry.list_tools()
70
+ tools.extend(self._mcp.list_tools())
71
+ return tools
72
+
73
+ def to_openai_schemas(self) -> list[dict[str, Any]]:
74
+ return self._registry.to_openai_schemas()
75
+
76
+ def to_anthropic_schemas(self) -> list[dict[str, Any]]:
77
+ return self._registry.to_anthropic_schemas()
78
+
79
+ def execute(
80
+ self,
81
+ tool_name: str,
82
+ args: dict[str, Any],
83
+ timeout: int = 30,
84
+ retry: int = 2,
85
+ ) -> dict[str, Any]:
86
+ if self._on_tool_call:
87
+ self._on_tool_call(tool_name, args)
88
+
89
+ cache_key = _cache_key(tool_name, args)
90
+ if cache_key in self._cache:
91
+ return self._cache[cache_key]
92
+
93
+ for attempt in range(retry + 1):
94
+ try:
95
+ result = self._execute_once(tool_name, args, timeout)
96
+ self._cache[cache_key] = result
97
+ return result
98
+ except Exception as exc:
99
+ if attempt == retry:
100
+ return {"content": str(exc), "is_error": True}
101
+ time.sleep(0.5 * (attempt + 1))
102
+
103
+ return {"content": "Unexpected error", "is_error": True}
104
+
105
+ def _execute_once(self, tool_name: str, args: dict[str, Any], timeout: int) -> dict[str, Any]:
106
+ if self._registry.has(tool_name):
107
+ tool = self._registry.get(tool_name)
108
+
109
+ # Authorization check
110
+ require_approval = getattr(tool, "require_approval", False)
111
+ if require_approval and self._on_approval is not None:
112
+ approved = self._on_approval(tool_name, args)
113
+ if not approved:
114
+ logger.info("Tool '%s' rejected by approval callback", tool_name)
115
+ return {"content": f"Tool '{tool_name}' execution rejected", "is_error": True}
116
+
117
+ _validate_args(tool.parameters, args)
118
+
119
+ # Middleware chain
120
+ def call():
121
+ return tool.execute(**args)
122
+ for mw in reversed(self._middleware):
123
+ call = mw(call)
124
+ raw = call()
125
+
126
+ content = compact_result(_normalize_result(raw))
127
+ return {"content": content, "is_error": False}
128
+
129
+ if self._mcp.has_tool(tool_name):
130
+ raw = self._mcp.execute(tool_name, args, timeout=timeout)
131
+ content = compact_result(_normalize_result(raw))
132
+ return {"content": content, "is_error": False}
133
+
134
+ return {
135
+ "content": f"Unknown tool: {tool_name}",
136
+ "is_error": True,
137
+ }
138
+
139
+ def clear_cache(self) -> None:
140
+ self._cache.clear()
141
+
142
+
143
+ def _cache_key(tool_name: str, args: dict[str, Any]) -> str:
144
+ raw = f"{tool_name}:{json.dumps(args, sort_keys=True)}"
145
+ return hashlib.sha256(raw.encode()).hexdigest()
@@ -0,0 +1,12 @@
1
+ def compact_result(
2
+ content: str,
3
+ *,
4
+ max_chars: int = 12_000,
5
+ ) -> str:
6
+ """Shrink oversized tool output before returning it to the LLM."""
7
+ if len(content) <= max_chars:
8
+ return content
9
+ truncated = max_chars - 20
10
+ truncated = max(truncated, 0)
11
+ removed = len(content) - truncated
12
+ return f"{content[:truncated]}\n...[truncated {removed} chars]"
modus/actions/local.py ADDED
@@ -0,0 +1,47 @@
1
+ from collections.abc import Callable
2
+ from dataclasses import dataclass, field
3
+ from typing import Any
4
+
5
+
6
+ @dataclass
7
+ class FunctionTool:
8
+ name: str
9
+ description: str
10
+ parameters: dict[str, Any]
11
+ _fn: Callable[..., str] = field(repr=False)
12
+ require_approval: bool = False
13
+
14
+ def execute(self, **kwargs: Any) -> str:
15
+ return self._fn(**kwargs)
16
+
17
+
18
+ def tool(
19
+ name: str,
20
+ description: str,
21
+ parameters: dict[str, Any],
22
+ require_approval: bool = False,
23
+ ) -> Callable[[Callable[..., str]], FunctionTool]:
24
+ def decorator(fn: Callable[..., str]) -> FunctionTool:
25
+ return FunctionTool(
26
+ name=name,
27
+ description=description,
28
+ parameters=parameters,
29
+ require_approval=require_approval,
30
+ _fn=fn,
31
+ )
32
+
33
+ return decorator
34
+
35
+
36
+ class EchoTool:
37
+ name = "echo"
38
+ description = "Echo back the input message"
39
+ parameters = {
40
+ "type": "object",
41
+ "properties": {"message": {"type": "string"}},
42
+ "required": ["message"],
43
+ }
44
+ require_approval = False
45
+
46
+ def execute(self, *, message: str) -> str:
47
+ return message
@@ -0,0 +1,3 @@
1
+ from modus.actions.mcp.client import MCPClientManager
2
+
3
+ __all__ = ["MCPClientManager"]
@@ -0,0 +1,79 @@
1
+ import json
2
+ import logging
3
+ import subprocess
4
+ from typing import Any
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ class MCPStdioServer:
10
+ def __init__(self, command: str, args: list[str] | None = None) -> None:
11
+ self._command = command
12
+ self._args = args or []
13
+ self._process: subprocess.Popen | None = None
14
+
15
+ def start(self) -> None:
16
+ self._process = subprocess.Popen(
17
+ [self._command, *self._args],
18
+ stdin=subprocess.PIPE,
19
+ stdout=subprocess.PIPE,
20
+ stderr=subprocess.PIPE,
21
+ text=True,
22
+ )
23
+
24
+ def send(self, request: dict[str, Any]) -> dict[str, Any]:
25
+ if self._process is None or self._process.stdin is None:
26
+ raise RuntimeError("Server not started")
27
+ line = json.dumps(request) + "\n"
28
+ self._process.stdin.write(line)
29
+ self._process.stdin.flush()
30
+ raw = self._process.stdout.readline() if self._process.stdout else ""
31
+ if not raw:
32
+ raise ConnectionError("MCP server closed connection")
33
+ return json.loads(raw)
34
+
35
+ def close(self) -> None:
36
+ if self._process:
37
+ self._process.terminate()
38
+ self._process.wait(timeout=5)
39
+
40
+ def list_tools(self) -> list[dict[str, Any]]:
41
+ resp = self.send({"jsonrpc": "2.0", "method": "tools/list", "id": 1})
42
+ return resp.get("result", {}).get("tools", [])
43
+
44
+ def call_tool(self, name: str, args: dict[str, Any], timeout: int = 30) -> str:
45
+ if self._process is None or self._process.stdout is None:
46
+ raise RuntimeError("Server not started")
47
+ request = json.dumps({
48
+ "jsonrpc": "2.0",
49
+ "method": "tools/call",
50
+ "params": {"name": name, "arguments": args},
51
+ "id": 2,
52
+ }) + "\n"
53
+ self._process.stdin.write(request)
54
+ self._process.stdin.flush()
55
+ try:
56
+ self._process.stdout.flush()
57
+ except Exception:
58
+ logger.debug("Failed to flush stdout stream")
59
+ raw = self._read_line_with_timeout(timeout)
60
+ if not raw:
61
+ self.close()
62
+ raise TimeoutError(f"Tool '{name}' timed out after {timeout}s")
63
+ resp = json.loads(raw)
64
+ result = resp.get("result", {})
65
+ content = result.get("content", [])
66
+ parts = [c.get("text", "") for c in content if c.get("type") == "text"]
67
+ return "\n".join(parts)
68
+
69
+ def _read_line_with_timeout(self, timeout: int) -> str:
70
+ import select
71
+ if self._process is None or self._process.stdout is None:
72
+ return ""
73
+ import time
74
+ deadline = time.time() + timeout
75
+ while time.time() < deadline:
76
+ r, _, _ = select.select([self._process.stdout], [], [], 1.0)
77
+ if r:
78
+ return self._process.stdout.readline()
79
+ return ""
@@ -0,0 +1,103 @@
1
+ import logging
2
+ from typing import Any
3
+
4
+ from modus.actions.mcp._stdio import MCPStdioServer
5
+ from modus.core.types import ToolDefinition
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ class MCPClientManager:
11
+ def __init__(self) -> None:
12
+ self._servers: dict[str, MCPStdioServer] = {}
13
+ self._tool_routes: dict[str, str] = {}
14
+ self._tool_definitions: dict[str, ToolDefinition] = {}
15
+
16
+ def has_tool(self, name: str) -> bool:
17
+ return name in self._tool_routes
18
+
19
+ def list_tools(self) -> list[ToolDefinition]:
20
+ return list(self._tool_definitions.values())
21
+
22
+ def connect(
23
+ self,
24
+ server: str,
25
+ *,
26
+ command: str | None = None,
27
+ args: list[str] | None = None,
28
+ url: str | None = None,
29
+ **kwargs: Any,
30
+ ) -> None:
31
+ if command is not None:
32
+ self._connect_stdio(server, command, args or [])
33
+ elif url is not None:
34
+ self._connect_http(server, url)
35
+ else:
36
+ raise ValueError("connect() requires either command or url")
37
+
38
+ def _connect_stdio(self, server_name: str, command: str, args: list[str]) -> None:
39
+ mcp_server = MCPStdioServer(command, args)
40
+ try:
41
+ mcp_server.start()
42
+ tools = mcp_server.list_tools()
43
+ except Exception as e:
44
+ mcp_server.close()
45
+ raise ConnectionError(f"Failed to connect to MCP server '{server_name}': {e}") from e
46
+
47
+ self._servers[server_name] = mcp_server
48
+ self._register_tools(server_name, tools)
49
+
50
+ def _connect_http(self, server_name: str, url: str) -> None:
51
+ try:
52
+ import httpx
53
+ resp = httpx.post(f"{url.rstrip('/')}/tools/list", json={"jsonrpc": "2.0", "method": "tools/list", "id": 1}, timeout=10)
54
+ resp.raise_for_status()
55
+ data = resp.json()
56
+ tools = data.get("result", {}).get("tools", [])
57
+ except ImportError:
58
+ raise ImportError("httpx is required for HTTP MCP transport. Install it with: pip install httpx")
59
+ except Exception as e:
60
+ raise ConnectionError(f"Failed to connect to MCP HTTP server '{server_name}' at {url}: {e}") from e
61
+
62
+ self._tool_routes["_http_" + server_name] = server_name
63
+ self._register_tools(server_name, tools)
64
+
65
+ def _register_tools(self, server_name: str, tools: list[dict]) -> None:
66
+ for t in tools:
67
+ name = t["name"]
68
+ self._tool_routes[name] = server_name
69
+ self._tool_definitions[name] = ToolDefinition(
70
+ name=name,
71
+ description=t.get("description", ""),
72
+ parameters=t.get("inputSchema"),
73
+ )
74
+ logger.info("MCP server '%s' registered %d tools", server_name, len(tools))
75
+
76
+ def execute(self, tool_name: str, args: dict[str, Any], timeout: int = 30) -> str:
77
+ if tool_name not in self._tool_routes:
78
+ raise KeyError(f"Unknown MCP tool: {tool_name}")
79
+ server_name = self._tool_routes[tool_name]
80
+ server = self._servers.get(server_name)
81
+ if server is None:
82
+ raise RuntimeError(f"MCP server '{server_name}' is not connected")
83
+ return server.call_tool(tool_name, args, timeout=timeout)
84
+
85
+ def refresh(self) -> int:
86
+ new_count = 0
87
+ for server_name, server in list(self._servers.items()):
88
+ try:
89
+ tools = server.list_tools()
90
+ for t in tools:
91
+ name = t["name"]
92
+ if name not in self._tool_routes:
93
+ self._tool_routes[name] = server_name
94
+ self._tool_definitions[name] = ToolDefinition(
95
+ name=name,
96
+ description=t.get("description", ""),
97
+ parameters=t.get("inputSchema"),
98
+ )
99
+ new_count += 1
100
+ except Exception as e:
101
+ logger.warning("Failed to refresh tools from '%s': %s", server_name, e)
102
+ logger.info("Discovered %d new tools", new_count)
103
+ return new_count
@@ -0,0 +1,10 @@
1
+ from typing import Any, Protocol, runtime_checkable
2
+
3
+
4
+ @runtime_checkable
5
+ class Transport(Protocol):
6
+ async def connect(self) -> None: ...
7
+
8
+ async def close(self) -> None: ...
9
+
10
+ async def send_request(self, method: str, params: dict[str, Any]) -> dict[str, Any]: ...
@@ -0,0 +1,63 @@
1
+ from typing import Any
2
+
3
+ from modus.core.protocols import Tool
4
+ from modus.core.types import ToolDefinition
5
+
6
+
7
+ class ToolRegistry:
8
+ """In-memory index of local (in-process) tools."""
9
+
10
+ def __init__(self) -> None:
11
+ self._tools: dict[str, Tool] = {}
12
+
13
+ def register(self, tool: Tool) -> None:
14
+ if not tool.name:
15
+ raise ValueError("Tool must have a name")
16
+ self._tools[tool.name] = tool
17
+
18
+ def get(self, name: str) -> Tool:
19
+ if name not in self._tools:
20
+ raise KeyError(f"Unknown tool: {name}")
21
+ return self._tools[name]
22
+
23
+ def has(self, name: str) -> bool:
24
+ return name in self._tools
25
+
26
+ def list_tools(self) -> list[ToolDefinition]:
27
+ return [
28
+ ToolDefinition(
29
+ name=tool.name,
30
+ description=tool.description,
31
+ parameters=tool.parameters,
32
+ require_approval=getattr(tool, "require_approval", False),
33
+ )
34
+ for tool in self._tools.values()
35
+ ]
36
+
37
+ def to_openai_schemas(self) -> list[dict[str, Any]]:
38
+ return [
39
+ {
40
+ "type": "function",
41
+ "function": {
42
+ "name": tool.name,
43
+ "description": tool.description,
44
+ "parameters": tool.parameters
45
+ or {"type": "object", "properties": {}},
46
+ },
47
+ }
48
+ for tool in self._tools.values()
49
+ ]
50
+
51
+ def to_anthropic_schemas(self) -> list[dict[str, Any]]:
52
+ return [
53
+ {
54
+ "name": tool.name,
55
+ "description": tool.description,
56
+ "input_schema": tool.parameters
57
+ or {"type": "object", "properties": {}},
58
+ }
59
+ for tool in self._tools.values()
60
+ ]
61
+
62
+
63
+ LocalToolRegistry = ToolRegistry