agentfences 0.2.0__tar.gz → 0.3.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.
Files changed (25) hide show
  1. {agentfences-0.2.0 → agentfences-0.3.0}/PKG-INFO +75 -5
  2. {agentfences-0.2.0 → agentfences-0.3.0}/README.md +75 -5
  3. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences/__init__.py +6 -2
  4. agentfences-0.3.0/agentfences/client.py +88 -0
  5. agentfences-0.3.0/agentfences/control.py +230 -0
  6. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences/core.py +120 -52
  7. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences/events.py +5 -0
  8. agentfences-0.3.0/agentfences/exceptions.py +28 -0
  9. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences/instrument.py +3 -22
  10. agentfences-0.3.0/agentfences/langchain.py +187 -0
  11. agentfences-0.3.0/agentfences/openai_agents.py +83 -0
  12. agentfences-0.3.0/agentfences/prices.json +1 -0
  13. agentfences-0.3.0/agentfences/spans.py +43 -0
  14. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences/tools.py +6 -18
  15. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences.egg-info/PKG-INFO +75 -5
  16. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences.egg-info/SOURCES.txt +4 -0
  17. {agentfences-0.2.0 → agentfences-0.3.0}/pyproject.toml +4 -1
  18. agentfences-0.2.0/agentfences/client.py +0 -78
  19. agentfences-0.2.0/agentfences/exceptions.py +0 -38
  20. agentfences-0.2.0/agentfences/prices.json +0 -1
  21. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences/pricing.py +0 -0
  22. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences.egg-info/dependency_links.txt +0 -0
  23. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences.egg-info/requires.txt +0 -0
  24. {agentfences-0.2.0 → agentfences-0.3.0}/agentfences.egg-info/top_level.txt +0 -0
  25. {agentfences-0.2.0 → agentfences-0.3.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: agentfences
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Runtime governance for AI agents — budget limits, loop protection, token limits, audit trail
5
5
  Author: Bhavik Sardar
6
6
  License: MIT
@@ -13,7 +13,9 @@ Requires-Python: >=3.9
13
13
  Description-Content-Type: text/markdown
14
14
  Requires-Dist: requests>=2.25.0
15
15
 
16
- # Fences
16
+ # (|=|) Fences
17
+
18
+ [![test](https://github.com/bhaviksardar/fences/actions/workflows/test.yml/badge.svg)](https://github.com/bhaviksardar/fences/actions/workflows/test.yml)
17
19
 
18
20
  The open-source SDK for Fences, on-call for AI agents. It records what your agent decides and why, enforces limits the agent can't raise, and lets you stop a run from the Fences dashboard. Works offline too: local limits, no account.
19
21
 
@@ -115,7 +117,9 @@ print(asyncio.run(my_agent("hello")))
115
117
 
116
118
  A limit trips once it is exceeded, not when it is reached: a $0.10 budget allows exactly $0.10 of spend.
117
119
 
118
- On Fences Cloud a run can also stop with `stopped_by_user` (someone pressed Stop in the dashboard), `key_daily_budget` or `key_monthly_budget` (the agent's daily or monthly cap across all its runs). With `init(fail_closed=True)`, an unreachable backend stops it with `fences_unreachable`. Each comes with its own `message` and `system_prompt`.
120
+ Every limit is optional. On Fences Cloud, a limit left out of `@governed(...)` comes from the agent's page in the dashboard, so `@governed()` on its own works. Limits set nowhere default to 100 steps, 5 minutes and no token limit, and no budget: the run still starts, but its spend isn't capped, and Fences logs a warning once per agent (and flags the agent in the dashboard).
121
+
122
+ On Fences Cloud a run can also stop with `stopped_by_user` (someone pressed Stop in the dashboard), `paused` (paused and not resumed in time), `key_daily_budget` or `key_monthly_budget` (the agent's daily or monthly cap across all its runs). With `init(fail_closed=True)`, an unreachable backend stops it with `fences_unreachable`. Each comes with its own `message` and `system_prompt`.
119
123
 
120
124
  ## Sync agents and streaming
121
125
 
@@ -135,6 +139,62 @@ def my_agent(query: str):
135
139
 
136
140
  A governed async generator (a streaming agent) stays governed until the stream is exhausted. Concurrent agents in one event loop and nested `@governed` calls each get their own run.
137
141
 
142
+ ## Frameworks: LangChain, LangGraph and the OpenAI Agents SDK
143
+
144
+ Agents built on a framework need no decorators. Each model call is recorded with its tokens and cost and checkpointed, so limits apply, and each tool call is recorded. Limits work as in `@governed` and are all optional.
145
+
146
+ Callbacks and hooks can't hand a result back to the agent, so when a limit is crossed these integrations raise `FencesStop`. It carries the same `breach_type`, `message` and `system_prompt` as a breached `checkpoint()`.
147
+
148
+ **LangChain and LangGraph** (needs `langchain-core`):
149
+
150
+ ```python
151
+ from agentfences import FencesStop
152
+ from agentfences.langchain import FencesCallbackHandler
153
+
154
+ try:
155
+ graph.invoke(inputs, config={"callbacks": [FencesCallbackHandler(budget_usd=2)]})
156
+ except FencesStop as stop:
157
+ answer = stop.message
158
+ ```
159
+
160
+ The outermost run becomes a Fences run named after it (or `agent_name=...`), and joins the run if it's already inside `@governed`. Sync and async graphs both work. LangChain logs its own "Error in FencesCallbackHandler.on_llm_end callback" line when the handler stops a graph; that's expected.
161
+
162
+ **OpenAI Agents SDK** (needs `openai-agents`, Python 3.10+):
163
+
164
+ ```python
165
+ from agentfences import FencesStop, openai_agents
166
+
167
+ try:
168
+ result = await openai_agents.run(agent, "Research cats", budget_usd=2) # Runner.run, governed
169
+ except FencesStop as stop:
170
+ answer = stop.message
171
+ ```
172
+
173
+ Already inside `@governed`? Use `Runner.run(agent, input, hooks=openai_agents.FencesRunHooks())`.
174
+
175
+ With a framework integration, don't also pass `instrument=True` or decorate tools with `@agentfences.tool`: each call would be recorded twice.
176
+
177
+ ## Live control
178
+
179
+ In cloud mode the SDK keeps a heartbeat with Fences, so whoever is on call can act on a run while it's going:
180
+
181
+ - **Stop:** the run's next `checkpoint()` returns `breach_type="stopped_by_user"` with its message, so the agent wraps up gracefully. A stop sticks, whatever later responses say.
182
+ - **Pause and resume:** a paused run waits inside its next `checkpoint()` until it's resumed, then carries on. If no one resumes it within `pause_timeout_s` (default one hour), the checkpoint returns `breach_type="paused"`.
183
+ - **Change limits:** new limits apply to the run immediately.
184
+ - **Quarantine:** calling a governed function for a quarantined agent raises `AgentQuarantined` before any of its code runs.
185
+
186
+ An agent can also ask a person before doing something risky:
187
+
188
+ ```python
189
+ approval = await agentfences.request_approval("Refund $240 to order 1182?", amount_usd=240, timeout_s=600)
190
+ if not approval.granted:
191
+ return f"I didn't issue the refund: {approval.note}"
192
+ ```
193
+
194
+ The answer has `granted`, `by`, `note` and `amount_usd`; an approved amount raises the run's budget by that much. `request_approval_sync()` does the same for synchronous agents. It never hangs and never raises: in local mode, outside a run, or when the server can't take requests it returns denied right away, and with no answer it returns denied after `timeout_s`.
195
+
196
+ The heartbeat reports live runs every 15 seconds (`init(heartbeat_s=...)`), and every 2 seconds while a run is paused or waiting for approval. A Fences server without these features gets one warning: stops still apply at the next checkpoint, and approval requests are denied.
197
+
138
198
  ## Evidence: tool calls and model calls
139
199
 
140
200
  On-call can only explain what was recorded. Fences records two kinds of call on the run automatically, alongside your `log_decision()` entries.
@@ -159,7 +219,7 @@ agentfences.init(api_key="fc_...", endpoint="https://...", instrument=True)
159
219
 
160
220
  Each call records the model, tokens (including cache reads and writes), cost, latency, and the error and status code if it failed (a 429 rate limit, say). This is a record only: it doesn't count as a checkpoint or add to the run's spend, so keep calling `checkpoint(response)` where limits should be checked. Streamed calls are recorded without token counts.
161
221
 
162
- Both kinds of call are kept on the run (`get_active_run().events`, newest 1,000) and, in cloud mode, sent to Fences in the background in batches. They pass through the `redact` hook first as `tool_call` (`name`, `args`, `error`) and `llm_call` (`model`, `error`) events. A Fences server that doesn't accept them yet gets a single warning and nothing else changes.
222
+ Both kinds of call are recorded as spans named by the OpenTelemetry GenAI conventions (`chat gpt-4o`, `execute_tool web_search`, with `gen_ai.*` attributes plus Fences' `fences.cost_usd`). They're kept on the run (`get_active_run().events`, newest 1,000) and, in cloud mode, sent to Fences in the background in batches. They pass through the `redact` hook first as `tool_call` (`name`, `args`, `error`) and `llm_call` (`model`, `error`) events. A Fences server that doesn't accept them yet gets a single warning and nothing else changes.
163
223
 
164
224
  ## Context, errors and redaction
165
225
 
@@ -187,7 +247,7 @@ def redact(event):
187
247
  agentfences.init(api_key="fc_...", endpoint="https://...", redact=redact)
188
248
  ```
189
249
 
190
- Events have a `type` of `run_start` (`context`), `decision` (`reasoning`, `action`), `tool_call` (`name`, `args`, `error`), `llm_call` (`model`, `error`) or `run_end` (`status`, `error`, `exception`). If the hook raises, that event is dropped rather than sent unredacted, and a warning is logged once. Runs still start and end, so limits keep working.
250
+ Events have a `type` of `run_start` (`context`), `decision` (`reasoning`, `action`), `span` (a tool or model call: change its `attributes`, e.g. `gen_ai.tool.call.arguments` or `fences.error.message`) or `run_end` (`status`, `error`, `exception`). If the hook raises, that event is dropped rather than sent unredacted, and a warning is logged once. Runs still start and end, so limits keep working.
191
251
 
192
252
  ## Modes
193
253
 
@@ -208,6 +268,16 @@ If the backend can't be reached, limits are enforced locally and a warning is lo
208
268
  agentfences.init(api_key="fc_...", endpoint="https://...", fail_closed=True)
209
269
  ```
210
270
 
271
+ ## Project layout
272
+
273
+ ```
274
+ fences/
275
+ ├── docs/ landing page
276
+ ├── sdk/ agentfences Python package
277
+ └── sdk-js/ agentfences TypeScript package (npm)
278
+ └── agentfences/
279
+ ```
280
+
211
281
  ## License
212
282
 
213
283
  MIT
@@ -1,4 +1,6 @@
1
- # Fences
1
+ # (|=|) Fences
2
+
3
+ [![test](https://github.com/bhaviksardar/fences/actions/workflows/test.yml/badge.svg)](https://github.com/bhaviksardar/fences/actions/workflows/test.yml)
2
4
 
3
5
  The open-source SDK for Fences, on-call for AI agents. It records what your agent decides and why, enforces limits the agent can't raise, and lets you stop a run from the Fences dashboard. Works offline too: local limits, no account.
4
6
 
@@ -100,7 +102,9 @@ print(asyncio.run(my_agent("hello")))
100
102
 
101
103
  A limit trips once it is exceeded, not when it is reached: a $0.10 budget allows exactly $0.10 of spend.
102
104
 
103
- On Fences Cloud a run can also stop with `stopped_by_user` (someone pressed Stop in the dashboard), `key_daily_budget` or `key_monthly_budget` (the agent's daily or monthly cap across all its runs). With `init(fail_closed=True)`, an unreachable backend stops it with `fences_unreachable`. Each comes with its own `message` and `system_prompt`.
105
+ Every limit is optional. On Fences Cloud, a limit left out of `@governed(...)` comes from the agent's page in the dashboard, so `@governed()` on its own works. Limits set nowhere default to 100 steps, 5 minutes and no token limit, and no budget: the run still starts, but its spend isn't capped, and Fences logs a warning once per agent (and flags the agent in the dashboard).
106
+
107
+ On Fences Cloud a run can also stop with `stopped_by_user` (someone pressed Stop in the dashboard), `paused` (paused and not resumed in time), `key_daily_budget` or `key_monthly_budget` (the agent's daily or monthly cap across all its runs). With `init(fail_closed=True)`, an unreachable backend stops it with `fences_unreachable`. Each comes with its own `message` and `system_prompt`.
104
108
 
105
109
  ## Sync agents and streaming
106
110
 
@@ -120,6 +124,62 @@ def my_agent(query: str):
120
124
 
121
125
  A governed async generator (a streaming agent) stays governed until the stream is exhausted. Concurrent agents in one event loop and nested `@governed` calls each get their own run.
122
126
 
127
+ ## Frameworks: LangChain, LangGraph and the OpenAI Agents SDK
128
+
129
+ Agents built on a framework need no decorators. Each model call is recorded with its tokens and cost and checkpointed, so limits apply, and each tool call is recorded. Limits work as in `@governed` and are all optional.
130
+
131
+ Callbacks and hooks can't hand a result back to the agent, so when a limit is crossed these integrations raise `FencesStop`. It carries the same `breach_type`, `message` and `system_prompt` as a breached `checkpoint()`.
132
+
133
+ **LangChain and LangGraph** (needs `langchain-core`):
134
+
135
+ ```python
136
+ from agentfences import FencesStop
137
+ from agentfences.langchain import FencesCallbackHandler
138
+
139
+ try:
140
+ graph.invoke(inputs, config={"callbacks": [FencesCallbackHandler(budget_usd=2)]})
141
+ except FencesStop as stop:
142
+ answer = stop.message
143
+ ```
144
+
145
+ The outermost run becomes a Fences run named after it (or `agent_name=...`), and joins the run if it's already inside `@governed`. Sync and async graphs both work. LangChain logs its own "Error in FencesCallbackHandler.on_llm_end callback" line when the handler stops a graph; that's expected.
146
+
147
+ **OpenAI Agents SDK** (needs `openai-agents`, Python 3.10+):
148
+
149
+ ```python
150
+ from agentfences import FencesStop, openai_agents
151
+
152
+ try:
153
+ result = await openai_agents.run(agent, "Research cats", budget_usd=2) # Runner.run, governed
154
+ except FencesStop as stop:
155
+ answer = stop.message
156
+ ```
157
+
158
+ Already inside `@governed`? Use `Runner.run(agent, input, hooks=openai_agents.FencesRunHooks())`.
159
+
160
+ With a framework integration, don't also pass `instrument=True` or decorate tools with `@agentfences.tool`: each call would be recorded twice.
161
+
162
+ ## Live control
163
+
164
+ In cloud mode the SDK keeps a heartbeat with Fences, so whoever is on call can act on a run while it's going:
165
+
166
+ - **Stop:** the run's next `checkpoint()` returns `breach_type="stopped_by_user"` with its message, so the agent wraps up gracefully. A stop sticks, whatever later responses say.
167
+ - **Pause and resume:** a paused run waits inside its next `checkpoint()` until it's resumed, then carries on. If no one resumes it within `pause_timeout_s` (default one hour), the checkpoint returns `breach_type="paused"`.
168
+ - **Change limits:** new limits apply to the run immediately.
169
+ - **Quarantine:** calling a governed function for a quarantined agent raises `AgentQuarantined` before any of its code runs.
170
+
171
+ An agent can also ask a person before doing something risky:
172
+
173
+ ```python
174
+ approval = await agentfences.request_approval("Refund $240 to order 1182?", amount_usd=240, timeout_s=600)
175
+ if not approval.granted:
176
+ return f"I didn't issue the refund: {approval.note}"
177
+ ```
178
+
179
+ The answer has `granted`, `by`, `note` and `amount_usd`; an approved amount raises the run's budget by that much. `request_approval_sync()` does the same for synchronous agents. It never hangs and never raises: in local mode, outside a run, or when the server can't take requests it returns denied right away, and with no answer it returns denied after `timeout_s`.
180
+
181
+ The heartbeat reports live runs every 15 seconds (`init(heartbeat_s=...)`), and every 2 seconds while a run is paused or waiting for approval. A Fences server without these features gets one warning: stops still apply at the next checkpoint, and approval requests are denied.
182
+
123
183
  ## Evidence: tool calls and model calls
124
184
 
125
185
  On-call can only explain what was recorded. Fences records two kinds of call on the run automatically, alongside your `log_decision()` entries.
@@ -144,7 +204,7 @@ agentfences.init(api_key="fc_...", endpoint="https://...", instrument=True)
144
204
 
145
205
  Each call records the model, tokens (including cache reads and writes), cost, latency, and the error and status code if it failed (a 429 rate limit, say). This is a record only: it doesn't count as a checkpoint or add to the run's spend, so keep calling `checkpoint(response)` where limits should be checked. Streamed calls are recorded without token counts.
146
206
 
147
- Both kinds of call are kept on the run (`get_active_run().events`, newest 1,000) and, in cloud mode, sent to Fences in the background in batches. They pass through the `redact` hook first as `tool_call` (`name`, `args`, `error`) and `llm_call` (`model`, `error`) events. A Fences server that doesn't accept them yet gets a single warning and nothing else changes.
207
+ Both kinds of call are recorded as spans named by the OpenTelemetry GenAI conventions (`chat gpt-4o`, `execute_tool web_search`, with `gen_ai.*` attributes plus Fences' `fences.cost_usd`). They're kept on the run (`get_active_run().events`, newest 1,000) and, in cloud mode, sent to Fences in the background in batches. They pass through the `redact` hook first as `tool_call` (`name`, `args`, `error`) and `llm_call` (`model`, `error`) events. A Fences server that doesn't accept them yet gets a single warning and nothing else changes.
148
208
 
149
209
  ## Context, errors and redaction
150
210
 
@@ -172,7 +232,7 @@ def redact(event):
172
232
  agentfences.init(api_key="fc_...", endpoint="https://...", redact=redact)
173
233
  ```
174
234
 
175
- Events have a `type` of `run_start` (`context`), `decision` (`reasoning`, `action`), `tool_call` (`name`, `args`, `error`), `llm_call` (`model`, `error`) or `run_end` (`status`, `error`, `exception`). If the hook raises, that event is dropped rather than sent unredacted, and a warning is logged once. Runs still start and end, so limits keep working.
235
+ Events have a `type` of `run_start` (`context`), `decision` (`reasoning`, `action`), `span` (a tool or model call: change its `attributes`, e.g. `gen_ai.tool.call.arguments` or `fences.error.message`) or `run_end` (`status`, `error`, `exception`). If the hook raises, that event is dropped rather than sent unredacted, and a warning is logged once. Runs still start and end, so limits keep working.
176
236
 
177
237
  ## Modes
178
238
 
@@ -193,6 +253,16 @@ If the backend can't be reached, limits are enforced locally and a warning is lo
193
253
  agentfences.init(api_key="fc_...", endpoint="https://...", fail_closed=True)
194
254
  ```
195
255
 
256
+ ## Project layout
257
+
258
+ ```
259
+ fences/
260
+ ├── docs/ landing page
261
+ ├── sdk/ agentfences Python package
262
+ └── sdk-js/ agentfences TypeScript package (npm)
263
+ └── agentfences/
264
+ ```
265
+
196
266
  ## License
197
267
 
198
- MIT
268
+ MIT
@@ -1,11 +1,15 @@
1
+ __version__ = "0.3.0" # the one place the version lives; pyproject.toml reads it from here
2
+
1
3
  from .core import init, governed, checkpoint, checkpoint_sync, log_decision, flush, get_active_run, CheckpointResult
2
4
  from .events import context
3
5
  from .tools import tool
4
6
  from .instrument import instrument
5
- from .exceptions import FencesError, BudgetExceeded, IterationLimitReached, TimeLimitReached, TokenLimitReached
7
+ from .control import request_approval, request_approval_sync, Approval
8
+ from .exceptions import FencesError, AgentQuarantined, FencesStop
6
9
 
7
10
  __all__ = [
8
11
  "init", "governed", "checkpoint", "checkpoint_sync", "log_decision", "flush", "get_active_run", "context", "tool", "instrument",
12
+ "request_approval", "request_approval_sync", "Approval",
9
13
  "CheckpointResult",
10
- "FencesError", "BudgetExceeded", "IterationLimitReached", "TimeLimitReached", "TokenLimitReached",
14
+ "FencesError", "AgentQuarantined", "FencesStop",
11
15
  ]
@@ -0,0 +1,88 @@
1
+ import requests
2
+
3
+ from . import __version__
4
+ from typing import Optional
5
+
6
+
7
+ class GovClient:
8
+ def __init__(self, api_key: str, endpoint: str, timeout: float = 3.0):
9
+ self.api_key = api_key
10
+ # The server uses the SDK version to warn about old SDKs and to skip commands they don't understand
11
+ self.headers = {"X-API-Key": api_key, "X-Fences-SDK": f"python/{__version__}"}
12
+ self.endpoint = endpoint.rstrip("/")
13
+ self.timeout = timeout
14
+
15
+ def start_run(self, run_id: str, agent_name: str, budget_usd: float, max_iterations: int, max_duration_ms: int, max_tokens: int,
16
+ context: Optional[dict] = None) -> dict:
17
+ payload = {
18
+ "run_id": run_id,
19
+ "agent_name": agent_name,
20
+ "budget_usd": budget_usd,
21
+ "max_iterations": max_iterations,
22
+ "max_duration_ms": max_duration_ms,
23
+ "max_tokens": max_tokens,
24
+ }
25
+ if context:
26
+ payload["context"] = context
27
+ return self._post("/api/runs/start", payload)
28
+
29
+ def checkpoint(self, run_id: str, cost_delta_usd: float, iterations: int, duration_ms: int, tokens_used: int) -> dict:
30
+ return self._post(f"/api/runs/{run_id}/checkpoint", {
31
+ "cost_delta_usd": cost_delta_usd,
32
+ "iterations": iterations,
33
+ "duration_ms": duration_ms,
34
+ "tokens_used": tokens_used,
35
+ })
36
+
37
+ def log_decision(self, run_id: str, iteration: int, reasoning: str, action: Optional[str]) -> dict:
38
+ return self._post(f"/api/runs/{run_id}/decisions", {
39
+ "iteration": iteration,
40
+ "reasoning": reasoning,
41
+ "action": action,
42
+ })
43
+
44
+ def log_spans(self, run_id: str, spans: list) -> dict:
45
+ return self._post(f"/api/runs/{run_id}/spans", {"spans": spans}, optional=True)
46
+
47
+ def heartbeat(self, runs: list) -> dict:
48
+ """Report live runs; the reply may carry commands for them."""
49
+ return self._post("/api/heartbeat", {"runs": runs}, optional=True)
50
+
51
+ def request_approval(self, run_id: str, approval_id: str, reason: str, amount_usd: Optional[float],
52
+ timeout_s: float) -> dict:
53
+ return self._post(f"/api/runs/{run_id}/approvals", {"approval_id": approval_id, "reason": reason,
54
+ "amount_usd": amount_usd, "timeout_s": timeout_s}, optional=True)
55
+
56
+ def end_run(self, run_id: str, status: str, error: Optional[str] = None, exception: Optional[dict] = None) -> dict:
57
+ payload = {"status": status, "error": error}
58
+ if exception:
59
+ payload["exception"] = exception
60
+ return self._post(f"/api/runs/{run_id}/end", payload)
61
+
62
+ def _post(self, path: str, payload: dict, optional: bool = False) -> dict:
63
+ """
64
+ optional: an endpoint older servers may not have. A missing route returns
65
+ {"unsupported": True} and no error raises, not even a rejected key.
66
+ """
67
+ try:
68
+ resp = requests.post(f"{self.endpoint}{path}", json=payload, headers=self.headers, timeout=self.timeout)
69
+ except requests.RequestException as e:
70
+ return {"network_error": str(e)}
71
+ try:
72
+ body, is_json = resp.json(), True
73
+ except ValueError: # not JSON: the status code still decides
74
+ body, is_json = {}, False
75
+ detail = body.get("detail", "") if isinstance(body, dict) else ""
76
+ if optional:
77
+ if resp.status_code in (404, 405) and detail in ("Not Found", "Method Not Allowed"):
78
+ return {"unsupported": True}
79
+ return body if resp.ok else {"ok": False, "status": resp.status_code}
80
+ if resp.status_code in (401, 403):
81
+ raise PermissionError(f"Fences API key rejected: {resp.text}")
82
+ if resp.status_code == 423: # the agent is quarantined: the run must not start
83
+ return {"ok": False, "quarantined": True, "detail": detail}
84
+ if resp.status_code == 409: # e.g. checkpoint on a run the server already fenced
85
+ return {"ok": False, "conflict": detail}
86
+ if not resp.ok or not is_json: # an error, or not a Fences reply: enforce locally
87
+ return {"network_error": f"HTTP {resp.status_code}" if not resp.ok else "response was not JSON"}
88
+ return body
@@ -0,0 +1,230 @@
1
+ """
2
+ Live control from the Fences dashboard: a heartbeat that reports live runs and brings
3
+ back commands (stop, pause, resume, limits, approval answers), pausing at checkpoints,
4
+ and approval requests. Cloud mode only; an older server without these endpoints gets
5
+ one warning and runs carry on as before.
6
+ """
7
+ import asyncio
8
+ import logging
9
+ import threading
10
+ import time
11
+ import uuid
12
+ from dataclasses import dataclass
13
+ from typing import Optional
14
+
15
+ log = logging.getLogger("agentfences")
16
+
17
+ FAST_S = 2.0 # heartbeat interval while a run is paused or waiting for an approval
18
+
19
+ _live: dict = {} # run_id -> RunState, for runs in progress
20
+ _lock = threading.Lock()
21
+ _wake = threading.Event() # nudges the heartbeat to report right away
22
+ _thread: Optional[threading.Thread] = None
23
+ _client = None
24
+ _interval = 15.0
25
+ pause_timeout_s = 3600.0
26
+ _supported = {"heartbeat": True, "approvals": True}
27
+ _asked: dict = {} # approval_id -> (perf_counter at request, reason, amount_usd)
28
+
29
+
30
+ @dataclass
31
+ class Approval:
32
+ granted: bool
33
+ by: Optional[str] = None # who answered, as the dashboard reports it
34
+ note: Optional[str] = None # their note, or why no one could answer
35
+ amount_usd: Optional[float] = None # the amount approved, if one was asked for
36
+
37
+
38
+ def configure(client, heartbeat_s: float, pause_timeout: float):
39
+ global _client, _interval, pause_timeout_s, _thread
40
+ _client, _interval, pause_timeout_s = client, heartbeat_s, pause_timeout
41
+ _supported.update(heartbeat=True, approvals=True)
42
+ _wake.set() # a running heartbeat picks up the new client and interval now, not after its old wait
43
+ if client is not None and _thread is None:
44
+ _thread = threading.Thread(target=_heartbeat, name="agentfences-heartbeat", daemon=True)
45
+ _thread.start()
46
+
47
+
48
+ def register(run):
49
+ with _lock:
50
+ _live[run.run_id] = run
51
+
52
+
53
+ def unregister(run):
54
+ with _lock:
55
+ _live.pop(run.run_id, None)
56
+
57
+
58
+ def _unsupported(kind: str, what: str, consequence: str):
59
+ if _supported[kind]:
60
+ _supported[kind] = False
61
+ log.warning("agentfences: this Fences server doesn't support %s yet, so %s", what, consequence)
62
+
63
+
64
+ # ── Commands ──────────────────────────────────────────────────────────────────
65
+
66
+ LIMIT_FIELDS = ("budget_usd", "max_iterations", "max_duration_ms", "max_tokens")
67
+
68
+
69
+ def apply(run, commands):
70
+ """Apply the commands addressed to this run (from a heartbeat or a checkpoint response)."""
71
+ for c in commands or ():
72
+ if c.get("run_id") not in (None, run.run_id):
73
+ continue
74
+ kind = c.get("type")
75
+ if kind == "stop":
76
+ run.stopped = True
77
+ _resume(run)
78
+ elif kind == "pause":
79
+ run.paused = True
80
+ run.resumed.clear()
81
+ _wake.set()
82
+ elif kind == "resume":
83
+ _resume(run)
84
+ elif kind == "limits":
85
+ for f in LIMIT_FIELDS:
86
+ if c.get(f) is not None:
87
+ setattr(run, f, c[f])
88
+ elif kind == "approval" and c.get("approval_id") in run.approvals:
89
+ run.approvals[c["approval_id"]] = Approval(
90
+ granted=bool(c.get("granted")), by=c.get("by"), note=c.get("note"), amount_usd=c.get("amount_usd"))
91
+
92
+
93
+ def _resume(run):
94
+ run.paused = False
95
+ run.resumed.set()
96
+
97
+
98
+ def dispatch(commands):
99
+ with _lock:
100
+ runs = dict(_live)
101
+ for run_id in {c.get("run_id") for c in commands or ()}:
102
+ if run_id in runs:
103
+ apply(runs[run_id], commands)
104
+
105
+
106
+ def _heartbeat():
107
+ while True:
108
+ with _lock:
109
+ busy = any(r.paused or r.awaiting for r in _live.values())
110
+ _wake.wait(FAST_S if busy else _interval)
111
+ _wake.clear()
112
+ with _lock:
113
+ runs = list(_live.values())
114
+ if not runs or _client is None:
115
+ continue
116
+ try:
117
+ resp = _client.heartbeat([{"run_id": r.run_id, "iterations": r.iterations, "spent_usd": r.cost_usd,
118
+ "tokens_used": r.tokens_used, "paused": r.paused} for r in runs])
119
+ except Exception:
120
+ continue
121
+ if resp.get("unsupported"):
122
+ _unsupported("heartbeat", "the heartbeat", "a stop from the dashboard applies at the next checkpoint and pause isn't available")
123
+ return
124
+ dispatch(resp.get("commands"))
125
+
126
+
127
+ # ── Pausing ───────────────────────────────────────────────────────────────────
128
+
129
+ def _pause_over(run, deadline: float) -> bool:
130
+ if not run.paused:
131
+ return True
132
+ if time.monotonic() >= deadline:
133
+ run.paused, run.pause_expired = False, True
134
+ return True
135
+ return False
136
+
137
+
138
+ def wait_if_paused(run):
139
+ """Block a synchronous agent at its checkpoint while the run is paused."""
140
+ deadline = time.monotonic() + pause_timeout_s
141
+ while not _pause_over(run, deadline):
142
+ run.resumed.wait(min(1.0, max(0.0, deadline - time.monotonic())))
143
+
144
+
145
+ async def wait_if_paused_async(run):
146
+ """The same for async agents, without tying up a thread per paused run."""
147
+ deadline = time.monotonic() + pause_timeout_s
148
+ while not _pause_over(run, deadline):
149
+ await asyncio.sleep(0.2)
150
+
151
+
152
+ # ── Approvals ─────────────────────────────────────────────────────────────────
153
+
154
+ def _ask(reason: str, amount_usd: Optional[float], timeout_s: float):
155
+ """Send the request; returns (run, approval_id) to wait on, or an Approval already decided."""
156
+ from .core import get_active_run
157
+ run = get_active_run()
158
+ if run is None:
159
+ return Approval(False, note="request_approval() was called outside a governed run")
160
+ if _client is None:
161
+ return Approval(False, note="Local mode: there is no one to approve this request")
162
+ if not _supported["approvals"]:
163
+ return Approval(False, note="This Fences server doesn't support approvals")
164
+ approval_id = str(uuid.uuid4())
165
+ _asked[approval_id] = (time.perf_counter(), reason, amount_usd)
166
+ resp = _client.request_approval(run.run_id, approval_id, reason, amount_usd, timeout_s) # so the server expires it in step
167
+ if resp.get("unsupported") or "network_error" in resp:
168
+ _asked.pop(approval_id, None)
169
+ if resp.get("unsupported"):
170
+ _unsupported("approvals", "approval requests", "they are denied")
171
+ return Approval(False, note="This Fences server doesn't support approvals")
172
+ if "network_error" in resp:
173
+ return Approval(False, note="Couldn't reach Fences to ask for approval")
174
+ run.approvals[approval_id] = None
175
+ run.awaiting += 1
176
+ _wake.set() # poll fast while someone decides
177
+ return run, approval_id
178
+
179
+
180
+ def _waiting(run, approval_id: str, deadline: float) -> bool:
181
+ return run.approvals.get(approval_id) is None and time.monotonic() < deadline
182
+
183
+
184
+ def _settle(run, approval_id: str) -> Approval:
185
+ from .core import record_span
186
+ run.awaiting -= 1
187
+ answer = run.approvals.pop(approval_id, None) or Approval(False, note="No answer before the timeout")
188
+ if answer.granted and answer.amount_usd and run.budget_usd is not None: # an unlimited run stays unlimited
189
+ run.budget_usd += answer.amount_usd
190
+ started, reason, asked_usd = _asked.pop(approval_id, (time.perf_counter(), None, None))
191
+ record_span("fences.approval", time.perf_counter() - started, { # one span from request to answer
192
+ "fences.approval.id": approval_id, "fences.approval.reason": reason,
193
+ "fences.approval.amount_usd": asked_usd, "fences.approval.granted": answer.granted,
194
+ "fences.approval.by": answer.by, "fences.approval.note": answer.note,
195
+ "fences.approval.granted_usd": answer.amount_usd})
196
+ return answer
197
+
198
+
199
+ def request_approval_sync(reason: str, amount_usd: Optional[float] = None, timeout_s: float = 600) -> Approval:
200
+ """request_approval() for synchronous agents. Same arguments and result."""
201
+ asked = _ask(reason, amount_usd, timeout_s)
202
+ if isinstance(asked, Approval):
203
+ return asked
204
+ run, approval_id = asked
205
+ deadline = time.monotonic() + timeout_s
206
+ while _waiting(run, approval_id, deadline):
207
+ time.sleep(0.1)
208
+ return _settle(run, approval_id)
209
+
210
+
211
+ async def request_approval(reason: str, amount_usd: Optional[float] = None, timeout_s: float = 600) -> Approval:
212
+ """
213
+ Ask a person, through the Fences dashboard, to approve something, and wait for the answer:
214
+
215
+ approval = await agentfences.request_approval("Refund $240 to order 1182?", amount_usd=240)
216
+ if not approval.granted:
217
+ return f"I didn't issue the refund: {approval.note}"
218
+
219
+ If an amount is approved, the run's budget goes up by that much. Returns denied right
220
+ away in local mode, outside a run, or when the server can't take requests, and denied
221
+ after timeout_s seconds with no answer: it never hangs and never raises.
222
+ """
223
+ asked = await asyncio.to_thread(_ask, reason, amount_usd, timeout_s)
224
+ if isinstance(asked, Approval):
225
+ return asked
226
+ run, approval_id = asked
227
+ deadline = time.monotonic() + timeout_s
228
+ while _waiting(run, approval_id, deadline):
229
+ await asyncio.sleep(0.1)
230
+ return _settle(run, approval_id)