actentra 0.1.0a0__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 (48) hide show
  1. actentra/__init__.py +84 -0
  2. actentra/adapters/__init__.py +11 -0
  3. actentra/adapters/function_calling.py +195 -0
  4. actentra/adapters/langchain.py +151 -0
  5. actentra/boundary.py +1992 -0
  6. actentra/secrets.py +177 -0
  7. actentra-0.1.0a0.dist-info/METADATA +191 -0
  8. actentra-0.1.0a0.dist-info/RECORD +48 -0
  9. actentra-0.1.0a0.dist-info/WHEEL +5 -0
  10. actentra-0.1.0a0.dist-info/entry_points.txt +2 -0
  11. actentra-0.1.0a0.dist-info/licenses/LICENSE +158 -0
  12. actentra-0.1.0a0.dist-info/top_level.txt +5 -0
  13. actentra_cli/__init__.py +1 -0
  14. actentra_cli/main.py +1856 -0
  15. actentra_core/__init__.py +312 -0
  16. actentra_core/budgets.py +345 -0
  17. actentra_core/canary.py +293 -0
  18. actentra_core/canonicalize.py +332 -0
  19. actentra_core/causal.py +650 -0
  20. actentra_core/checkpoints.py +1262 -0
  21. actentra_core/claims.py +122 -0
  22. actentra_core/context.py +316 -0
  23. actentra_core/coordination.py +249 -0
  24. actentra_core/envelope.py +255 -0
  25. actentra_core/evidence.py +180 -0
  26. actentra_core/handoffs.py +302 -0
  27. actentra_core/identity.py +1907 -0
  28. actentra_core/lifecycle.py +260 -0
  29. actentra_core/observability.py +153 -0
  30. actentra_core/observations.py +624 -0
  31. actentra_core/policy.py +567 -0
  32. actentra_core/receipts.py +4747 -0
  33. actentra_core/reporting.py +416 -0
  34. actentra_core/risk.py +75 -0
  35. actentra_core/verdict.py +63 -0
  36. actentra_core/warrants.py +377 -0
  37. actentra_executors/__init__.py +18 -0
  38. actentra_executors/fs.py +855 -0
  39. actentra_executors/http.py +668 -0
  40. actentra_executors/sqlite.py +432 -0
  41. actentra_executors/verifiers.py +293 -0
  42. actentra_gateway/__init__.py +29 -0
  43. actentra_gateway/console.html +1016 -0
  44. actentra_gateway/demo.py +664 -0
  45. actentra_gateway/http_service.py +2506 -0
  46. actentra_gateway/mcp_proxy.py +365 -0
  47. actentra_gateway/multi_agent_realtime_sim.py +426 -0
  48. actentra_gateway/services.py +3646 -0
actentra/__init__.py ADDED
@@ -0,0 +1,84 @@
1
+ """Actentra Python SDK."""
2
+
3
+ from actentra.adapters import (
4
+ FunctionCallAdapter,
5
+ LangChainToolWrapper,
6
+ ProtectedTool,
7
+ wrap_langchain_tool,
8
+ )
9
+ from actentra.boundary import (
10
+ ActentraError,
11
+ ActionBlockedError,
12
+ ApprovalCallback,
13
+ Boundary,
14
+ CrossingReceipt,
15
+ ExecutionResult,
16
+ PostconditionFailedError,
17
+ cli_approval_prompt,
18
+ path_resource,
19
+ )
20
+ from actentra.secrets import (
21
+ SecretsBroker,
22
+ SecretsError,
23
+ dpapi_protect,
24
+ dpapi_unprotect,
25
+ )
26
+ from actentra_core.canonicalize import CanonicalizationError
27
+ from actentra_core.envelope import ProvenanceItem
28
+ from actentra_core.policy import (
29
+ PolicyPack,
30
+ PolicyValidationError,
31
+ load_policy_file,
32
+ load_policy_yaml,
33
+ )
34
+ from actentra_core.receipts import (
35
+ ReceiptRecord,
36
+ ReceiptStore,
37
+ VerificationResult,
38
+ verify_log,
39
+ )
40
+ from actentra_core.verdict import Decision, Verdict
41
+ from actentra_executors.fs import ExecutorError, LocalFSExecutor, ScopedFSTools
42
+ from actentra_executors.http import ScopedHTTPExecutor, ScopedHTTPTools
43
+ from actentra_executors.sqlite import ScopedSQLiteExecutor, ScopedSQLiteTools
44
+ from actentra_executors.verifiers import WorkspaceFileVerifier
45
+
46
+ __all__ = [
47
+ "ActentraError",
48
+ "ActionBlockedError",
49
+ "ApprovalCallback",
50
+ "Boundary",
51
+ "CanonicalizationError",
52
+ "CrossingReceipt",
53
+ "Decision",
54
+ "ExecutionResult",
55
+ "ExecutorError",
56
+ "FunctionCallAdapter",
57
+ "LangChainToolWrapper",
58
+ "LocalFSExecutor",
59
+ "PolicyPack",
60
+ "PolicyValidationError",
61
+ "PostconditionFailedError",
62
+ "ProtectedTool",
63
+ "ProvenanceItem",
64
+ "ReceiptRecord",
65
+ "ReceiptStore",
66
+ "ScopedFSTools",
67
+ "ScopedHTTPExecutor",
68
+ "ScopedHTTPTools",
69
+ "ScopedSQLiteExecutor",
70
+ "ScopedSQLiteTools",
71
+ "SecretsBroker",
72
+ "SecretsError",
73
+ "VerificationResult",
74
+ "Verdict",
75
+ "WorkspaceFileVerifier",
76
+ "cli_approval_prompt",
77
+ "dpapi_protect",
78
+ "dpapi_unprotect",
79
+ "load_policy_file",
80
+ "load_policy_yaml",
81
+ "path_resource",
82
+ "verify_log",
83
+ "wrap_langchain_tool",
84
+ ]
@@ -0,0 +1,11 @@
1
+ """Actentra agent framework adapters for drop-in tool protection."""
2
+
3
+ from actentra.adapters.function_calling import FunctionCallAdapter, ProtectedTool
4
+ from actentra.adapters.langchain import LangChainToolWrapper, wrap_langchain_tool
5
+
6
+ __all__ = [
7
+ "FunctionCallAdapter",
8
+ "LangChainToolWrapper",
9
+ "ProtectedTool",
10
+ "wrap_langchain_tool",
11
+ ]
@@ -0,0 +1,195 @@
1
+ """OpenAI/Anthropic-style function calling adapter for Actentra."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import json
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ from actentra.boundary import ActionBlockedError, Boundary
12
+ from actentra_core.canonicalize import canonicalize_json
13
+ from actentra_core.envelope import ProvenanceItem
14
+ from actentra_core.identity import CallerContext
15
+
16
+ ResourceFn = Callable[[dict[str, Any]], str]
17
+
18
+
19
+ def _infer_verb_from_name(name: str) -> str:
20
+ n = name.lower()
21
+ if n.startswith(("read", "get", "list", "fetch", "search", "view", "describe")):
22
+ return "read"
23
+ if n.startswith(("delete", "remove", "drop", "destroy", "purge")):
24
+ return "delete"
25
+ if n.startswith(("write", "edit", "create", "update", "set", "save", "insert", "append")):
26
+ return "write"
27
+ if n.startswith(("exec", "run", "bash", "sh", "cmd", "powershell")):
28
+ return "exec"
29
+ if n.startswith(("http", "curl", "post", "webhook", "email")):
30
+ return "network"
31
+ return "other"
32
+
33
+
34
+ def _default_resource_extractor(args: dict[str, Any], fallback_tool: str) -> str:
35
+ for key in ("resource", "path", "file_path", "target_path", "filepath", "url", "endpoint"):
36
+ val = args.get(key)
37
+ if isinstance(val, str) and val.strip():
38
+ if key in ("path", "file_path", "target_path", "filepath") and not val.startswith(
39
+ "path:"
40
+ ):
41
+ return f"path:{val}"
42
+ return val
43
+ return f"tool:{fallback_tool}"
44
+
45
+
46
+ @dataclass(frozen=True, slots=True)
47
+ class ProtectedTool:
48
+ name: str
49
+ fn: Callable[..., Any]
50
+ verb: str
51
+ resource_fn: ResourceFn
52
+ description: str = ""
53
+
54
+
55
+ class FunctionCallAdapter:
56
+ """Intermediary mediating agent tool calls (e.g. OpenAI function-calling format)."""
57
+
58
+ def __init__(
59
+ self,
60
+ boundary: Boundary,
61
+ *,
62
+ raise_on_blocked: bool = False,
63
+ caller_context: CallerContext | None = None,
64
+ ) -> None:
65
+ self._boundary = boundary
66
+ self._raise_on_blocked = raise_on_blocked
67
+ self._caller_context = caller_context
68
+ self._tools: dict[str, ProtectedTool] = {}
69
+
70
+ @property
71
+ def boundary(self) -> Boundary:
72
+ return self._boundary
73
+
74
+ def register_tool(
75
+ self,
76
+ name: str,
77
+ fn: Callable[..., Any],
78
+ *,
79
+ verb: str | None = None,
80
+ resource_fn: ResourceFn | None = None,
81
+ description: str = "",
82
+ ) -> None:
83
+ """Register a Python callable under a tool name."""
84
+ clean_name = name.strip()
85
+ inferred_verb = verb or _infer_verb_from_name(clean_name)
86
+ res_fn = resource_fn or (lambda args: _default_resource_extractor(args, clean_name))
87
+
88
+ self._tools[clean_name] = ProtectedTool(
89
+ name=clean_name,
90
+ fn=fn,
91
+ verb=inferred_verb,
92
+ resource_fn=res_fn,
93
+ description=description,
94
+ )
95
+
96
+ def execute_call(
97
+ self,
98
+ tool_call: dict[str, Any],
99
+ *,
100
+ provenance: list[ProvenanceItem] | tuple[ProvenanceItem, ...] = (),
101
+ user_goal: str | None = None,
102
+ caller_context: CallerContext | None = None,
103
+ idempotency_key: str | None = None,
104
+ ) -> dict[str, Any]:
105
+ """Execute a tool call dict and return an OpenAI-compatible tool response message.
106
+
107
+ Supports both standard OpenAI format:
108
+ {"id": "call_1", "type": "function", "function": {"name": "..", "arguments": "{}"}}
109
+ and direct format:
110
+ {"name": "...", "arguments": {...}}
111
+ """
112
+ call_id = str(tool_call.get("id") or "call_default")
113
+
114
+ # Resolve name & arguments from either format
115
+ fn_part = tool_call.get("function")
116
+ if isinstance(fn_part, dict):
117
+ raw_name = str(fn_part.get("name", ""))
118
+ raw_args = fn_part.get("arguments", {})
119
+ else:
120
+ raw_name = str(tool_call.get("name", ""))
121
+ raw_args = tool_call.get("arguments", {})
122
+
123
+ if isinstance(raw_args, str):
124
+ try:
125
+ args = json.loads(raw_args) if raw_args.strip() else {}
126
+ except json.JSONDecodeError as exc:
127
+ return self._error_response(call_id, f"Invalid JSON in tool arguments: {exc}")
128
+ elif isinstance(raw_args, dict):
129
+ args = dict(raw_args)
130
+ else:
131
+ args = {}
132
+
133
+ tool_obj = self._tools.get(raw_name)
134
+ if tool_obj is None:
135
+ err_msg = f"Tool '{raw_name}' is not registered with Actentra FunctionCallAdapter"
136
+ if self._raise_on_blocked:
137
+ raise KeyError(err_msg)
138
+ return self._error_response(call_id, err_msg)
139
+
140
+ try:
141
+ resource = tool_obj.resource_fn(args)
142
+ except Exception as exc:
143
+ err_msg = f"Failed to compute resource identifier for '{raw_name}': {exc}"
144
+ if self._raise_on_blocked:
145
+ raise
146
+ return self._error_response(call_id, err_msg)
147
+
148
+ effective_ctx = caller_context or self._caller_context
149
+ try:
150
+ result = self._boundary.execute(
151
+ tool=tool_obj.name,
152
+ verb=tool_obj.verb,
153
+ resource=resource,
154
+ params=args,
155
+ fn=lambda _env, _dec: self._invoke_callable(tool_obj.fn, args),
156
+ provenance=provenance,
157
+ user_goal=user_goal,
158
+ caller_context=effective_ctx,
159
+ idempotency_key=idempotency_key,
160
+ )
161
+ content_str = (
162
+ canonicalize_json(result) if isinstance(result, (dict, list)) else str(result)
163
+ )
164
+ return {
165
+ "role": "tool",
166
+ "tool_call_id": call_id,
167
+ "content": content_str,
168
+ "is_error": False,
169
+ }
170
+ except ActionBlockedError as exc:
171
+ if self._raise_on_blocked:
172
+ raise
173
+ return self._error_response(call_id, f"Blocked by Actentra policy: {exc}")
174
+ except Exception as exc:
175
+ if self._raise_on_blocked:
176
+ raise
177
+ return self._error_response(call_id, f"Tool execution failed: {type(exc).__name__}")
178
+
179
+ def _invoke_callable(self, fn: Callable[..., Any], args: dict[str, Any]) -> Any:
180
+ sig = inspect.signature(fn)
181
+ # Check if function takes **kwargs
182
+ has_varkw = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values())
183
+ if has_varkw:
184
+ return fn(**args)
185
+ # Filter to declared params only
186
+ filtered = {k: v for k, v in args.items() if k in sig.parameters}
187
+ return fn(**filtered)
188
+
189
+ def _error_response(self, call_id: str, error_message: str) -> dict[str, Any]:
190
+ return {
191
+ "role": "tool",
192
+ "tool_call_id": call_id,
193
+ "content": json.dumps({"error": error_message}),
194
+ "is_error": True,
195
+ }
@@ -0,0 +1,151 @@
1
+ """LangChain tool adapter for Actentra."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from actentra.adapters.function_calling import _default_resource_extractor, _infer_verb_from_name
9
+ from actentra.boundary import Boundary
10
+ from actentra_core.envelope import ProvenanceItem
11
+ from actentra_core.identity import CallerContext
12
+
13
+ ResourceFn = Callable[[dict[str, Any]], str]
14
+
15
+
16
+ class LangChainToolWrapper:
17
+ """Wraps any LangChain BaseTool, structured tool, or callable with Actentra enforcement."""
18
+
19
+ def __init__(
20
+ self,
21
+ tool: Any,
22
+ boundary: Boundary,
23
+ *,
24
+ tool_name: str | None = None,
25
+ verb: str | None = None,
26
+ resource_fn: ResourceFn | None = None,
27
+ provenance: list[ProvenanceItem] | tuple[ProvenanceItem, ...] = (),
28
+ user_goal: str | None = None,
29
+ caller_context: CallerContext | None = None,
30
+ ) -> None:
31
+ self._underlying = tool
32
+ self._boundary = boundary
33
+ fallback_name = getattr(tool, "__name__", "unnamed_tool")
34
+ resolved_name = tool_name or getattr(tool, "name", fallback_name)
35
+ self.name: str = str(resolved_name)
36
+ desc = getattr(tool, "description", getattr(tool, "__doc__", "") or "")
37
+ self.description: str = str(desc)
38
+ self.verb: str = verb or _infer_verb_from_name(self.name)
39
+ self.resource_fn: ResourceFn = resource_fn or (
40
+ lambda args: _default_resource_extractor(args, self.name)
41
+ )
42
+ self._provenance = tuple(provenance)
43
+ self._user_goal = user_goal
44
+ self._caller_context = caller_context
45
+
46
+ @property
47
+ def underlying(self) -> Any:
48
+ return self._underlying
49
+
50
+ @property
51
+ def boundary(self) -> Boundary:
52
+ return self._boundary
53
+
54
+ def _normalize_args(self, input_val: Any, kwargs: dict[str, Any]) -> dict[str, Any]:
55
+ if isinstance(input_val, dict):
56
+ merged = dict(input_val)
57
+ merged.update(kwargs)
58
+ return merged
59
+ if input_val is not None:
60
+ # Single argument passed (e.g. query string)
61
+ merged = {"input": input_val}
62
+ merged.update(kwargs)
63
+ return merged
64
+ return dict(kwargs)
65
+
66
+ def _execute_underlying(self, input_val: Any, kwargs: dict[str, Any]) -> Any:
67
+ actual_input = kwargs if input_val is None and kwargs else input_val
68
+ # Check if underlying tool has an .invoke() method (standard modern LangChain)
69
+ if hasattr(self._underlying, "invoke") and callable(self._underlying.invoke):
70
+ config = kwargs.get("config") if isinstance(kwargs, dict) else None
71
+ if config is not None:
72
+ return self._underlying.invoke(actual_input, config=config)
73
+ return self._underlying.invoke(actual_input)
74
+ # Check if underlying tool has a .run() method (legacy LangChain)
75
+ if hasattr(self._underlying, "run") and callable(self._underlying.run):
76
+ if input_val is not None and kwargs:
77
+ return self._underlying.run(input_val, **kwargs)
78
+ if input_val is not None:
79
+ return self._underlying.run(input_val)
80
+ return self._underlying.run(**kwargs)
81
+ # Direct callable fallback
82
+ if callable(self._underlying):
83
+ if isinstance(actual_input, dict) and not (input_val and kwargs):
84
+ return self._underlying(**actual_input)
85
+ if input_val is not None:
86
+ return self._underlying(input_val, **kwargs)
87
+ return self._underlying(**kwargs)
88
+ raise TypeError(f"Underlying tool {self._underlying!r} is not callable")
89
+
90
+ def invoke(
91
+ self,
92
+ input: Any = None,
93
+ config: Any = None,
94
+ *,
95
+ caller_context: CallerContext | None = None,
96
+ idempotency_key: str | None = None,
97
+ **kwargs: Any,
98
+ ) -> Any:
99
+ """Mediate LangChain tool invoke() call through Actentra boundary."""
100
+ args_dict = self._normalize_args(input, kwargs)
101
+ resource = self.resource_fn(args_dict)
102
+
103
+ extra_call_kwargs = dict(kwargs)
104
+ if config is not None:
105
+ extra_call_kwargs["config"] = config
106
+
107
+ effective_ctx = caller_context or self._caller_context
108
+ return self._boundary.execute(
109
+ tool=self.name,
110
+ verb=self.verb,
111
+ resource=resource,
112
+ params=args_dict,
113
+ fn=lambda _env, _dec: self._execute_underlying(input, extra_call_kwargs),
114
+ provenance=self._provenance,
115
+ user_goal=self._user_goal,
116
+ caller_context=effective_ctx,
117
+ idempotency_key=idempotency_key,
118
+ )
119
+
120
+ def run(self, *args: Any, **kwargs: Any) -> Any:
121
+ """Mediate LangChain tool run() call through Actentra boundary."""
122
+ first_arg = args[0] if args else None
123
+ return self.invoke(first_arg, **kwargs)
124
+
125
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
126
+ first_arg = args[0] if args else None
127
+ return self.invoke(first_arg, **kwargs)
128
+
129
+
130
+ def wrap_langchain_tool(
131
+ tool: Any,
132
+ boundary: Boundary,
133
+ *,
134
+ tool_name: str | None = None,
135
+ verb: str | None = None,
136
+ resource_fn: ResourceFn | None = None,
137
+ provenance: list[ProvenanceItem] | tuple[ProvenanceItem, ...] = (),
138
+ user_goal: str | None = None,
139
+ caller_context: CallerContext | None = None,
140
+ ) -> LangChainToolWrapper:
141
+ """Convenience helper to wrap a LangChain tool with an Actentra Boundary."""
142
+ return LangChainToolWrapper(
143
+ tool=tool,
144
+ boundary=boundary,
145
+ tool_name=tool_name,
146
+ verb=verb,
147
+ resource_fn=resource_fn,
148
+ provenance=provenance,
149
+ user_goal=user_goal,
150
+ caller_context=caller_context,
151
+ )