provenza 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
provenza/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ # Copyright (c) 2026 Laziz Kironov
2
+ # Licensed under the Apache License, Version 2.0.
3
+ # Part of Provenza — https://github.com/kironovlaziz-del/provenza
4
+
5
+ """
6
+ Provenza SDK - governed, signed and auditable actions for AI agents.
7
+
8
+ from provenza import Agent
9
+
10
+ agent = Agent("support-bot") # PROVENZA_URL + PROVENZA_TOKEN, or standalone without them
11
+
12
+ @agent.tool(name="zendesk.read")
13
+ def open_tickets() -> list: ...
14
+
15
+ See README.md for modes, keys and integrations.
16
+ """
17
+
18
+ from provenza.agent import Agent, Check, ProvenzaWarning, ToolSpec
19
+ from provenza.errors import (ProvenzaApprovalRequired, ProvenzaConfigError, ProvenzaDenied, ProvenzaError,
20
+ ProvenzaRequestError, ProvenzaUnavailable)
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ __all__ = [
25
+ "Agent", "Check", "ToolSpec", "ProvenzaWarning",
26
+ "ProvenzaError", "ProvenzaConfigError", "ProvenzaUnavailable", "ProvenzaRequestError",
27
+ "ProvenzaDenied", "ProvenzaApprovalRequired", "__version__",
28
+ ]
provenza/agent.py ADDED
@@ -0,0 +1,540 @@
1
+ # Copyright (c) 2026 Laziz Kironov
2
+ # Licensed under the Apache License, Version 2.0.
3
+ # Part of Provenza — https://github.com/kironovlaziz-del/provenza
4
+
5
+ """
6
+ Agent - the SDK's entry point.
7
+
8
+ from provenza import Agent
9
+
10
+ agent = Agent("billing-bot") # PROVENZA_URL / PROVENZA_TOKEN from the environment
11
+
12
+ @agent.tool(name="db.read")
13
+ def read(query: str) -> dict: ...
14
+
15
+ Every call of a tool becomes a PVP action (docs/pvp/spec.md):
16
+
17
+ connected check on the server (rights, policies, Tool Registry, injection,
18
+ behaviour, breaker) -> the tool runs only if allowed -> the
19
+ result is recorded, signed with the agent's key under the
20
+ single-use check_id. Denied and pending calls raise and are
21
+ recorded too. The server unreachable: the call does NOT run
22
+ (fail-closed) unless fail_open=True.
23
+ standalone no server: the call runs (within allowed_tools if given) and
24
+ is written to the local signed audit log.
25
+
26
+ What this is, said plainly: the SDK runs inside the agent's process, so it
27
+ is the agent's honest record and cooperative enforcement - code in that
28
+ process could call a tool around it. Enforcement that does not depend on the
29
+ agent is Provenza's gateways (LLM, MCP, A2A) and, next, the egress proxy.
30
+ """
31
+
32
+ import asyncio
33
+ import contextlib
34
+ import contextvars
35
+ import functools
36
+ import inspect
37
+ import json
38
+ import os
39
+ import secrets
40
+ import time
41
+ import warnings
42
+ from dataclasses import dataclass, field
43
+ from pathlib import Path
44
+ from typing import Any, Callable, Dict, Iterable, Optional, TypeVar
45
+
46
+ from provenza import identity as ids
47
+ from provenza.audit_log import AuditLog
48
+ from provenza.client import Client
49
+ from provenza.crypto import Keys, canonical, content_hash
50
+ from provenza.errors import (ProvenzaApprovalRequired, ProvenzaConfigError, ProvenzaDenied, ProvenzaRequestError,
51
+ ProvenzaUnavailable)
52
+
53
+ F = TypeVar("F", bound=Callable[..., Any])
54
+ _chain: contextvars.ContextVar = contextvars.ContextVar("provenza_chain_id", default=None)
55
+ RECORD_RETRIES = (0.2, 1.0) # seconds before the 2nd and 3rd attempt; the check lives 5 minutes
56
+
57
+
58
+ class ProvenzaWarning(UserWarning):
59
+ """Something went wrong after a tool already ran (it could not be
60
+ recorded on the server); the gap is in the local audit log."""
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class ToolSpec:
65
+ name: str
66
+ action_type: str = "tool_call"
67
+ version: Optional[str] = None
68
+ digest: Optional[str] = None
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class Check:
73
+ """The server's verdict for one proposed call, bound to it."""
74
+ check_id: str
75
+ decision: str # allowed | denied | pending_approval
76
+ reason: str
77
+ tool: str
78
+ action_type: str
79
+ input: Dict[str, Any] = field(repr=False)
80
+ chain_id: Optional[int] = None
81
+ incident_type: Optional[str] = None
82
+ policy_id: Optional[int] = None
83
+
84
+ @property
85
+ def allowed(self) -> bool:
86
+ return self.decision == "allowed"
87
+
88
+
89
+ def _json_value(value: Any, what: str) -> Any:
90
+ """Normalized to plain JSON (tuples become lists); refuses what has no
91
+ JSON form, and NaN / Infinity, before anything is sent or run."""
92
+ try:
93
+ return json.loads(canonical(value))
94
+ except (TypeError, ValueError) as exc:
95
+ raise TypeError(f"{what} must be JSON-serializable (no NaN / Infinity): {exc}") from exc
96
+
97
+
98
+ def _arguments(fn: Callable, args: tuple, kwargs: dict) -> Dict[str, Any]:
99
+ params = list(inspect.signature(fn).parameters)
100
+ bound = inspect.signature(fn).bind(*args, **kwargs)
101
+ bound.apply_defaults()
102
+ data = {k: v for k, v in bound.arguments.items() if not (params and k == params[0] and k in ("self", "cls"))}
103
+ return _json_value(data, "tool arguments")
104
+
105
+
106
+ def _output(result: Any) -> Optional[Dict[str, Any]]:
107
+ if result is None:
108
+ return None
109
+ try:
110
+ value = json.loads(canonical(result))
111
+ except (TypeError, ValueError):
112
+ return {"repr": repr(result)[:2000]} # what is recorded (hashed) for a non-JSON result
113
+ return value if isinstance(value, dict) else {"result": value}
114
+
115
+
116
+ class _Recorder:
117
+ """record_mode="background" for sync tools: one daemon thread sends the
118
+ records in order. A failure becomes a gap in the local audit log, as in
119
+ sync mode. Drained by close() and at interpreter exit; a process that is
120
+ killed loses what is still queued - the price of not waiting."""
121
+
122
+ def __init__(self, send: Callable[..., Any]):
123
+ import atexit
124
+ import queue
125
+ import threading
126
+
127
+ self._send, self._queue = send, queue.Queue()
128
+ self._thread = threading.Thread(target=self._work, name="provenza-recorder", daemon=True)
129
+ self._thread.start()
130
+ atexit.register(self.drain)
131
+
132
+ def _work(self) -> None:
133
+ while True:
134
+ job = self._queue.get()
135
+ try:
136
+ if job is not None:
137
+ self._send(*job)
138
+ finally:
139
+ self._queue.task_done()
140
+
141
+ def put(self, *job: Any) -> None:
142
+ self._queue.put(job)
143
+
144
+ def drain(self, timeout: float = 30.0) -> bool:
145
+ """Wait until everything queued was sent (or became a gap)."""
146
+ import threading
147
+
148
+ done = threading.Event()
149
+ threading.Thread(target=lambda: (self._queue.join(), done.set()), daemon=True).start()
150
+ return done.wait(timeout)
151
+
152
+
153
+ class Agent:
154
+ def __init__(self, name: Optional[str] = None, *, server_url: Optional[str] = None,
155
+ enrollment_token: Optional[str] = None, identity_path: Optional[str] = None,
156
+ key_store: str = "file", mode: Optional[str] = None, hybrid: bool = False,
157
+ allowed_tools: Optional[Iterable[str]] = None, audit_log: Optional[str] = None,
158
+ fail_open: bool = False, record_mode: str = "sync", timeout: float = 10.0, transport=None,
159
+ async_transport=None):
160
+ self.name = name or os.environ.get("PROVENZA_AGENT_NAME") or "agent"
161
+ server_url = server_url or os.environ.get("PROVENZA_URL")
162
+ token = enrollment_token or os.environ.get("PROVENZA_TOKEN")
163
+ self.mode = mode or os.environ.get("PROVENZA_MODE") or ("connected" if server_url else "standalone")
164
+ if self.mode not in ("connected", "standalone"):
165
+ raise ProvenzaConfigError("mode must be 'connected' or 'standalone'")
166
+ self.identity_path = Path(identity_path or os.environ.get("PROVENZA_IDENTITY") or ids.default_path(self.name))
167
+ self.fail_open = fail_open
168
+ if record_mode not in ("sync", "background"):
169
+ raise ProvenzaConfigError("record_mode must be 'sync' or 'background'")
170
+ self.record_mode = record_mode
171
+ self._recorder: Optional[_Recorder] = None
172
+ self._pending: set = set() # background record tasks of async tools
173
+ self.allowed_tools = frozenset(allowed_tools) if allowed_tools is not None else None
174
+ self._client: Optional[Client] = None
175
+ self.identity = self._load_identity(server_url, token, key_store, hybrid, timeout, transport, async_transport)
176
+ self.audit_log = AuditLog(Path(audit_log) if audit_log else self.identity_path.with_suffix(".audit.jsonl"),
177
+ self.identity.keys, self.name)
178
+
179
+ # ------------------------------------------------------------------ setup
180
+
181
+ def _load_identity(self, server_url, token, key_store, hybrid, timeout, transport, async_transport):
182
+ try:
183
+ identity = ids.load(self.identity_path)
184
+ except FileNotFoundError:
185
+ identity = None
186
+ if self.mode == "standalone":
187
+ if identity is None:
188
+ identity = ids.Identity(keys=Keys.generate(hybrid), name=self.name)
189
+ ids.save(identity, self.identity_path, key_store)
190
+ return identity
191
+
192
+ server = (server_url or (identity.server if identity else None) or "").rstrip("/")
193
+ if not server:
194
+ raise ProvenzaConfigError("connected mode needs server_url (or PROVENZA_URL)")
195
+ if identity is not None and identity.server and identity.server.rstrip("/") != server:
196
+ # never present this agent's key to a server it was not enrolled with
197
+ raise ProvenzaConfigError(f"{self.identity_path} belongs to {identity.server}, not {server}")
198
+ if identity is None or identity.agent_id is None:
199
+ if not token:
200
+ raise ProvenzaConfigError("this agent is not enrolled: pass enrollment_token (or PROVENZA_TOKEN), "
201
+ "issued in Provenza under Agents -> New agent")
202
+ client = Client(server, timeout=timeout, transport=transport, async_transport=async_transport)
203
+ identity = ids.enroll(client, token, name=self.name, hybrid=hybrid)
204
+ ids.save(identity, self.identity_path, key_store)
205
+ self._client = Client(server, identity.api_key, timeout=timeout, transport=transport,
206
+ async_transport=async_transport)
207
+ return identity
208
+
209
+ @property
210
+ def agent_id(self) -> Optional[int]:
211
+ return self.identity.agent_id
212
+
213
+ @property
214
+ def server_url(self) -> Optional[str]:
215
+ return self._client.server_url if self._client is not None else None
216
+
217
+ def credentials(self) -> Dict[str, str]:
218
+ """(base server URL, agent key) for clients that talk to Provenza's
219
+ gateways themselves (integrations.openai / integrations.mcp)."""
220
+ client = self._connected()
221
+ if not client.api_key:
222
+ raise ProvenzaConfigError("this agent has no API key")
223
+ return {"server_url": client.server_url, "api_key": client.api_key}
224
+
225
+ @property
226
+ def fingerprint(self) -> str:
227
+ """Give this to whoever verifies the agent's signatures."""
228
+ return self.identity.fingerprint
229
+
230
+ @contextlib.contextmanager
231
+ def chain(self, chain_id: Optional[int]):
232
+ """Tool calls inside act within this delegation chain."""
233
+ token = _chain.set(chain_id)
234
+ try:
235
+ yield
236
+ finally:
237
+ _chain.reset(token)
238
+
239
+ # ------------------------------------------------------------------ protocol
240
+
241
+ def _check_body(self, tool: ToolSpec, input: Dict[str, Any], chain_id: Optional[int]) -> Dict[str, Any]:
242
+ body = {"agent_id": self.agent_id, "chain_id": chain_id, "action_type": tool.action_type,
243
+ "tool_name": tool.name, "input": input}
244
+ if tool.version:
245
+ body["tool_version"] = tool.version
246
+ if tool.digest:
247
+ body["tool_digest"] = tool.digest
248
+ return body
249
+
250
+ @staticmethod
251
+ def _check_of(res: Dict[str, Any], tool: ToolSpec, input: Dict[str, Any], chain_id: Optional[int]) -> Check:
252
+ return Check(check_id=res["check_id"], decision=res["decision"], reason=res.get("reason") or "",
253
+ tool=tool.name, action_type=tool.action_type, input=input, chain_id=chain_id,
254
+ incident_type=res.get("incident_type"), policy_id=res.get("policy_id"))
255
+
256
+ def _record_body(self, chk: Check, output: Optional[Dict[str, Any]], duration_ms: Optional[int]) -> Dict[str, Any]:
257
+ payload = {"check_id": chk.check_id, "agent_id": self.agent_id, "chain_id": chk.chain_id,
258
+ "action_type": chk.action_type, "tool_name": chk.tool,
259
+ "input_sha256": content_hash(chk.input), "output_sha256": content_hash(output)}
260
+ sig, pq = self.identity.keys.sign(payload)
261
+ return {"agent_id": self.agent_id, "chain_id": chk.chain_id, "action_type": chk.action_type,
262
+ "tool_name": chk.tool, "input": chk.input, "output": output, "duration_ms": duration_ms,
263
+ "check_id": chk.check_id, "signature": sig, "pq_signature": pq}
264
+
265
+ def _connected(self) -> Client:
266
+ if self._client is None:
267
+ raise ProvenzaConfigError("this needs connected mode")
268
+ return self._client
269
+
270
+ def check(self, tool: str, input: Dict[str, Any], *, action_type: str = "tool_call",
271
+ chain_id: Optional[int] = None) -> Check:
272
+ """Ask before doing something that is not a decorated tool."""
273
+ spec, inp = ToolSpec(tool, action_type), _json_value(input, "input")
274
+ cid = chain_id if chain_id is not None else _chain.get()
275
+ res = self._connected().post("/agents/actions/check", self._check_body(spec, inp, cid))
276
+ return self._check_of(res, spec, inp, cid)
277
+
278
+ async def acheck(self, tool: str, input: Dict[str, Any], *, action_type: str = "tool_call",
279
+ chain_id: Optional[int] = None) -> Check:
280
+ spec, inp = ToolSpec(tool, action_type), _json_value(input, "input")
281
+ cid = chain_id if chain_id is not None else _chain.get()
282
+ res = await self._connected().apost("/agents/actions/check", self._check_body(spec, inp, cid))
283
+ return self._check_of(res, spec, inp, cid)
284
+
285
+ def record(self, check: Check, output: Any = None, duration_ms: Optional[int] = None) -> Dict[str, Any]:
286
+ """Record what was done under a check (once). Retries a server that
287
+ is down; a 409 on a retry means an earlier attempt got through."""
288
+ body = self._record_body(check, _output(output) if not isinstance(output, dict) else
289
+ _json_value(output, "output"), duration_ms)
290
+ for attempt, pause in enumerate((0.0, *RECORD_RETRIES)):
291
+ if pause:
292
+ time.sleep(pause)
293
+ try:
294
+ return self._connected().post("/agents/actions/record", body)
295
+ except ProvenzaUnavailable:
296
+ if attempt == len(RECORD_RETRIES):
297
+ raise
298
+ except ProvenzaRequestError as exc:
299
+ if exc.status == 409 and attempt > 0:
300
+ return {"id": None, "check_id": check.check_id, "note": "recorded by an earlier attempt"}
301
+ raise
302
+ raise AssertionError("unreachable") # pragma: no cover
303
+
304
+ async def arecord(self, check: Check, output: Any = None, duration_ms: Optional[int] = None) -> Dict[str, Any]:
305
+ body = self._record_body(check, _output(output) if not isinstance(output, dict) else
306
+ _json_value(output, "output"), duration_ms)
307
+ for attempt, pause in enumerate((0.0, *RECORD_RETRIES)):
308
+ if pause:
309
+ await asyncio.sleep(pause)
310
+ try:
311
+ return await self._connected().apost("/agents/actions/record", body)
312
+ except ProvenzaUnavailable:
313
+ if attempt == len(RECORD_RETRIES):
314
+ raise
315
+ except ProvenzaRequestError as exc:
316
+ if exc.status == 409 and attempt > 0:
317
+ return {"id": None, "check_id": check.check_id, "note": "recorded by an earlier attempt"}
318
+ raise
319
+ raise AssertionError("unreachable") # pragma: no cover
320
+
321
+ def delegate(self, to_agent_id: int, task: str, capabilities: Iterable[str] = (), *,
322
+ tools: Optional[Iterable[str]] = None, expires_in: Optional[int] = None,
323
+ chain_id: Optional[int] = None) -> Dict[str, Any]:
324
+ """Hand a task and a subset of this agent's rights to another agent
325
+ (signed, single-use nonce). Returns the server's answer with chain_id."""
326
+ return self._connected().post(f"/agents/{self.agent_id}/delegate",
327
+ self._delegation_body(to_agent_id, task, capabilities, tools, expires_in, chain_id))
328
+
329
+ async def adelegate(self, to_agent_id: int, task: str, capabilities: Iterable[str] = (), *,
330
+ tools: Optional[Iterable[str]] = None, expires_in: Optional[int] = None,
331
+ chain_id: Optional[int] = None) -> Dict[str, Any]:
332
+ return await self._connected().apost(f"/agents/{self.agent_id}/delegate",
333
+ self._delegation_body(to_agent_id, task, capabilities, tools, expires_in,
334
+ chain_id))
335
+
336
+ def _delegation_body(self, to_agent_id, task, capabilities, tools, expires_in, chain_id) -> Dict[str, Any]:
337
+ caps = list(capabilities)
338
+ tools = list(tools) if tools is not None else None
339
+ cid = chain_id if chain_id is not None else _chain.get()
340
+ payload = {"from_agent_id": self.agent_id, "to_agent_id": to_agent_id, "task": task,
341
+ "delegated_capabilities": sorted(caps), "chain_id": cid, "nonce": secrets.token_hex(16),
342
+ "issued_at": int(time.time()), "expires_in": expires_in}
343
+ if tools is not None:
344
+ payload["delegated_tools"] = sorted(set(tools))
345
+ sig, pq = self.identity.keys.sign(payload)
346
+ body = {k: payload[k] for k in ("to_agent_id", "task", "chain_id", "nonce", "issued_at", "expires_in")}
347
+ body.update(delegated_capabilities=caps, delegated_tools=tools, signature=sig, pq_signature=pq)
348
+ return body
349
+
350
+ # ------------------------------------------------------------------ tools
351
+
352
+ def tool(self, fn: Optional[F] = None, *, name: Optional[str] = None, action_type: str = "tool_call",
353
+ version: Optional[str] = None, digest: Optional[str] = None):
354
+ """Decorate a function (sync or async) so every call is governed."""
355
+ def decorate(f: F) -> F:
356
+ spec = ToolSpec(name or f.__name__, action_type, version, digest)
357
+ if inspect.iscoroutinefunction(f):
358
+ @functools.wraps(f)
359
+ async def async_wrapper(*args, **kwargs):
360
+ return await self._arun(spec, f, args, kwargs)
361
+ async_wrapper.provenza_tool = spec
362
+ return async_wrapper # type: ignore[return-value]
363
+
364
+ @functools.wraps(f)
365
+ def wrapper(*args, **kwargs):
366
+ return self._run(spec, f, args, kwargs)
367
+ wrapper.provenza_tool = spec
368
+ return wrapper # type: ignore[return-value]
369
+
370
+ return decorate(fn) if fn is not None else decorate
371
+
372
+ def _local_refusal(self, spec: ToolSpec, inp: Dict[str, Any]) -> None:
373
+ if self.allowed_tools is not None and spec.name not in self.allowed_tools:
374
+ reason = "not in this agent's allowed_tools (standalone)"
375
+ self.audit_log.append(status="denied", tool=spec.name, action_type=spec.action_type,
376
+ input_sha256=content_hash(inp), reason=reason)
377
+ raise ProvenzaDenied(spec.name, reason)
378
+
379
+ def _local(self, spec: ToolSpec, inp, status: str, output, duration_ms: int, reason: str = "") -> None:
380
+ self.audit_log.append(status=status, tool=spec.name, action_type=spec.action_type,
381
+ input_sha256=content_hash(inp), output_sha256=content_hash(output),
382
+ duration_ms=duration_ms, reason=reason)
383
+
384
+ def _refused(self, spec: ToolSpec, chk: Check, action: Optional[Dict[str, Any]]) -> ProvenzaDenied:
385
+ cls = ProvenzaApprovalRequired if chk.decision == "pending_approval" else ProvenzaDenied
386
+ return cls(spec.name, chk.reason, chk.decision, chk.incident_type, chk.check_id,
387
+ (action or {}).get("id"))
388
+
389
+ def _gap(self, spec: ToolSpec, chk: Check, output, duration_ms: int, exc: Exception) -> None:
390
+ self.audit_log.append(status="unrecorded", tool=spec.name, action_type=spec.action_type,
391
+ check_id=chk.check_id, input_sha256=content_hash(chk.input),
392
+ output_sha256=content_hash(output), duration_ms=duration_ms,
393
+ reason=f"{type(exc).__name__}: {str(exc)[:200]}")
394
+ warnings.warn(f"{spec.name} ran but could not be recorded on the server ({exc}); the gap is in "
395
+ f"{self.audit_log.path}", ProvenzaWarning, stacklevel=3)
396
+
397
+ # the one governed path: everything above and every integration ends here
398
+
399
+ def call(self, tool: str, arguments: Dict[str, Any], fn: Callable[[], Any], *,
400
+ action_type: str = "tool_call") -> Any:
401
+ """Govern one call whose arguments you already have as a dict -
402
+ check, run fn() only if allowed, record. What the integrations use."""
403
+ return self._govern(ToolSpec(tool, action_type), _json_value(arguments, "tool arguments"), fn)
404
+
405
+ async def acall(self, tool: str, arguments: Dict[str, Any], fn: Callable[[], Any], *,
406
+ action_type: str = "tool_call") -> Any:
407
+ """call() for a coroutine: fn() returns an awaitable."""
408
+ return await self._agovern(ToolSpec(tool, action_type), _json_value(arguments, "tool arguments"), fn)
409
+
410
+ def _run(self, spec: ToolSpec, f: Callable, args: tuple, kwargs: dict) -> Any:
411
+ return self._govern(spec, _arguments(f, args, kwargs), lambda: f(*args, **kwargs))
412
+
413
+ async def _arun(self, spec: ToolSpec, f: Callable, args: tuple, kwargs: dict) -> Any:
414
+ return await self._agovern(spec, _arguments(f, args, kwargs), lambda: f(*args, **kwargs))
415
+
416
+ def _govern(self, spec: ToolSpec, inp: Dict[str, Any], fn: Callable[[], Any]) -> Any:
417
+ if self.mode == "standalone":
418
+ self._local_refusal(spec, inp)
419
+ return self._timed_local(spec, fn, inp, "recorded")
420
+ try:
421
+ res = self._connected().post("/agents/actions/check", self._check_body(spec, inp, _chain.get()))
422
+ except ProvenzaUnavailable:
423
+ if not self.fail_open:
424
+ raise
425
+ warnings.warn(f"{spec.name}: Provenza unreachable, running unchecked (fail_open)", ProvenzaWarning,
426
+ stacklevel=4)
427
+ return self._timed_local(spec, fn, inp, "unchecked")
428
+ chk = self._check_of(res, spec, inp, _chain.get())
429
+ if not chk.allowed:
430
+ raise self._refused(spec, chk, self._try_record(spec, chk, None, None))
431
+ started = time.monotonic()
432
+ try:
433
+ result = fn()
434
+ except Exception as exc:
435
+ self._record_after(spec, chk, {"error": type(exc).__name__}, int((time.monotonic() - started) * 1000))
436
+ raise
437
+ self._record_after(spec, chk, _output(result), int((time.monotonic() - started) * 1000))
438
+ return result
439
+
440
+ def _record_after(self, spec, chk, output, duration_ms) -> None:
441
+ if self.record_mode == "background":
442
+ if self._recorder is None:
443
+ self._recorder = _Recorder(self._try_record)
444
+ self._recorder.put(spec, chk, output, duration_ms)
445
+ else:
446
+ self._try_record(spec, chk, output, duration_ms)
447
+
448
+ async def _agovern(self, spec: ToolSpec, inp: Dict[str, Any], fn: Callable[[], Any]) -> Any:
449
+ if self.mode == "standalone":
450
+ self._local_refusal(spec, inp)
451
+ started = time.monotonic()
452
+ result = await fn()
453
+ self._local(spec, inp, "recorded", _output(result), int((time.monotonic() - started) * 1000))
454
+ return result
455
+ try:
456
+ res = await self._connected().apost("/agents/actions/check", self._check_body(spec, inp, _chain.get()))
457
+ except ProvenzaUnavailable:
458
+ if not self.fail_open:
459
+ raise
460
+ warnings.warn(f"{spec.name}: Provenza unreachable, running unchecked (fail_open)", ProvenzaWarning,
461
+ stacklevel=4)
462
+ started = time.monotonic()
463
+ result = await fn()
464
+ self._local(spec, inp, "unchecked", _output(result), int((time.monotonic() - started) * 1000))
465
+ return result
466
+ chk = self._check_of(res, spec, inp, _chain.get())
467
+ if not chk.allowed:
468
+ raise self._refused(spec, chk, await self._atry_record(spec, chk, None, None))
469
+ started = time.monotonic()
470
+ try:
471
+ result = await fn()
472
+ except Exception as exc:
473
+ await self._arecord_after(spec, chk, {"error": type(exc).__name__},
474
+ int((time.monotonic() - started) * 1000))
475
+ raise
476
+ await self._arecord_after(spec, chk, _output(result), int((time.monotonic() - started) * 1000))
477
+ return result
478
+
479
+ async def _arecord_after(self, spec, chk, output, duration_ms) -> None:
480
+ if self.record_mode == "background":
481
+ task = asyncio.get_running_loop().create_task(self._atry_record(spec, chk, output, duration_ms))
482
+ self._pending.add(task)
483
+ task.add_done_callback(self._pending.discard)
484
+ else:
485
+ await self._atry_record(spec, chk, output, duration_ms)
486
+
487
+ def _timed_local(self, spec: ToolSpec, fn: Callable[[], Any], inp, status: str) -> Any:
488
+ started = time.monotonic()
489
+ result = fn()
490
+ self._local(spec, inp, status, _output(result), int((time.monotonic() - started) * 1000))
491
+ return result
492
+
493
+ def _try_record(self, spec, chk, output, duration_ms) -> Optional[Dict[str, Any]]:
494
+ try:
495
+ return self.record(chk, output, duration_ms)
496
+ except (ProvenzaUnavailable, ProvenzaRequestError) as exc:
497
+ self._gap(spec, chk, output, duration_ms or 0, exc)
498
+ return None
499
+
500
+ async def _atry_record(self, spec, chk, output, duration_ms) -> Optional[Dict[str, Any]]:
501
+ try:
502
+ return await self.arecord(chk, output, duration_ms)
503
+ except (ProvenzaUnavailable, ProvenzaRequestError) as exc:
504
+ self._gap(spec, chk, output, duration_ms or 0, exc)
505
+ return None
506
+
507
+ # ------------------------------------------------------------------ lifecycle
508
+
509
+ def flush(self, timeout: float = 30.0) -> bool:
510
+ """Wait for background records of sync tools; True when all were sent
511
+ (or written as gaps)."""
512
+ return self._recorder.drain(timeout) if self._recorder is not None else True
513
+
514
+ async def aflush(self) -> None:
515
+ """Wait for background records of async tools."""
516
+ if self._pending:
517
+ await asyncio.gather(*list(self._pending), return_exceptions=True)
518
+
519
+ def close(self) -> None:
520
+ self.flush()
521
+ if self._client is not None:
522
+ self._client.close()
523
+
524
+ async def aclose(self) -> None:
525
+ await self.aflush()
526
+ if self._client is not None:
527
+ await self._client.aclose()
528
+
529
+ def __enter__(self) -> "Agent":
530
+ return self
531
+
532
+ def __exit__(self, *exc) -> None:
533
+ self.close()
534
+
535
+ async def __aenter__(self) -> "Agent":
536
+ return self
537
+
538
+ async def __aexit__(self, *exc) -> None:
539
+ await self.aclose()
540
+ self.close()