rungated 0.10.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.
- rungated-0.10.0/.gitignore +18 -0
- rungated-0.10.0/LICENSE +177 -0
- rungated-0.10.0/NOTICE +4 -0
- rungated-0.10.0/PKG-INFO +59 -0
- rungated-0.10.0/README.md +21 -0
- rungated-0.10.0/pyproject.toml +39 -0
- rungated-0.10.0/rungated/__init__.py +20 -0
- rungated-0.10.0/rungated/client.py +326 -0
- rungated-0.10.0/rungated/errors.py +40 -0
- rungated-0.10.0/rungated/guard.py +111 -0
- rungated-0.10.0/rungated/integrations/__init__.py +0 -0
- rungated-0.10.0/rungated/integrations/langgraph.py +83 -0
- rungated-0.10.0/rungated/integrations/openai_agents.py +50 -0
- rungated-0.10.0/rungated/py.typed +0 -0
- rungated-0.10.0/rungated/types.py +55 -0
- rungated-0.10.0/tests/__init__.py +0 -0
- rungated-0.10.0/tests/conftest.py +86 -0
- rungated-0.10.0/tests/fake_upstream.py +108 -0
- rungated-0.10.0/tests/test_client.py +167 -0
- rungated-0.10.0/tests/test_integrations.py +106 -0
- rungated-0.10.0/tests/test_llm.py +53 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
bin/
|
|
2
|
+
*.test
|
|
3
|
+
*.out
|
|
4
|
+
/data/
|
|
5
|
+
node_modules/
|
|
6
|
+
console/.next/
|
|
7
|
+
console/out/
|
|
8
|
+
console/next-env.d.ts
|
|
9
|
+
*.tsbuildinfo
|
|
10
|
+
.venv/
|
|
11
|
+
__pycache__/
|
|
12
|
+
.pytest_cache/
|
|
13
|
+
*.egg-info/
|
|
14
|
+
sdk/typescript/dist/
|
|
15
|
+
site-public/
|
|
16
|
+
site-internal/
|
|
17
|
+
sdk/python/dist/
|
|
18
|
+
sdk/python/build/
|
rungated-0.10.0/LICENSE
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
rungated-0.10.0/NOTICE
ADDED
rungated-0.10.0/PKG-INFO
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: rungated
|
|
3
|
+
Version: 0.10.0
|
|
4
|
+
Summary: Python SDK for the Rungated runtime AI agent firewall
|
|
5
|
+
Project-URL: Homepage, https://rungated.com
|
|
6
|
+
Project-URL: Documentation, https://docs.rungated.com
|
|
7
|
+
Author: Rungated
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
License-File: NOTICE
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Security
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Requires-Dist: httpx>=0.25
|
|
17
|
+
Provides-Extra: anthropic
|
|
18
|
+
Requires-Dist: anthropic>=0.40; extra == 'anthropic'
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: anthropic; extra == 'dev'
|
|
21
|
+
Requires-Dist: langchain-core; extra == 'dev'
|
|
22
|
+
Requires-Dist: langgraph; extra == 'dev'
|
|
23
|
+
Requires-Dist: openai; extra == 'dev'
|
|
24
|
+
Requires-Dist: openai-agents; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
27
|
+
Requires-Dist: pyyaml; extra == 'dev'
|
|
28
|
+
Provides-Extra: langgraph
|
|
29
|
+
Requires-Dist: langchain-core>=0.3; extra == 'langgraph'
|
|
30
|
+
Requires-Dist: langgraph>=0.2; extra == 'langgraph'
|
|
31
|
+
Provides-Extra: openai
|
|
32
|
+
Requires-Dist: openai>=1.40; extra == 'openai'
|
|
33
|
+
Provides-Extra: openai-agents
|
|
34
|
+
Requires-Dist: openai-agents>=0.1; extra == 'openai-agents'
|
|
35
|
+
Provides-Extra: yaml
|
|
36
|
+
Requires-Dist: pyyaml>=6; extra == 'yaml'
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# rungated
|
|
40
|
+
|
|
41
|
+
Python SDK for the Rungated runtime AI agent firewall.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from rungated import Rungated, protect
|
|
45
|
+
|
|
46
|
+
ab = Rungated(gateway="http://127.0.0.1:8080", agent_id="finance-agent", agent_key="...")
|
|
47
|
+
|
|
48
|
+
client = ab.openai()
|
|
49
|
+
reply = client.chat.completions.create(model="gpt-4o", messages=[{"role": "user", "content": "hi"}])
|
|
50
|
+
|
|
51
|
+
@protect(ab, name="get_invoice", server="finance-mcp")
|
|
52
|
+
def get_invoice(invoice_id: str) -> dict: ...
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Every function has an async twin prefixed with `a` (`adecide`, `acheck_tool`, `acheck_result`, `ascan`, `arestore`).
|
|
56
|
+
|
|
57
|
+
Adapters live in `rungated.integrations`: `langgraph` (`RungatedToolNode`, `protect_tools`) and `openai_agents` (`protect_function_tools`, `use_gateway`).
|
|
58
|
+
|
|
59
|
+
Environment variables: RUNGATED_GATEWAY, RUNGATED_AGENT, RUNGATED_AGENT_KEY, RUNGATED_TOKEN, RUNGATED_API_KEY, RUNGATED_SESSION.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# rungated
|
|
2
|
+
|
|
3
|
+
Python SDK for the Rungated runtime AI agent firewall.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from rungated import Rungated, protect
|
|
7
|
+
|
|
8
|
+
ab = Rungated(gateway="http://127.0.0.1:8080", agent_id="finance-agent", agent_key="...")
|
|
9
|
+
|
|
10
|
+
client = ab.openai()
|
|
11
|
+
reply = client.chat.completions.create(model="gpt-4o", messages=[{"role": "user", "content": "hi"}])
|
|
12
|
+
|
|
13
|
+
@protect(ab, name="get_invoice", server="finance-mcp")
|
|
14
|
+
def get_invoice(invoice_id: str) -> dict: ...
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Every function has an async twin prefixed with `a` (`adecide`, `acheck_tool`, `acheck_result`, `ascan`, `arestore`).
|
|
18
|
+
|
|
19
|
+
Adapters live in `rungated.integrations`: `langgraph` (`RungatedToolNode`, `protect_tools`) and `openai_agents` (`protect_function_tools`, `use_gateway`).
|
|
20
|
+
|
|
21
|
+
Environment variables: RUNGATED_GATEWAY, RUNGATED_AGENT, RUNGATED_AGENT_KEY, RUNGATED_TOKEN, RUNGATED_API_KEY, RUNGATED_SESSION.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "rungated"
|
|
7
|
+
version = "0.10.0"
|
|
8
|
+
description = "Python SDK for the Rungated runtime AI agent firewall"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{ name = "Rungated" }]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"License :: OSI Approved :: Apache Software License",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Security",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
dependencies = ["httpx>=0.25"]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://rungated.com"
|
|
24
|
+
Documentation = "https://docs.rungated.com"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
openai = ["openai>=1.40"]
|
|
28
|
+
anthropic = ["anthropic>=0.40"]
|
|
29
|
+
langgraph = ["langgraph>=0.2", "langchain-core>=0.3"]
|
|
30
|
+
openai-agents = ["openai-agents>=0.1"]
|
|
31
|
+
yaml = ["pyyaml>=6"]
|
|
32
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.23", "openai", "anthropic", "langgraph", "langchain-core", "openai-agents", "pyyaml"]
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["rungated"]
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
asyncio_mode = "auto"
|
|
39
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from .client import Rungated, collect_strings, replace_strings
|
|
2
|
+
from .errors import ActionBlocked, AgentContained, RungatedError, ApprovalDenied, GatewayError
|
|
3
|
+
from .guard import protect
|
|
4
|
+
from .types import Decision
|
|
5
|
+
|
|
6
|
+
__version__ = "0.10.0"
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Rungated",
|
|
10
|
+
"Decision",
|
|
11
|
+
"protect",
|
|
12
|
+
"ActionBlocked",
|
|
13
|
+
"AgentContained",
|
|
14
|
+
"ApprovalDenied",
|
|
15
|
+
"RungatedError",
|
|
16
|
+
"GatewayError",
|
|
17
|
+
"collect_strings",
|
|
18
|
+
"replace_strings",
|
|
19
|
+
"__version__",
|
|
20
|
+
]
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import copy
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any, Dict, List, Mapping, Optional
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from .errors import ActionBlocked, AgentContained, RungatedError, ApprovalDenied, GatewayError
|
|
11
|
+
from .types import Decision
|
|
12
|
+
|
|
13
|
+
DEFAULT_GATEWAY = "http://127.0.0.1:8080"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _env(name: str) -> Optional[str]:
|
|
17
|
+
v = os.environ.get(name)
|
|
18
|
+
return v if v else None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def collect_strings(obj: Any, path: tuple = ()) -> List[tuple]:
|
|
22
|
+
out: List[tuple] = []
|
|
23
|
+
if isinstance(obj, str):
|
|
24
|
+
out.append((path, obj))
|
|
25
|
+
elif isinstance(obj, Mapping):
|
|
26
|
+
for k, v in obj.items():
|
|
27
|
+
out.extend(collect_strings(v, path + (k,)))
|
|
28
|
+
elif isinstance(obj, (list, tuple)):
|
|
29
|
+
for i, v in enumerate(obj):
|
|
30
|
+
out.extend(collect_strings(v, path + (i,)))
|
|
31
|
+
return out
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def replace_strings(obj: Any, replacements: List[str], strings: List[tuple]) -> Any:
|
|
35
|
+
if not strings:
|
|
36
|
+
return obj
|
|
37
|
+
if strings[0][0] == ():
|
|
38
|
+
return replacements[0]
|
|
39
|
+
root = copy.deepcopy(obj)
|
|
40
|
+
for (path, _), new in zip(strings, replacements):
|
|
41
|
+
cur = root
|
|
42
|
+
for key in path[:-1]:
|
|
43
|
+
cur = cur[key]
|
|
44
|
+
last = path[-1]
|
|
45
|
+
if isinstance(cur, tuple):
|
|
46
|
+
continue
|
|
47
|
+
cur[last] = new
|
|
48
|
+
return root
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Rungated:
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
gateway: Optional[str] = None,
|
|
55
|
+
agent_id: Optional[str] = None,
|
|
56
|
+
agent_key: Optional[str] = None,
|
|
57
|
+
token: Optional[str] = None,
|
|
58
|
+
api_key: Optional[str] = None,
|
|
59
|
+
session_id: Optional[str] = None,
|
|
60
|
+
timeout: float = 30.0,
|
|
61
|
+
hold_timeout: float = 600.0,
|
|
62
|
+
fail_open: bool = False,
|
|
63
|
+
wait: bool = True,
|
|
64
|
+
transport: Optional[httpx.BaseTransport] = None,
|
|
65
|
+
):
|
|
66
|
+
self.gateway = (gateway or _env("RUNGATED_GATEWAY") or DEFAULT_GATEWAY).rstrip("/")
|
|
67
|
+
self.agent_id = agent_id or _env("RUNGATED_AGENT")
|
|
68
|
+
self.agent_key = agent_key or _env("RUNGATED_AGENT_KEY")
|
|
69
|
+
self.token = token or _env("RUNGATED_TOKEN")
|
|
70
|
+
self.api_key = api_key or _env("RUNGATED_API_KEY")
|
|
71
|
+
self.session_id = session_id or _env("RUNGATED_SESSION")
|
|
72
|
+
self.timeout = timeout
|
|
73
|
+
self.hold_timeout = hold_timeout
|
|
74
|
+
self.fail_open = fail_open
|
|
75
|
+
self.wait = wait
|
|
76
|
+
self._transport = transport
|
|
77
|
+
self._http: Optional[httpx.Client] = None
|
|
78
|
+
self._ahttp: Dict[int, httpx.AsyncClient] = {}
|
|
79
|
+
|
|
80
|
+
def with_session(self, session_id: str) -> "Rungated":
|
|
81
|
+
c = copy.copy(self)
|
|
82
|
+
c.session_id = session_id
|
|
83
|
+
c._http = None
|
|
84
|
+
c._ahttp = {}
|
|
85
|
+
return c
|
|
86
|
+
|
|
87
|
+
def headers(self) -> Dict[str, str]:
|
|
88
|
+
h: Dict[str, str] = {}
|
|
89
|
+
if self.token:
|
|
90
|
+
h["X-Rungated-Token"] = self.token
|
|
91
|
+
else:
|
|
92
|
+
if self.agent_id:
|
|
93
|
+
h["X-Rungated-Agent"] = self.agent_id
|
|
94
|
+
if self.agent_key:
|
|
95
|
+
h["X-Rungated-Key"] = self.agent_key
|
|
96
|
+
if self.api_key:
|
|
97
|
+
h["Authorization"] = "Bearer " + self.api_key
|
|
98
|
+
if self.session_id:
|
|
99
|
+
h["X-Rungated-Session"] = self.session_id
|
|
100
|
+
return h
|
|
101
|
+
|
|
102
|
+
def llm_url(self, provider: str) -> str:
|
|
103
|
+
if provider == "openai":
|
|
104
|
+
return self.gateway + "/llm/openai/v1"
|
|
105
|
+
if provider == "anthropic":
|
|
106
|
+
return self.gateway + "/llm/anthropic"
|
|
107
|
+
raise ValueError("provider must be openai or anthropic")
|
|
108
|
+
|
|
109
|
+
def llm_kwargs(self, provider: str) -> Dict[str, Any]:
|
|
110
|
+
return {"base_url": self.llm_url(provider), "default_headers": self.headers()}
|
|
111
|
+
|
|
112
|
+
def _client(self) -> httpx.Client:
|
|
113
|
+
if self._http is None:
|
|
114
|
+
self._http = httpx.Client(timeout=httpx.Timeout(self.timeout, read=max(self.timeout, self.hold_timeout)), transport=self._transport)
|
|
115
|
+
return self._http
|
|
116
|
+
|
|
117
|
+
def _aclient(self) -> httpx.AsyncClient:
|
|
118
|
+
loop = asyncio.get_running_loop()
|
|
119
|
+
key = id(loop)
|
|
120
|
+
c = self._ahttp.get(key)
|
|
121
|
+
if c is None or c.is_closed:
|
|
122
|
+
c = httpx.AsyncClient(timeout=httpx.Timeout(self.timeout, read=max(self.timeout, self.hold_timeout)))
|
|
123
|
+
self._ahttp[key] = c
|
|
124
|
+
return c
|
|
125
|
+
|
|
126
|
+
def close(self) -> None:
|
|
127
|
+
if self._http is not None:
|
|
128
|
+
self._http.close()
|
|
129
|
+
self._http = None
|
|
130
|
+
|
|
131
|
+
async def aclose(self) -> None:
|
|
132
|
+
loop = asyncio.get_running_loop()
|
|
133
|
+
c = self._ahttp.pop(id(loop), None)
|
|
134
|
+
if c is not None:
|
|
135
|
+
await c.aclose()
|
|
136
|
+
|
|
137
|
+
def __enter__(self) -> "Rungated":
|
|
138
|
+
return self
|
|
139
|
+
|
|
140
|
+
def __exit__(self, *exc: Any) -> None:
|
|
141
|
+
self.close()
|
|
142
|
+
|
|
143
|
+
async def __aenter__(self) -> "Rungated":
|
|
144
|
+
return self
|
|
145
|
+
|
|
146
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
147
|
+
await self.aclose()
|
|
148
|
+
|
|
149
|
+
@staticmethod
|
|
150
|
+
def _payload(kind: str, **kw: Any) -> Dict[str, Any]:
|
|
151
|
+
body: Dict[str, Any] = {"kind": kind}
|
|
152
|
+
for k, v in kw.items():
|
|
153
|
+
if v is not None and v != "" and v != {}:
|
|
154
|
+
body[k] = v
|
|
155
|
+
return body
|
|
156
|
+
|
|
157
|
+
def _decide_body(self, kind: str, kw: Dict[str, Any]) -> Dict[str, Any]:
|
|
158
|
+
body = self._payload(kind, **kw)
|
|
159
|
+
if self.agent_id and "agent_id" not in body:
|
|
160
|
+
body["agent_id"] = self.agent_id
|
|
161
|
+
if self.session_id and "session_id" not in body:
|
|
162
|
+
body["session_id"] = self.session_id
|
|
163
|
+
return body
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _raise_for(resp: httpx.Response) -> Any:
|
|
167
|
+
try:
|
|
168
|
+
data = resp.json()
|
|
169
|
+
except ValueError:
|
|
170
|
+
data = resp.text
|
|
171
|
+
if resp.status_code >= 400:
|
|
172
|
+
msg = data.get("error") if isinstance(data, dict) else None
|
|
173
|
+
raise GatewayError(msg or "gateway returned HTTP %d" % resp.status_code, resp.status_code, data)
|
|
174
|
+
return data
|
|
175
|
+
|
|
176
|
+
def _open(self, exc: Exception) -> Decision:
|
|
177
|
+
if self.fail_open:
|
|
178
|
+
return Decision.open_allow("gateway unreachable, failing open: %s" % exc)
|
|
179
|
+
raise GatewayError("gateway unreachable: %s" % exc) from exc
|
|
180
|
+
|
|
181
|
+
def decide(self, kind: str, **kw: Any) -> Decision:
|
|
182
|
+
wait = kw.pop("wait", self.wait)
|
|
183
|
+
body = self._decide_body(kind, kw)
|
|
184
|
+
try:
|
|
185
|
+
resp = self._client().post(self.gateway + "/v1/decide", json=body, params={"wait": "true"} if wait else None, headers=self.headers())
|
|
186
|
+
except httpx.TransportError as e:
|
|
187
|
+
return self._open(e)
|
|
188
|
+
return Decision.from_json(self._raise_for(resp))
|
|
189
|
+
|
|
190
|
+
async def adecide(self, kind: str, **kw: Any) -> Decision:
|
|
191
|
+
wait = kw.pop("wait", self.wait)
|
|
192
|
+
body = self._decide_body(kind, kw)
|
|
193
|
+
try:
|
|
194
|
+
resp = await self._aclient().post(self.gateway + "/v1/decide", json=body, params={"wait": "true"} if wait else None, headers=self.headers())
|
|
195
|
+
except httpx.TransportError as e:
|
|
196
|
+
return self._open(e)
|
|
197
|
+
return Decision.from_json(self._raise_for(resp))
|
|
198
|
+
|
|
199
|
+
@staticmethod
|
|
200
|
+
def _enforce(d: Decision) -> Decision:
|
|
201
|
+
if d.allowed:
|
|
202
|
+
return d
|
|
203
|
+
if d.verdict == "contain":
|
|
204
|
+
raise AgentContained(d)
|
|
205
|
+
if d.verdict == "hold":
|
|
206
|
+
raise ApprovalDenied(d)
|
|
207
|
+
raise ActionBlocked(d)
|
|
208
|
+
|
|
209
|
+
def check_tool(self, tool: str, args: Optional[Dict[str, Any]] = None, server: Optional[str] = None, method: Optional[str] = None, enforce: bool = False, **kw: Any) -> Decision:
|
|
210
|
+
d = self.decide("tool.call", tool=tool, args=args, server=server, method=method, **kw)
|
|
211
|
+
return self._enforce(d) if enforce else d
|
|
212
|
+
|
|
213
|
+
async def acheck_tool(self, tool: str, args: Optional[Dict[str, Any]] = None, server: Optional[str] = None, method: Optional[str] = None, enforce: bool = False, **kw: Any) -> Decision:
|
|
214
|
+
d = await self.adecide("tool.call", tool=tool, args=args, server=server, method=method, **kw)
|
|
215
|
+
return self._enforce(d) if enforce else d
|
|
216
|
+
|
|
217
|
+
def check_result(self, tool: str, result: Any, enforce: bool = False, server: Optional[str] = None) -> tuple:
|
|
218
|
+
strings = collect_strings(result)
|
|
219
|
+
if not strings:
|
|
220
|
+
return Decision.open_allow("no text in result"), result
|
|
221
|
+
texts = [{"source": "tool_result", "text": s, "path": ".".join(str(p) for p in path)} for path, s in strings]
|
|
222
|
+
d = self.decide("tool.result", tool=tool, server=server, texts=texts)
|
|
223
|
+
if enforce:
|
|
224
|
+
self._enforce(d)
|
|
225
|
+
return d, self._apply(d, result, strings)
|
|
226
|
+
|
|
227
|
+
async def acheck_result(self, tool: str, result: Any, enforce: bool = False, server: Optional[str] = None) -> tuple:
|
|
228
|
+
strings = collect_strings(result)
|
|
229
|
+
if not strings:
|
|
230
|
+
return Decision.open_allow("no text in result"), result
|
|
231
|
+
texts = [{"source": "tool_result", "text": s, "path": ".".join(str(p) for p in path)} for path, s in strings]
|
|
232
|
+
d = await self.adecide("tool.result", tool=tool, server=server, texts=texts)
|
|
233
|
+
if enforce:
|
|
234
|
+
self._enforce(d)
|
|
235
|
+
return d, self._apply(d, result, strings)
|
|
236
|
+
|
|
237
|
+
@staticmethod
|
|
238
|
+
def _apply(d: Decision, result: Any, strings: List[tuple]) -> Any:
|
|
239
|
+
if d.allowed and d.redacted_texts and len(d.redacted_texts) == len(strings):
|
|
240
|
+
return replace_strings(result, d.redacted_texts, strings)
|
|
241
|
+
return result
|
|
242
|
+
|
|
243
|
+
def scan(self, text: str, source: str = "user", kind: str = "llm.request", enforce: bool = False, **kw: Any) -> Decision:
|
|
244
|
+
d = self.decide(kind, texts=[{"source": source, "text": text}], **kw)
|
|
245
|
+
return self._enforce(d) if enforce else d
|
|
246
|
+
|
|
247
|
+
async def ascan(self, text: str, source: str = "user", kind: str = "llm.request", enforce: bool = False, **kw: Any) -> Decision:
|
|
248
|
+
d = await self.adecide(kind, texts=[{"source": source, "text": text}], **kw)
|
|
249
|
+
return self._enforce(d) if enforce else d
|
|
250
|
+
|
|
251
|
+
def restore(self, value: Any) -> Any:
|
|
252
|
+
body: Dict[str, Any] = {"agent_id": self.agent_id, "session_id": self.session_id}
|
|
253
|
+
if isinstance(value, str):
|
|
254
|
+
body["text"] = value
|
|
255
|
+
else:
|
|
256
|
+
body["value"] = value
|
|
257
|
+
resp = self._client().post(self.gateway + "/v1/restore", json=body, headers=self.headers())
|
|
258
|
+
data = self._raise_for(resp)
|
|
259
|
+
return data["text"] if isinstance(value, str) else data["value"]
|
|
260
|
+
|
|
261
|
+
async def arestore(self, value: Any) -> Any:
|
|
262
|
+
body: Dict[str, Any] = {"agent_id": self.agent_id, "session_id": self.session_id}
|
|
263
|
+
if isinstance(value, str):
|
|
264
|
+
body["text"] = value
|
|
265
|
+
else:
|
|
266
|
+
body["value"] = value
|
|
267
|
+
resp = await self._aclient().post(self.gateway + "/v1/restore", json=body, headers=self.headers())
|
|
268
|
+
data = self._raise_for(resp)
|
|
269
|
+
return data["text"] if isinstance(value, str) else data["value"]
|
|
270
|
+
|
|
271
|
+
def register(self, manifest: str, rotate_key: bool = False) -> Dict[str, Any]:
|
|
272
|
+
if "\n" not in manifest and os.path.exists(manifest):
|
|
273
|
+
with open(manifest, "r", encoding="utf-8") as f:
|
|
274
|
+
manifest = f.read()
|
|
275
|
+
resp = self._client().post(
|
|
276
|
+
self.gateway + "/v1/agents",
|
|
277
|
+
content=manifest.encode(),
|
|
278
|
+
params={"rotate_key": "true"} if rotate_key else None,
|
|
279
|
+
headers={**self.headers(), "Content-Type": "application/yaml"},
|
|
280
|
+
)
|
|
281
|
+
return self._raise_for(resp)
|
|
282
|
+
|
|
283
|
+
def issue_token(self, session_id: Optional[str] = None, ttl_seconds: int = 0) -> Dict[str, Any]:
|
|
284
|
+
if not self.agent_id:
|
|
285
|
+
raise RungatedError("agent_id is required")
|
|
286
|
+
body: Dict[str, Any] = {"session_id": session_id or self.session_id or "", "ttl_seconds": ttl_seconds}
|
|
287
|
+
hdrs = {k: v for k, v in self.headers().items() if k != "X-Rungated-Token"}
|
|
288
|
+
resp = self._client().post(self.gateway + "/v1/agents/%s/token" % self.agent_id, json=body, headers=hdrs)
|
|
289
|
+
return self._raise_for(resp)
|
|
290
|
+
|
|
291
|
+
def health(self) -> Dict[str, Any]:
|
|
292
|
+
return self._raise_for(self._client().get(self.gateway + "/v1/health"))
|
|
293
|
+
|
|
294
|
+
def approval(self, approval_id: str) -> Dict[str, Any]:
|
|
295
|
+
return self._raise_for(self._client().get(self.gateway + "/v1/approvals/" + approval_id, headers=self.headers()))
|
|
296
|
+
|
|
297
|
+
def wrap_openai(self, client: Any) -> Any:
|
|
298
|
+
return client.with_options(**self.llm_kwargs("openai"))
|
|
299
|
+
|
|
300
|
+
def wrap_anthropic(self, client: Any) -> Any:
|
|
301
|
+
return client.with_options(**self.llm_kwargs("anthropic"))
|
|
302
|
+
|
|
303
|
+
def openai(self, **kw: Any) -> Any:
|
|
304
|
+
from openai import OpenAI
|
|
305
|
+
|
|
306
|
+
kw.setdefault("api_key", "rungated")
|
|
307
|
+
return OpenAI(**{**kw, **self.llm_kwargs("openai")})
|
|
308
|
+
|
|
309
|
+
def async_openai(self, **kw: Any) -> Any:
|
|
310
|
+
from openai import AsyncOpenAI
|
|
311
|
+
|
|
312
|
+
kw.setdefault("api_key", "rungated")
|
|
313
|
+
return AsyncOpenAI(**{**kw, **self.llm_kwargs("openai")})
|
|
314
|
+
|
|
315
|
+
def anthropic(self, **kw: Any) -> Any:
|
|
316
|
+
from anthropic import Anthropic
|
|
317
|
+
|
|
318
|
+
kw.setdefault("api_key", "rungated")
|
|
319
|
+
return Anthropic(**{**kw, **self.llm_kwargs("anthropic")})
|
|
320
|
+
|
|
321
|
+
def async_anthropic(self, **kw: Any) -> Any:
|
|
322
|
+
from anthropic import AsyncAnthropic
|
|
323
|
+
|
|
324
|
+
kw.setdefault("api_key", "rungated")
|
|
325
|
+
return AsyncAnthropic(**{**kw, **self.llm_kwargs("anthropic")})
|
|
326
|
+
|