aegis-langchain 1.0.0__tar.gz

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept warranty
167
+ and/or charge a fee for support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Abhishek Mishra
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: aegis-langchain
3
+ Version: 1.0.0
4
+ Summary: LangChain governance middleware for Aegis ACP
5
+ Author: Aegis ACP
6
+ Keywords: ai,governance,langchain,security,aegis
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Topic :: Security
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: httpx>=0.25
15
+ Provides-Extra: langchain
16
+ Requires-Dist: langchain-core>=0.1; extra == "langchain"
17
+ Dynamic: author
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: keywords
22
+ Dynamic: license-file
23
+ Dynamic: provides-extra
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ # aegis-langchain
29
+
30
+ > Drop-in LangChain middleware that routes every tool invocation through Aegis's runtime governance pipeline before execution.
31
+
32
+ [![PyPI](https://img.shields.io/badge/pypi-aegis--langchain-blue)](https://pypi.org/project/aegis-langchain/)
33
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue)]()
34
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green)]()
35
+
36
+ ```bash
37
+ pip install aegis-langchain
38
+ ```
39
+
40
+ ## What it does
41
+
42
+ Wraps a LangChain agent (`AgentExecutor` / `Runnable`) so every tool the agent decides to call is **pre-checked by Aegis** (`POST /execute`) before the tool actually runs. Blocked calls return a descriptive message back to the agent loop; allowed calls pass through unchanged.
43
+
44
+ Aegis decides what to block based on **action semantics** — the `DROP TABLE`, `rm -rf`, `kubectl delete`, external-PII-egress patterns in `services/policy/policies/action_semantics_deny.rego`. The deny is earned from the content of the action, not from a hardcoded "critical" tag on the agent. So a buyer flipping the agent's risk level can't accidentally bypass it.
45
+
46
+ Every check produces a signed audit row in the Aegis chain. Verify any of them offline with `aegis-verify` (the `tools/aegis_verify/` CLI).
47
+
48
+ ## Three-line install
49
+
50
+ ```python
51
+ from aegis_langchain import AegisMiddleware
52
+
53
+ agent = AegisMiddleware(
54
+ my_langchain_agent,
55
+ api_key="acp_...", # or AEGIS_API_KEY env var
56
+ aegis_url="https://ha.aegisagent.in", # or AEGIS_URL env
57
+ tenant_id="00000000-0000-0000-0000-000000000001",
58
+ agent_id="<your-agent-uuid>",
59
+ )
60
+
61
+ result = agent.invoke({"input": "analyze the customer table and clean up old rows"})
62
+ # Each tool invocation is pre-checked. Blocked tools return a message
63
+ # explaining the deny; the agent reasons over it like any other tool
64
+ # observation.
65
+ ```
66
+
67
+ Works with any LangChain agent that uses tools (`AgentExecutor`, structured-chat agents, custom runnables that invoke tools via `tool_call`).
68
+
69
+ ## Fail-closed by default
70
+
71
+ If the Aegis gateway is unreachable, tool invocations return deny with reason `aegis_unreachable_fail_closed`. Letting unchecked calls through because the security plane was down defeats the integration's purpose.
72
+
73
+ ## What you can verify offline
74
+
75
+ After any allowed (or denied) tool call:
76
+
77
+ 1. `GET /receipts/key` — ed25519 PEM
78
+ 2. `GET /compliance/export/eu-ai-act?period_start=…&period_end=…` — signed bundle
79
+ 3. `aegis-verify --bundle bundle.json` — V1–V6 checks pass without any network call back to Aegis
80
+
81
+ ## Requirements
82
+
83
+ - Python 3.10+
84
+ - `langchain-core>=0.1` (auto-pulled with `pip install "aegis-langchain[langchain]"`)
85
+
86
+ ## See also
87
+
88
+ - [aegis-anthropic](https://pypi.org/project/aegis-anthropic/) — same pattern for Anthropic tool_use
89
+ - [aegis-openai](https://pypi.org/project/aegis-openai/) — same pattern for OpenAI tool_calls
90
+ - [Aegis live demo](https://ha.aegisagent.in/live-demo) — three real scenarios across three risk profiles
91
+
92
+ ## License
93
+
94
+ Apache 2.0.
@@ -0,0 +1,67 @@
1
+ # aegis-langchain
2
+
3
+ > Drop-in LangChain middleware that routes every tool invocation through Aegis's runtime governance pipeline before execution.
4
+
5
+ [![PyPI](https://img.shields.io/badge/pypi-aegis--langchain-blue)](https://pypi.org/project/aegis-langchain/)
6
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue)]()
7
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green)]()
8
+
9
+ ```bash
10
+ pip install aegis-langchain
11
+ ```
12
+
13
+ ## What it does
14
+
15
+ Wraps a LangChain agent (`AgentExecutor` / `Runnable`) so every tool the agent decides to call is **pre-checked by Aegis** (`POST /execute`) before the tool actually runs. Blocked calls return a descriptive message back to the agent loop; allowed calls pass through unchanged.
16
+
17
+ Aegis decides what to block based on **action semantics** — the `DROP TABLE`, `rm -rf`, `kubectl delete`, external-PII-egress patterns in `services/policy/policies/action_semantics_deny.rego`. The deny is earned from the content of the action, not from a hardcoded "critical" tag on the agent. So a buyer flipping the agent's risk level can't accidentally bypass it.
18
+
19
+ Every check produces a signed audit row in the Aegis chain. Verify any of them offline with `aegis-verify` (the `tools/aegis_verify/` CLI).
20
+
21
+ ## Three-line install
22
+
23
+ ```python
24
+ from aegis_langchain import AegisMiddleware
25
+
26
+ agent = AegisMiddleware(
27
+ my_langchain_agent,
28
+ api_key="acp_...", # or AEGIS_API_KEY env var
29
+ aegis_url="https://ha.aegisagent.in", # or AEGIS_URL env
30
+ tenant_id="00000000-0000-0000-0000-000000000001",
31
+ agent_id="<your-agent-uuid>",
32
+ )
33
+
34
+ result = agent.invoke({"input": "analyze the customer table and clean up old rows"})
35
+ # Each tool invocation is pre-checked. Blocked tools return a message
36
+ # explaining the deny; the agent reasons over it like any other tool
37
+ # observation.
38
+ ```
39
+
40
+ Works with any LangChain agent that uses tools (`AgentExecutor`, structured-chat agents, custom runnables that invoke tools via `tool_call`).
41
+
42
+ ## Fail-closed by default
43
+
44
+ If the Aegis gateway is unreachable, tool invocations return deny with reason `aegis_unreachable_fail_closed`. Letting unchecked calls through because the security plane was down defeats the integration's purpose.
45
+
46
+ ## What you can verify offline
47
+
48
+ After any allowed (or denied) tool call:
49
+
50
+ 1. `GET /receipts/key` — ed25519 PEM
51
+ 2. `GET /compliance/export/eu-ai-act?period_start=…&period_end=…` — signed bundle
52
+ 3. `aegis-verify --bundle bundle.json` — V1–V6 checks pass without any network call back to Aegis
53
+
54
+ ## Requirements
55
+
56
+ - Python 3.10+
57
+ - `langchain-core>=0.1` (auto-pulled with `pip install "aegis-langchain[langchain]"`)
58
+
59
+ ## See also
60
+
61
+ - [aegis-anthropic](https://pypi.org/project/aegis-anthropic/) — same pattern for Anthropic tool_use
62
+ - [aegis-openai](https://pypi.org/project/aegis-openai/) — same pattern for OpenAI tool_calls
63
+ - [Aegis live demo](https://ha.aegisagent.in/live-demo) — three real scenarios across three risk profiles
64
+
65
+ ## License
66
+
67
+ Apache 2.0.
@@ -0,0 +1,224 @@
1
+ """
2
+ aegis-langchain — LangChain governance middleware for Aegis ACP
3
+ Install: pip install aegis-langchain (or pip install -e integrations/aegis-langchain)
4
+
5
+ Usage:
6
+ from aegis_langchain import AegisMiddleware
7
+
8
+ agent = AegisMiddleware(
9
+ my_langchain_agent,
10
+ api_key="acp_...", # or set AEGIS_API_KEY env var
11
+ tenant_id="...", # or set AEGIS_TENANT_ID env var
12
+ agent_id="...", # optional
13
+ )
14
+ result = agent.invoke({"input": "analyze the /etc/passwd file"})
15
+ # → tool calls are checked by Aegis before execution; blocked = descriptive message
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import functools
20
+ import json
21
+ import os
22
+ from typing import Any
23
+
24
+ import httpx
25
+
26
+ __all__ = ["AegisMiddleware", "AegisCallbackHandler", "AegisClient"]
27
+
28
+
29
+ class AegisClient:
30
+ """Thin synchronous client for the Aegis /execute governance endpoint."""
31
+
32
+ def __init__(
33
+ self,
34
+ api_key: str,
35
+ gateway_url: str = "https://aegisagent.in",
36
+ tenant_id: str = "",
37
+ agent_id: str = "langchain-agent",
38
+ timeout: float = 10.0,
39
+ ) -> None:
40
+ self._url = gateway_url.rstrip("/")
41
+ self._agent_id = agent_id
42
+ self._headers = {
43
+ "Authorization": f"Bearer {api_key}",
44
+ "X-Tenant-ID": tenant_id,
45
+ "X-Agent-ID": agent_id,
46
+ "Content-Type": "application/json",
47
+ }
48
+ self._timeout = timeout
49
+
50
+ def check(self, tool_name: str, parameters: dict[str, Any]) -> dict[str, Any]:
51
+ try:
52
+ with httpx.Client(timeout=self._timeout) as client:
53
+ resp = client.post(
54
+ f"{self._url}/execute",
55
+ headers=self._headers,
56
+ json={
57
+ # Canonical field names — `tool_name`/`parameters`
58
+ # are accepted as a fallback but the audit row gets
59
+ # logged with tool="unknown". Use the right names.
60
+ "agent_id": self._agent_id,
61
+ "tool": tool_name,
62
+ "arguments": parameters,
63
+ },
64
+ )
65
+ if resp.status_code in (200, 403):
66
+ return self._normalize(resp.json())
67
+ # Fail CLOSED on transport / server errors.
68
+ return {
69
+ "action": "deny",
70
+ "risk": 1.0,
71
+ "findings": [f"aegis_http_{resp.status_code}"],
72
+ }
73
+ except Exception as exc:
74
+ return {
75
+ "action": "deny",
76
+ "risk": 1.0,
77
+ "findings": [f"aegis_error:{type(exc).__name__}"],
78
+ }
79
+
80
+ @staticmethod
81
+ def _normalize(body: dict[str, Any]) -> dict[str, Any]:
82
+ """Map every /execute response onto {action, risk, findings}.
83
+
84
+ Plain 200 success → unwrap data envelope. 403 with
85
+ `approval_required` → escalate. 403 with any other error and no
86
+ action field → deny + carry the error string. Anything else with
87
+ success=false → fail-closed deny.
88
+ """
89
+ data = body.get("data") if isinstance(body, dict) else None
90
+ if data is None and isinstance(body, dict) and body.get("action"):
91
+ data = body
92
+ if isinstance(data, dict) and data.get("action"):
93
+ return data
94
+ err = (body.get("error") if isinstance(body, dict) else None) or "denied"
95
+ action = "escalate" if "approval_required" in str(err).lower() else "deny"
96
+ return {"action": action, "risk": 1.0, "findings": [str(err)[:120]]}
97
+
98
+ def is_blocked(self, decision: dict[str, Any]) -> bool:
99
+ return decision.get("action", "deny") in (
100
+ "deny", "block", "policy_deny", "reject", "escalate",
101
+ )
102
+
103
+ def blocked_message(self, tool_name: str, decision: dict[str, Any]) -> str:
104
+ findings = decision.get("findings", ["policy_violation"])
105
+ risk = decision.get("risk", 1.0)
106
+ return f"[BLOCKED by Aegis] Tool '{tool_name}' denied (risk={risk:.3f}): {findings}"
107
+
108
+
109
+ class AegisMiddleware:
110
+ """
111
+ Drop-in governance wrapper for any LangChain AgentExecutor or Runnable.
112
+
113
+ Patches every tool in the agent so each call is checked with Aegis
114
+ before execution. Blocked calls return a descriptive message instead
115
+ of running — the agent sees the block and responds appropriately.
116
+ """
117
+
118
+ def __init__(
119
+ self,
120
+ agent: Any,
121
+ api_key: str | None = None,
122
+ gateway_url: str | None = None,
123
+ tenant_id: str | None = None,
124
+ agent_id: str | None = None,
125
+ timeout: float = 10.0,
126
+ ) -> None:
127
+ self._agent = agent
128
+ self._client = AegisClient(
129
+ api_key=api_key or os.environ["AEGIS_API_KEY"],
130
+ gateway_url=gateway_url or os.environ.get("AEGIS_URL", "https://aegisagent.in"),
131
+ tenant_id=tenant_id or os.environ.get("AEGIS_TENANT_ID", ""),
132
+ agent_id=agent_id or os.environ.get("AEGIS_AGENT_ID", "langchain-agent"),
133
+ timeout=timeout,
134
+ )
135
+ self._patch_tools()
136
+
137
+ def _patch_tools(self) -> None:
138
+ tools = getattr(self._agent, "tools", None)
139
+ if not tools:
140
+ return
141
+ for tool in tools:
142
+ tool._run = self._make_governed_run(tool.name, tool._run)
143
+ if hasattr(tool, "_arun"):
144
+ tool._arun = self._make_governed_arun(tool.name, tool._arun)
145
+
146
+ def _make_governed_run(self, tool_name: str, original_run: Any) -> Any:
147
+ client = self._client
148
+
149
+ @functools.wraps(original_run)
150
+ def governed_run(*args: Any, **kwargs: Any) -> Any:
151
+ params = kwargs if kwargs else ({"args": list(args)} if args else {})
152
+ decision = client.check(tool_name, params)
153
+ if client.is_blocked(decision):
154
+ return client.blocked_message(tool_name, decision)
155
+ return original_run(*args, **kwargs)
156
+
157
+ return governed_run
158
+
159
+ def _make_governed_arun(self, tool_name: str, original_arun: Any) -> Any:
160
+ client = self._client
161
+
162
+ @functools.wraps(original_arun)
163
+ async def governed_arun(*args: Any, **kwargs: Any) -> Any:
164
+ params = kwargs if kwargs else ({"args": list(args)} if args else {})
165
+ decision = client.check(tool_name, params)
166
+ if client.is_blocked(decision):
167
+ return client.blocked_message(tool_name, decision)
168
+ return await original_arun(*args, **kwargs)
169
+
170
+ return governed_arun
171
+
172
+ def invoke(self, *args: Any, **kwargs: Any) -> Any:
173
+ return self._agent.invoke(*args, **kwargs)
174
+
175
+ def stream(self, *args: Any, **kwargs: Any) -> Any:
176
+ return self._agent.stream(*args, **kwargs)
177
+
178
+ async def ainvoke(self, *args: Any, **kwargs: Any) -> Any:
179
+ return await self._agent.ainvoke(*args, **kwargs)
180
+
181
+ async def astream(self, *args: Any, **kwargs: Any) -> Any:
182
+ async for chunk in self._agent.astream(*args, **kwargs):
183
+ yield chunk
184
+
185
+ def __getattr__(self, name: str) -> Any:
186
+ return getattr(self._agent, name)
187
+
188
+
189
+ class AegisCallbackHandler:
190
+ """
191
+ LangChain callback handler for monitor-only mode (no blocking).
192
+ Every tool call is logged to Aegis for observability without enforcement.
193
+
194
+ Usage:
195
+ agent.invoke(input, config={"callbacks": [AegisCallbackHandler(api_key="acp_...")]})
196
+ """
197
+
198
+ def __init__(
199
+ self,
200
+ api_key: str | None = None,
201
+ gateway_url: str | None = None,
202
+ tenant_id: str | None = None,
203
+ agent_id: str | None = None,
204
+ ) -> None:
205
+ self._client = AegisClient(
206
+ api_key=api_key or os.environ["AEGIS_API_KEY"],
207
+ gateway_url=gateway_url or os.environ.get("AEGIS_URL", "https://aegisagent.in"),
208
+ tenant_id=tenant_id or os.environ.get("AEGIS_TENANT_ID", ""),
209
+ agent_id=agent_id or os.environ.get("AEGIS_AGENT_ID", "langchain-agent"),
210
+ )
211
+
212
+ def on_tool_start(self, serialized: dict, input_str: str, **_kwargs: Any) -> None:
213
+ tool_name = serialized.get("name", "unknown")
214
+ try:
215
+ params = json.loads(input_str) if isinstance(input_str, str) else {"input": input_str}
216
+ except Exception:
217
+ params = {"input": str(input_str)}
218
+ self._client.check(tool_name, params)
219
+
220
+ def on_tool_end(self, output: str, **kwargs: Any) -> None:
221
+ pass
222
+
223
+ def on_tool_error(self, error: Exception, **kwargs: Any) -> None:
224
+ pass
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: aegis-langchain
3
+ Version: 1.0.0
4
+ Summary: LangChain governance middleware for Aegis ACP
5
+ Author: Aegis ACP
6
+ Keywords: ai,governance,langchain,security,aegis
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Topic :: Security
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: httpx>=0.25
15
+ Provides-Extra: langchain
16
+ Requires-Dist: langchain-core>=0.1; extra == "langchain"
17
+ Dynamic: author
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: keywords
22
+ Dynamic: license-file
23
+ Dynamic: provides-extra
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ # aegis-langchain
29
+
30
+ > Drop-in LangChain middleware that routes every tool invocation through Aegis's runtime governance pipeline before execution.
31
+
32
+ [![PyPI](https://img.shields.io/badge/pypi-aegis--langchain-blue)](https://pypi.org/project/aegis-langchain/)
33
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue)]()
34
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green)]()
35
+
36
+ ```bash
37
+ pip install aegis-langchain
38
+ ```
39
+
40
+ ## What it does
41
+
42
+ Wraps a LangChain agent (`AgentExecutor` / `Runnable`) so every tool the agent decides to call is **pre-checked by Aegis** (`POST /execute`) before the tool actually runs. Blocked calls return a descriptive message back to the agent loop; allowed calls pass through unchanged.
43
+
44
+ Aegis decides what to block based on **action semantics** — the `DROP TABLE`, `rm -rf`, `kubectl delete`, external-PII-egress patterns in `services/policy/policies/action_semantics_deny.rego`. The deny is earned from the content of the action, not from a hardcoded "critical" tag on the agent. So a buyer flipping the agent's risk level can't accidentally bypass it.
45
+
46
+ Every check produces a signed audit row in the Aegis chain. Verify any of them offline with `aegis-verify` (the `tools/aegis_verify/` CLI).
47
+
48
+ ## Three-line install
49
+
50
+ ```python
51
+ from aegis_langchain import AegisMiddleware
52
+
53
+ agent = AegisMiddleware(
54
+ my_langchain_agent,
55
+ api_key="acp_...", # or AEGIS_API_KEY env var
56
+ aegis_url="https://ha.aegisagent.in", # or AEGIS_URL env
57
+ tenant_id="00000000-0000-0000-0000-000000000001",
58
+ agent_id="<your-agent-uuid>",
59
+ )
60
+
61
+ result = agent.invoke({"input": "analyze the customer table and clean up old rows"})
62
+ # Each tool invocation is pre-checked. Blocked tools return a message
63
+ # explaining the deny; the agent reasons over it like any other tool
64
+ # observation.
65
+ ```
66
+
67
+ Works with any LangChain agent that uses tools (`AgentExecutor`, structured-chat agents, custom runnables that invoke tools via `tool_call`).
68
+
69
+ ## Fail-closed by default
70
+
71
+ If the Aegis gateway is unreachable, tool invocations return deny with reason `aegis_unreachable_fail_closed`. Letting unchecked calls through because the security plane was down defeats the integration's purpose.
72
+
73
+ ## What you can verify offline
74
+
75
+ After any allowed (or denied) tool call:
76
+
77
+ 1. `GET /receipts/key` — ed25519 PEM
78
+ 2. `GET /compliance/export/eu-ai-act?period_start=…&period_end=…` — signed bundle
79
+ 3. `aegis-verify --bundle bundle.json` — V1–V6 checks pass without any network call back to Aegis
80
+
81
+ ## Requirements
82
+
83
+ - Python 3.10+
84
+ - `langchain-core>=0.1` (auto-pulled with `pip install "aegis-langchain[langchain]"`)
85
+
86
+ ## See also
87
+
88
+ - [aegis-anthropic](https://pypi.org/project/aegis-anthropic/) — same pattern for Anthropic tool_use
89
+ - [aegis-openai](https://pypi.org/project/aegis-openai/) — same pattern for OpenAI tool_calls
90
+ - [Aegis live demo](https://ha.aegisagent.in/live-demo) — three real scenarios across three risk profiles
91
+
92
+ ## License
93
+
94
+ Apache 2.0.
@@ -0,0 +1,9 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ aegis_langchain/__init__.py
5
+ aegis_langchain.egg-info/PKG-INFO
6
+ aegis_langchain.egg-info/SOURCES.txt
7
+ aegis_langchain.egg-info/dependency_links.txt
8
+ aegis_langchain.egg-info/requires.txt
9
+ aegis_langchain.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ httpx>=0.25
2
+
3
+ [langchain]
4
+ langchain-core>=0.1
@@ -0,0 +1 @@
1
+ aegis_langchain
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,26 @@
1
+ from pathlib import Path
2
+
3
+ from setuptools import find_packages, setup
4
+
5
+ _here = Path(__file__).parent
6
+ _readme = (_here / "README.md").read_text() if (_here / "README.md").exists() else ""
7
+
8
+ setup(
9
+ name="aegis-langchain",
10
+ version="1.0.0",
11
+ description="LangChain governance middleware for Aegis ACP",
12
+ long_description=_readme,
13
+ long_description_content_type="text/markdown",
14
+ author="Aegis ACP",
15
+ python_requires=">=3.10",
16
+ packages=find_packages(),
17
+ install_requires=["httpx>=0.25"],
18
+ extras_require={"langchain": ["langchain-core>=0.1"]},
19
+ keywords=["ai", "governance", "langchain", "security", "aegis"],
20
+ classifiers=[
21
+ "Development Status :: 4 - Beta",
22
+ "Intended Audience :: Developers",
23
+ "Topic :: Security",
24
+ "Programming Language :: Python :: 3",
25
+ ],
26
+ )