aid-runtime-python 0.1.162__py3-none-any.whl → 0.1.164__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.
aid_runtime/__init__.py CHANGED
@@ -29,12 +29,15 @@ from aid_runtime.agents import (
29
29
  AgentCheckpoint,
30
30
  AgentDefinition,
31
31
  AgentRuntime,
32
+ CheckpointRefusalError,
33
+ CheckpointSigner,
32
34
  FileMemoryStore,
33
35
  HumanApproval,
34
36
  HumanDecision,
35
37
  InProcessMemoryStore,
36
38
  MemoryDefinition,
37
39
  MemoryStore,
40
+ NonceStore,
38
41
  PendingApproval,
39
42
  Principal,
40
43
  RunResult,
@@ -44,6 +47,8 @@ from aid_runtime.agents import (
44
47
  StepRecord,
45
48
  ThreadMemory,
46
49
  ToolSpec,
50
+ nonce_store_from_env,
51
+ signer_from_env,
47
52
  )
48
53
  from aid_runtime.cache import CompletionCache, cache_key_for
49
54
  from aid_runtime.concurrency import ConcurrencyLimiter
@@ -351,7 +356,7 @@ from aid_runtime.types import (
351
356
  )
352
357
 
353
358
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
354
- __version__ = "0.1.162"
359
+ __version__ = "0.1.164"
355
360
 
356
361
  __all__ = [
357
362
  "AGENT_LABEL",
@@ -409,6 +414,8 @@ __all__ = [
409
414
  "Capability",
410
415
  "CapabilityMismatchError",
411
416
  "CaseOutcome",
417
+ "CheckpointRefusalError",
418
+ "CheckpointSigner",
412
419
  "Chunk",
413
420
  "Chunker",
414
421
  "ChunkingSpec",
@@ -495,6 +502,7 @@ __all__ = [
495
502
  "ModelCacheConfig",
496
503
  "ModelGateway",
497
504
  "ModelSpec",
505
+ "NonceStore",
498
506
  "NormalizedContains",
499
507
  "OpenAICompatibleEmbedder",
500
508
  "OpenAICompatibleProvider",
@@ -627,6 +635,7 @@ __all__ = [
627
635
  "local_trace_enabled",
628
636
  "map_step",
629
637
  "metric_names",
638
+ "nonce_store_from_env",
630
639
  "normalize",
631
640
  "open_connector",
632
641
  "parallel",
@@ -652,6 +661,7 @@ __all__ = [
652
661
  "rrf_score",
653
662
  "run_evaluation",
654
663
  "run_structured",
664
+ "signer_from_env",
655
665
  "similarity",
656
666
  "sync_support",
657
667
  "tokenize",
@@ -60,8 +60,21 @@ from aid_runtime.agents.memory import (
60
60
  render_context,
61
61
  )
62
62
  from aid_runtime.agents.policy import Principal, evaluate_policy, policy_source
63
+ from aid_runtime.agents.resume import (
64
+ DEFAULT_CHECKPOINT_TTL_MINUTES,
65
+ CheckpointRefusalError,
66
+ CheckpointSigner,
67
+ InProcessNonceStore,
68
+ NonceStore,
69
+ PostgresNonceStore,
70
+ SqliteNonceStore,
71
+ nonce_store_for,
72
+ nonce_store_from_env,
73
+ signer_from_env,
74
+ )
63
75
  from aid_runtime.agents.state import (
64
76
  AgentCheckpoint,
77
+ CheckpointIntegrity,
65
78
  HumanDecision,
66
79
  PendingApproval,
67
80
  RunResult,
@@ -71,6 +84,7 @@ from aid_runtime.agents.state import (
71
84
  )
72
85
 
73
86
  __all__ = [
87
+ "DEFAULT_CHECKPOINT_TTL_MINUTES",
74
88
  "DETECTORS",
75
89
  "GUARDRAIL_ACTIONS",
76
90
  "GUARDRAIL_STAGES",
@@ -82,6 +96,9 @@ __all__ = [
82
96
  "AgentRuntime",
83
97
  "BedrockGuardrailClient",
84
98
  "BedrockGuardrailPolicy",
99
+ "CheckpointIntegrity",
100
+ "CheckpointRefusalError",
101
+ "CheckpointSigner",
85
102
  "DecisionAsker",
86
103
  "DecisionDefinition",
87
104
  "Detection",
@@ -96,16 +113,20 @@ __all__ = [
96
113
  "HumanApproval",
97
114
  "HumanDecision",
98
115
  "InProcessMemoryStore",
116
+ "InProcessNonceStore",
99
117
  "ManagedGuardrailSettings",
100
118
  "MemoryDefinition",
101
119
  "MemoryStore",
102
120
  "ModelArmorGuardrailClient",
103
121
  "ModelArmorGuardrailSettings",
122
+ "NonceStore",
104
123
  "PendingApproval",
124
+ "PostgresNonceStore",
105
125
  "Principal",
106
126
  "RunResult",
107
127
  "RunStatus",
108
128
  "RuntimeSpec",
129
+ "SqliteNonceStore",
109
130
  "StepKind",
110
131
  "StepRecord",
111
132
  "ThreadMemory",
@@ -115,6 +136,9 @@ __all__ = [
115
136
  "evaluate_policy",
116
137
  "managed_guardrail_settings",
117
138
  "model_armor_settings",
139
+ "nonce_store_for",
140
+ "nonce_store_from_env",
118
141
  "policy_source",
119
142
  "render_context",
143
+ "signer_from_env",
120
144
  ]
@@ -68,6 +68,11 @@ from aid_runtime.agents.policy import (
68
68
  evaluate_policy,
69
69
  policy_source,
70
70
  )
71
+ from aid_runtime.agents.resume import (
72
+ CheckpointSigner,
73
+ InProcessNonceStore,
74
+ NonceStore,
75
+ )
71
76
  from aid_runtime.agents.state import (
72
77
  AgentCheckpoint,
73
78
  HumanDecision,
@@ -193,6 +198,8 @@ class AgentRuntime:
193
198
  memory_store: MemoryStore | None = None,
194
199
  tracer: Tracer | None = None,
195
200
  limiter: ConcurrencyLimiter | None = None,
201
+ signer: CheckpointSigner | None = None,
202
+ nonces: NonceStore | None = None,
196
203
  ) -> None:
197
204
  self._spec = spec
198
205
  self._gateway = gateway
@@ -202,6 +209,11 @@ class AgentRuntime:
202
209
  memory_store if memory_store is not None else InProcessMemoryStore()
203
210
  )
204
211
  self._tracer = tracer
212
+ # A run that pauses hands its checkpoint to whoever called `run`, so the app that
213
+ # exposes a resume route must sign. Left `None`, the loop behaves exactly as it did
214
+ # before: a library embedding it directly is not silently given a key.
215
+ self._signer = signer
216
+ self._nonces: NonceStore = nonces if nonces is not None else InProcessNonceStore()
205
217
  self._guardrails = GuardrailEngine(spec.guardrails, decisions=spec.decisions)
206
218
  self._tools_by_name: dict[str, ToolSpec] = {
207
219
  definition.name: definition for definition in spec.tools.values()
@@ -220,6 +232,8 @@ class AgentRuntime:
220
232
  ledger: CostLedger | None = None,
221
233
  budget: Budget | None = None,
222
234
  tracer: Tracer | None = None,
235
+ signer: CheckpointSigner | None = None,
236
+ nonces: NonceStore | None = None,
223
237
  ) -> AgentRuntime:
224
238
  """Build a runtime from an emitted IR document.
225
239
 
@@ -240,6 +254,8 @@ class AgentRuntime:
240
254
  memory_store=memory_store,
241
255
  tracer=tracer,
242
256
  limiter=limiter,
257
+ signer=signer,
258
+ nonces=nonces,
243
259
  )
244
260
 
245
261
  @property
@@ -278,7 +294,7 @@ class AgentRuntime:
278
294
  try:
279
295
  outcome = await self._drive(
280
296
  frame,
281
- principal=principal if principal is not None else Principal(),
297
+ principal=principal if principal is not None else Principal.unauthenticated(),
282
298
  memory_key=key,
283
299
  )
284
300
  except BaseException:
@@ -296,6 +312,7 @@ class AgentRuntime:
296
312
  principal: Principal | None = None,
297
313
  ) -> RunResult:
298
314
  """Continue a paused run from its checkpoint, with a human's answer."""
315
+ checkpoint = await self._accept(checkpoint)
299
316
  resolved = HumanDecision(decision)
300
317
  self._restore_ledger(checkpoint)
301
318
  start_cost = self._gateway.ledger.cost_usd
@@ -304,7 +321,7 @@ class AgentRuntime:
304
321
  outcome = await self._resume(
305
322
  checkpoint,
306
323
  resolved,
307
- principal if principal is not None else Principal(),
324
+ principal if principal is not None else Principal.unauthenticated(),
308
325
  )
309
326
  except BaseException:
310
327
  # Same rule as `run`: a resumed run that fails has been billed too.
@@ -312,6 +329,18 @@ class AgentRuntime:
312
329
  raise
313
330
  return self._wrap(outcome, start_cost, start_tokens)
314
331
 
332
+ async def _accept(self, checkpoint: AgentCheckpoint) -> AgentCheckpoint:
333
+ """Refuse a checkpoint this app did not issue, has expired, or already spent.
334
+
335
+ Called before anything the checkpoint carries is read, so a tampered pending call
336
+ is never authorized, priced or observed. A runtime built without a signer keeps the
337
+ pre-signing behaviour, which is what a direct library embedder already had.
338
+ """
339
+ if self._signer is None:
340
+ return checkpoint
341
+ await self._signer.accept(checkpoint, self._nonces)
342
+ return checkpoint
343
+
315
344
  async def _resume(
316
345
  self,
317
346
  checkpoint: AgentCheckpoint,
@@ -1057,7 +1086,7 @@ class AgentRuntime:
1057
1086
  channel = approval.channel
1058
1087
  else:
1059
1088
  channel = _TOOL_CONFIRMATION
1060
- return AgentCheckpoint(
1089
+ checkpoint = AgentCheckpoint(
1061
1090
  agent_id=frame.agent.id,
1062
1091
  step=frame.step,
1063
1092
  messages=tuple(frame.messages),
@@ -1076,6 +1105,10 @@ class AgentRuntime:
1076
1105
  escalation=escalation,
1077
1106
  guardrails=tuple(frame.guardrails),
1078
1107
  )
1108
+ # Signed here rather than at the route, so every pause path -- approval, tool
1109
+ # confirmation, guardrail escalation, and the nested caller of a delegate -- is
1110
+ # issued by the same key. A second signing site is a second thing to forget.
1111
+ return checkpoint if self._signer is None else self._signer.sign(checkpoint)
1079
1112
 
1080
1113
  def _restore_ledger(self, checkpoint: AgentCheckpoint) -> None:
1081
1114
  """Carry a pause's spend into this process's ledger before resuming.
@@ -36,14 +36,23 @@ _LOGICAL = frozenset({"and", "or"})
36
36
  class Principal:
37
37
  """Who a policy is evaluated for.
38
38
 
39
- Defaults are the anonymous-but-authenticated caller an app with no auth layer
40
- has: ``isAuthenticated()`` is true and both role and scope sets are empty, so
41
- ``hasRole('admin')`` is false rather than undefined.
39
+ ``authenticated`` defaults to **false** on purpose. A default that is authenticated is
40
+ a silent authorization bug: ``isAuthenticated()`` is the weakest policy the security
41
+ gate accepts on a mutating tool, so a caller the app never identified would satisfy it.
42
+ :meth:`unauthenticated` is the caller an app with no auth layer has -- no roles, no
43
+ scopes, and ``isAuthenticated()`` false, which is the closed answer. Pass
44
+ ``authenticated=True`` only from code that actually verified a token.
42
45
  """
43
46
 
44
47
  roles: frozenset[str] = frozenset()
45
48
  scopes: frozenset[str] = frozenset()
46
- authenticated: bool = True
49
+ authenticated: bool = False
50
+
51
+ @classmethod
52
+ def unauthenticated(cls) -> Principal:
53
+ """The caller a route seeds when nothing verified a token: anonymous, fail-closed."""
54
+
55
+ return cls(authenticated=False)
47
56
 
48
57
 
49
58
  def evaluate_policy(node: Mapping[str, Any], principal: Principal) -> bool:
@@ -0,0 +1,402 @@
1
+ """Checkpoint integrity: signing, expiry and replay refusal for a paused run.
2
+
3
+ A paused run is continued by handing the checkpoint back to ``POST /agents/resume``, so
4
+ the checkpoint *is* the capability. Before this module it was a bearer capability with no
5
+ integrity: the body was parsed into :class:`AgentCheckpoint` and replayed, so anyone
6
+ holding one could edit an approval decision or swap the pending tool-call arguments and
7
+ the loop would execute the edited call. A signature is what turns "a body shaped like a
8
+ checkpoint" into "a checkpoint this app issued".
9
+
10
+ Three properties are enforced here, and each has its own refusal reason:
11
+
12
+ * ``"tampered"`` -- the HMAC does not match the payload the signer covered. The signature
13
+ covers the *whole* checkpoint minus the signature itself, so a flipped approval
14
+ decision, a swapped argument and an extended expiry all fail the same check rather than
15
+ needing a field-by-field audit.
16
+ * ``"expired"`` -- ``expires_at`` (inside the signed payload, so it cannot be extended
17
+ without breaking the signature) is in the past.
18
+ * ``"replayed"`` -- the nonce was already claimed. Claiming is a store operation rather
19
+ than an in-memory check because a replay across two processes is the interesting case.
20
+
21
+ The secret is a *value read from the environment*, never a value in the spec: the
22
+ generated app names the variable and this module fails loudly when it is unset, because a
23
+ missing secret must not degrade into "unsigned".
24
+
25
+ Replay durability is limited by the nonce store, and that limit is real rather than
26
+ theoretical: :class:`InProcessNonceStore` forgets on restart and does not span replicas.
27
+ :class:`SqliteNonceStore` and :class:`PostgresNonceStore` are durable and are what a
28
+ ``state.kind: sqlite`` or ``state.kind: postgres`` declaration gets; only a document that
29
+ declares no store at all falls back to the in-process one, which ``ir/resume-replay-weak``
30
+ states on the document rather than leaving to be discovered.
31
+
32
+ This module stores the *nonce*, not the run. The checkpoint for a paused run still returns
33
+ to the caller, so resuming after a restart is the application's to arrange -- see
34
+ :mod:`aid_runtime.agents.state`.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import asyncio
40
+ import hashlib
41
+ import hmac
42
+ import json
43
+ import os
44
+ import secrets
45
+ import sqlite3
46
+ import time
47
+ from dataclasses import dataclass, field
48
+ from pathlib import Path
49
+ from typing import Any, Protocol, runtime_checkable
50
+
51
+ from aid_runtime.agents.state import AgentCheckpoint, CheckpointIntegrity
52
+ from aid_runtime.errors import AidRuntimeError, ConfigurationError
53
+
54
+ __all__ = [
55
+ "DEFAULT_CHECKPOINT_TTL_MINUTES",
56
+ "CheckpointRefusalError",
57
+ "CheckpointSigner",
58
+ "InProcessNonceStore",
59
+ "NonceStore",
60
+ "PostgresNonceStore",
61
+ "SqliteNonceStore",
62
+ "checkpoint_payload",
63
+ "nonce_store_for",
64
+ "signer_from_env",
65
+ ]
66
+
67
+ #: How long a checkpoint stays usable. Short on purpose: a pause is a question asked of
68
+ #: a person in the same change window, not a durable queue.
69
+ DEFAULT_CHECKPOINT_TTL_MINUTES = 15
70
+
71
+
72
+ class CheckpointRefusalError(AidRuntimeError):
73
+ """A resume body this app will not honour, with a stable machine-readable reason.
74
+
75
+ ``reason`` is one of ``tampered``, ``expired``, ``replayed``, ``unsigned``. The
76
+ generated route maps it to a 403 and returns it as ``detail.reason``, so a caller can
77
+ tell "your checkpoint expired" from "your checkpoint was edited" without parsing
78
+ prose.
79
+ """
80
+
81
+ def __init__(self, reason: str, message: str) -> None:
82
+ super().__init__(message)
83
+ self.reason = reason
84
+
85
+
86
+ @runtime_checkable
87
+ class NonceStore(Protocol):
88
+ """Remembers which checkpoints have been spent.
89
+
90
+ ``claim`` must be atomic: two concurrent requests presenting the same checkpoint may
91
+ both reach it, and exactly one must be told ``True``. A store that reads then writes
92
+ would let both through.
93
+ """
94
+
95
+ async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
96
+ """``True`` the first time ``nonce`` is seen, ``False`` every time after.
97
+
98
+ ``now`` is the caller's clock, not this store's, so the pruning horizon and the
99
+ expiry the signer checked cannot disagree. A store that read the wall clock while
100
+ the signer took an injected one would prune a row before the replay check and
101
+ accept the replay.
102
+ """
103
+ ...
104
+
105
+
106
+ class InProcessNonceStore:
107
+ """A dict, and therefore a limit worth stating.
108
+
109
+ It is the honest default: a library must not decide where a host keeps its data. It
110
+ survives neither a restart nor a second replica, so a checkpoint replayed against
111
+ another worker is accepted there. ``profile: enterprise`` with no declared ``state``
112
+ is refused by ``ir/resume-replay-weak`` for exactly this reason.
113
+ """
114
+
115
+ def __init__(self) -> None:
116
+ self._seen: dict[str, int] = {}
117
+ self._lock = asyncio.Lock()
118
+
119
+ async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
120
+ async with self._lock:
121
+ self._seen = {seen: expiry for seen, expiry in self._seen.items() if expiry > now}
122
+ if nonce in self._seen:
123
+ return False
124
+ self._seen[nonce] = expires_at
125
+ return True
126
+
127
+
128
+ class SqliteNonceStore:
129
+ """A file, and therefore durable across a restart.
130
+
131
+ ``INSERT OR IGNORE`` is the atomic claim: SQLite reports whether it inserted, so two
132
+ workers sharing the file cannot both see ``True``. This is what a ``state.kind:
133
+ sqlite`` declaration is served by, because that declaration already means "a file on
134
+ a volume this process can reach".
135
+ """
136
+
137
+ def __init__(self, path: str | Path) -> None:
138
+ self._path = Path(path)
139
+ self._lock = asyncio.Lock()
140
+
141
+ async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
142
+ async with self._lock:
143
+ return await asyncio.to_thread(self._claim, nonce, expires_at, now)
144
+
145
+ def _claim(self, nonce: str, expires_at: int, now: int) -> bool:
146
+ self._path.parent.mkdir(parents=True, exist_ok=True)
147
+ with sqlite3.connect(self._path) as connection:
148
+ connection.execute("PRAGMA journal_mode=WAL")
149
+ connection.execute(
150
+ "CREATE TABLE IF NOT EXISTS checkpoint_nonce ("
151
+ "nonce TEXT PRIMARY KEY, expires_at INTEGER NOT NULL)"
152
+ )
153
+ connection.execute("DELETE FROM checkpoint_nonce WHERE expires_at <= ?", (now,))
154
+ cursor = connection.execute(
155
+ "INSERT OR IGNORE INTO checkpoint_nonce (nonce, expires_at) VALUES (?, ?)",
156
+ (nonce, expires_at),
157
+ )
158
+ return cursor.rowcount == 1
159
+
160
+
161
+ class PostgresNonceStore:
162
+ """The same claim in the database the document already names.
163
+
164
+ ``state.kind: postgres`` is the enterprise answer, so replay protection has to live
165
+ there rather than in a process: the whole point of a shared store is that the next
166
+ request may land anywhere. ``ON CONFLICT DO NOTHING`` plus ``RETURNING`` makes the
167
+ claim atomic in the database, which is the only place a claim can be atomic across
168
+ replicas.
169
+
170
+ The driver is optional, following the pgvector store: a deployment that never
171
+ declares `postgres` pays nothing for it, and one that does is told which extra to
172
+ install rather than discovering it at the first paused run.
173
+ """
174
+
175
+ def __init__(self, dsn: str) -> None:
176
+ self._dsn = dsn
177
+ self._lock = asyncio.Lock()
178
+ self._ready = False
179
+
180
+ async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
181
+ async with self._lock:
182
+ return await asyncio.to_thread(self._claim, nonce, expires_at, now)
183
+
184
+ def _claim(self, nonce: str, expires_at: int, now: int) -> bool:
185
+ psycopg = _load_psycopg()
186
+ with psycopg.connect(self._dsn) as connection:
187
+ if not self._ready:
188
+ connection.execute(
189
+ "CREATE TABLE IF NOT EXISTS checkpoint_nonce ("
190
+ "nonce TEXT PRIMARY KEY, expires_at BIGINT NOT NULL)"
191
+ )
192
+ self._ready = True
193
+ connection.execute("DELETE FROM checkpoint_nonce WHERE expires_at <= %s", (now,))
194
+ row = connection.execute(
195
+ "INSERT INTO checkpoint_nonce (nonce, expires_at) VALUES (%s, %s) "
196
+ "ON CONFLICT (nonce) DO NOTHING RETURNING nonce",
197
+ (nonce, expires_at),
198
+ ).fetchone()
199
+ return row is not None
200
+
201
+
202
+ def _load_psycopg() -> Any:
203
+ """Import the optional driver, or explain how to install it."""
204
+ try:
205
+ import psycopg
206
+ except ImportError as error:
207
+ raise ConfigurationError(
208
+ "a `state: postgres` declaration needs its driver for replay protection; "
209
+ "install it with `pip install aid-runtime-python[pgvector]` (the default "
210
+ "install omits psycopg)"
211
+ ) from error
212
+ return psycopg
213
+
214
+
215
+ def checkpoint_payload(checkpoint: AgentCheckpoint) -> bytes:
216
+ """The canonical bytes a signature covers.
217
+
218
+ Everything except the signature itself. That includes the integrity block's own
219
+ ``issued_at``, ``expires_at`` and ``nonce``: leaving those out would let a holder
220
+ move their deadline forward, and would let them swap the nonce of an already-spent
221
+ checkpoint to walk past replay protection. The pending calls, the approval channel
222
+ and the nested ``caller`` frames are inside too, so one signature binds all of them.
223
+ Sorted keys and no separator padding make the encoding reproducible in a second
224
+ process, which a signature requires.
225
+ """
226
+ document = checkpoint.model_dump(mode="json", exclude={"integrity": {"signature"}})
227
+ return json.dumps(
228
+ document,
229
+ sort_keys=True,
230
+ separators=(",", ":"),
231
+ ensure_ascii=False,
232
+ default=str,
233
+ ).encode("utf-8")
234
+
235
+
236
+ @dataclass(frozen=True, slots=True)
237
+ class CheckpointSigner:
238
+ """HMAC-SHA256 over :func:`checkpoint_payload`, plus the expiry it records.
239
+
240
+ ``secret`` is read from the environment by the caller; it is never a spec value. The
241
+ dataclass is frozen and holds no mutable state, so one instance can be shared across
242
+ requests and a test can construct its own without touching the process environment.
243
+ """
244
+
245
+ secret: str = field(repr=False)
246
+ ttl_seconds: int = DEFAULT_CHECKPOINT_TTL_MINUTES * 60
247
+
248
+ def __post_init__(self) -> None:
249
+ if not self.secret:
250
+ raise ValueError(
251
+ "CheckpointSigner needs a non-empty secret; an empty key would sign "
252
+ "every checkpoint identically"
253
+ )
254
+ if self.ttl_seconds <= 0:
255
+ raise ValueError("CheckpointSigner needs a positive ttl_seconds")
256
+
257
+ def _mac(self, payload: bytes) -> str:
258
+ return hmac.new(self.secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
259
+
260
+ def _digest(self, checkpoint: AgentCheckpoint) -> str:
261
+ """The MAC of ``checkpoint`` excluding only the signature field.
262
+
263
+ Signing and verifying both go through here, so the two sides cannot drift into
264
+ covering different bytes: a signature that verifies against a payload it was not
265
+ computed over would accept an edited checkpoint.
266
+ """
267
+ return self._mac(checkpoint_payload(checkpoint))
268
+
269
+ def sign(
270
+ self,
271
+ checkpoint: AgentCheckpoint,
272
+ *,
273
+ now: int | None = None,
274
+ nonce: str | None = None,
275
+ ) -> AgentCheckpoint:
276
+ """Return a copy of ``checkpoint`` carrying a fresh integrity block.
277
+
278
+ ``now`` and ``nonce`` exist for tests; production passes neither. The return is a
279
+ new frozen model, so a caller that kept the unsigned value still has it.
280
+ """
281
+ issued_at = int(time.time()) if now is None else int(now)
282
+ integrity = CheckpointIntegrity(
283
+ issued_at=issued_at,
284
+ expires_at=issued_at + self.ttl_seconds,
285
+ nonce=secrets.token_urlsafe(24) if nonce is None else nonce,
286
+ signature="",
287
+ )
288
+ unsigned = checkpoint.model_copy(update={"integrity": integrity})
289
+ signature = self._digest(unsigned)
290
+ return checkpoint.model_copy(
291
+ update={"integrity": integrity.model_copy(update={"signature": signature})}
292
+ )
293
+
294
+ def verify(self, checkpoint: AgentCheckpoint, *, now: int | None = None) -> CheckpointIntegrity:
295
+ """Check signature and expiry. Returns the integrity block, or raises.
296
+
297
+ Replay is *not* checked here: it needs the store, and therefore an ``await``.
298
+ :meth:`accept` is the full check a request handler wants.
299
+ """
300
+ integrity = checkpoint.integrity
301
+ if integrity is None:
302
+ raise CheckpointRefusalError(
303
+ "unsigned",
304
+ "this checkpoint carries no signature, so it was not issued by an app "
305
+ "built with checkpoint signing",
306
+ )
307
+ expected = self._digest(checkpoint)
308
+ if not hmac.compare_digest(expected, integrity.signature):
309
+ raise CheckpointRefusalError(
310
+ "tampered",
311
+ "this checkpoint's signature does not match its contents; it was edited "
312
+ "after it was issued",
313
+ )
314
+ moment = int(time.time()) if now is None else int(now)
315
+ if integrity.expires_at <= moment:
316
+ raise CheckpointRefusalError(
317
+ "expired",
318
+ f"this checkpoint expired at {integrity.expires_at}; a pause is valid for "
319
+ f"{self.ttl_seconds} seconds, so resume it sooner or start the run again",
320
+ )
321
+ return integrity
322
+
323
+ async def accept(
324
+ self,
325
+ checkpoint: AgentCheckpoint,
326
+ nonces: NonceStore,
327
+ *,
328
+ now: int | None = None,
329
+ ) -> CheckpointIntegrity:
330
+ """Signature, then expiry, then a one-time claim. Raises on any failure."""
331
+ moment = int(time.time()) if now is None else int(now)
332
+ integrity = self.verify(checkpoint, now=moment)
333
+ claimed = await nonces.claim(
334
+ nonce=integrity.nonce, expires_at=integrity.expires_at, now=moment
335
+ )
336
+ if not claimed:
337
+ raise CheckpointRefusalError(
338
+ "replayed",
339
+ "this checkpoint has already been spent; a resume is accepted once, so a "
340
+ "second presentation of the same checkpoint is refused",
341
+ )
342
+ return integrity
343
+
344
+
345
+ def signer_from_env(
346
+ variable: str, *, ttl_seconds: int = DEFAULT_CHECKPOINT_TTL_MINUTES * 60
347
+ ) -> CheckpointSigner:
348
+ """Build a signer from ``os.environ[variable]``, naming the variable when it is unset."""
349
+ secret = os.environ.get(variable, "")
350
+ if not secret:
351
+ raise ConfigurationError(
352
+ f"{variable} is not set, but this app signs its checkpoints; set it to a "
353
+ "high-entropy secret before serving the resume route"
354
+ )
355
+ return CheckpointSigner(secret=secret, ttl_seconds=ttl_seconds)
356
+
357
+
358
+ def nonce_store_for(kind: str | None, location: str | None) -> NonceStore:
359
+ """The most durable nonce store this build can offer for a declared ``state``.
360
+
361
+ Each declared kind claims the nonce where that declaration already points: ``sqlite``
362
+ names a file, ``postgres`` names a database. Both are durable across a restart and
363
+ across replicas. No declaration -- or a location that was not resolved from the
364
+ environment -- falls back to the in-process store, which ``ir/resume-replay-weak``
365
+ reports rather than this function hiding.
366
+ """
367
+ if location:
368
+ if kind == "sqlite":
369
+ return SqliteNonceStore(location)
370
+ if kind == "postgres":
371
+ return PostgresNonceStore(location)
372
+ return InProcessNonceStore()
373
+
374
+
375
+ def nonce_store_from_env(kind: str | None, variable: str | None) -> NonceStore:
376
+ """The store a generated app builds from the variable its ``state`` declaration names.
377
+
378
+ ``nonce_store_for`` falls back to the in-process store when it is handed no location,
379
+ which is right for a library and wrong here: the document declared a durable store, and
380
+ silently claiming the nonce in one worker would withdraw the replay protection the
381
+ build gate promised. So an unresolvable variable is refused by name, the same way
382
+ :func:`signer_from_env` refuses an unset signing key.
383
+
384
+ ``kind`` of ``None`` means the document declared no store at all -- ``standard`` with a
385
+ warning from ``ir/resume-replay-weak`` -- and then the in-process store is exactly what
386
+ was declared, so it is returned rather than refused.
387
+ """
388
+ if kind is None:
389
+ return InProcessNonceStore()
390
+ if variable is None:
391
+ raise ConfigurationError(
392
+ f"this app's state kind is {kind!r} but no urlEnv names where it lives; "
393
+ "declare state.urlEnv so a spent checkpoint can be claimed durably"
394
+ )
395
+ location = os.environ.get(variable, "")
396
+ if not location:
397
+ raise ConfigurationError(
398
+ f"{variable} is not set, but this app declares a {kind} state store; set it to "
399
+ "the connection string or file path, so a spent checkpoint is refused there "
400
+ "rather than only in the process that issued it"
401
+ )
402
+ return nonce_store_for(kind, location)
@@ -27,6 +27,7 @@ from aid_runtime.types import Message, ToolCall
27
27
 
28
28
  __all__ = [
29
29
  "AgentCheckpoint",
30
+ "CheckpointIntegrity",
30
31
  "HumanDecision",
31
32
  "PendingApproval",
32
33
  "RunResult",
@@ -87,6 +88,25 @@ class HumanDecision(StrEnum):
87
88
  REJECT = "reject"
88
89
 
89
90
 
91
+ class CheckpointIntegrity(BaseModel):
92
+ """What makes a checkpoint something this app issued rather than something it parsed.
93
+
94
+ Every field sits inside the signed payload, so ``expires_at`` cannot be extended
95
+ without breaking the signature and ``nonce`` cannot be swapped to replay a spent
96
+ checkpoint under a fresh identity. The signature itself does not cover itself.
97
+
98
+ Absent on a runtime built without a signer (a library embedding the loop directly);
99
+ the generated app always passes one, so an HTTP checkpoint is never unsigned.
100
+ """
101
+
102
+ model_config = ConfigDict(frozen=True, extra="forbid")
103
+
104
+ issued_at: int = Field(ge=0)
105
+ expires_at: int = Field(ge=0)
106
+ nonce: str = Field(min_length=1)
107
+ signature: str = ""
108
+
109
+
90
110
  class AgentCheckpoint(BaseModel):
91
111
  """Everything a paused agent needs to continue, and nothing that is derived."""
92
112
 
@@ -120,6 +140,10 @@ class AgentCheckpoint(BaseModel):
120
140
  # answer to release on approval, a `tool-call` one holds `calls` to execute.
121
141
  escalation: GuardrailEscalation | None = None
122
142
  guardrails: tuple[GuardrailRecord, ...] = ()
143
+ # Set by the signer when the app was built with one. It is part of the model rather
144
+ # than a sibling value on the wire so a resumed request carries it in the same body a
145
+ # caller already holds, and so `extra: forbid` keeps rejecting anything else.
146
+ integrity: CheckpointIntegrity | None = None
123
147
 
124
148
 
125
149
  class PendingApproval(BaseModel):
@@ -20,6 +20,13 @@ that pauses without supplying one is refused. The one exception is deliberate an
20
20
  ``ApprovalPolicy.APPROVE``/``REJECT`` exist for datasets that are testing something other
21
21
  than the approval, and they are named so a reader of the eval sees the scripted answer.
22
22
 
23
+ **It runs as a stated principal.** An agent's tools and approvals are policies over a
24
+ :class:`Principal`, so an eval that does not name the caller is evaluating an anonymous
25
+ one. That default is the closed answer and is kept deliberately: a mutating tool whose
26
+ policy is ``isAuthenticated()`` is refused for it, and a case written for a signed-in
27
+ caller has to say so. An eval that quietly ran as an authenticated caller would report a
28
+ tool path that production, behind an app which never verified a token, could not take.
29
+
23
30
  What this measures is worth stating plainly, since the module is named after the eval and
24
31
  not the model. When the provider is a recorded transcript or a scripted fake, the model's
25
32
  choices are fixed input: the run verifies that the machinery around the model obeys the
@@ -37,6 +44,7 @@ from enum import StrEnum
37
44
 
38
45
  from aid_runtime.agents.loop import AgentRuntime
39
46
  from aid_runtime.agents.memory import InProcessMemoryStore
47
+ from aid_runtime.agents.policy import Principal
40
48
  from aid_runtime.agents.state import HumanDecision, RunResult, RunStatus
41
49
  from aid_runtime.errors import ConfigurationError, EvalError
42
50
  from aid_runtime.evals.dataset import EvalCase
@@ -88,6 +96,7 @@ class AgentEvalRunner:
88
96
  tools: Iterable[Tool] = (),
89
97
  approval_policy: ApprovalPolicy | str = ApprovalPolicy.FROM_CASE,
90
98
  max_resumes: int = _DEFAULT_MAX_RESUMES,
99
+ principal: Principal | None = None,
91
100
  ) -> None:
92
101
  if not providers:
93
102
  raise ConfigurationError(
@@ -107,6 +116,9 @@ class AgentEvalRunner:
107
116
  self._tools = tuple(tools)
108
117
  self._policy = ApprovalPolicy(approval_policy)
109
118
  self._max_resumes = max_resumes
119
+ #: The caller this eval simulates. Anonymous unless the caller names one, so a
120
+ #: mutating tool is refused rather than silently permitted.
121
+ self._principal = principal if principal is not None else Principal.unauthenticated()
110
122
  #: Cumulative model spend, which is what ``evaluate_once`` differences to charge
111
123
  #: each case. Read from the ledger of the most recent run.
112
124
  self._cost_usd = 0.0
@@ -139,7 +151,7 @@ class AgentEvalRunner:
139
151
  runtime = self._runtime()
140
152
  before = runtime.gateway.ledger.cost_usd
141
153
  try:
142
- result = await runtime.run(self._agent_id, case.input)
154
+ result = await runtime.run(self._agent_id, case.input, principal=self._principal)
143
155
  result, approvals = await self._settle(runtime, case, result)
144
156
  finally:
145
157
  # Charged even when the run raised: a case stopped by a guardrail was billed,
@@ -205,7 +217,7 @@ class AgentEvalRunner:
205
217
  _Rejection(boundary=rejection.boundary, names=rejection.names - names)
206
218
  for rejection in rejections
207
219
  ]
208
- result = await runtime.resume(checkpoint, decision)
220
+ result = await runtime.resume(checkpoint, decision, principal=self._principal)
209
221
  return result, _Approvals(
210
222
  pauses=pauses,
211
223
  decisions=tuple(applied),
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.162
3
+ Version: 0.1.164
4
4
  Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
5
5
  Author: The AID Framework authors
6
6
  License-Expression: Apache-2.0
@@ -1,4 +1,4 @@
1
- aid_runtime/__init__.py,sha256=jFTM3HnzztNWpcicGQ4HeCMsG9E8Y0Sr1VYxiGojaHo,14951
1
+ aid_runtime/__init__.py,sha256=M-pbsJJ90R1eocStUMJd5hgLvWhOXzSc0Qqa73qYRo4,15187
2
2
  aid_runtime/cache.py,sha256=jhw_EBd9dfWEUzYeibOvIkVBqqiLUjqF5WKEPz9GkhE,6836
3
3
  aid_runtime/concurrency.py,sha256=z0tFQHw35ttFLKfazGBjCMPOLQOnUotE_OPpvR1piH4,2829
4
4
  aid_runtime/control.py,sha256=y6wPn0fqYJv0nVSsjzpzfiaq1Y7zBoMxCpdrEuqkfvg,17529
@@ -18,19 +18,20 @@ aid_runtime/telemetry.py,sha256=ykAXCL3XFi0yok3xr-fjD3oGvVycdfyrqJ8nGKC_ZHc,1287
18
18
  aid_runtime/tools.py,sha256=7LeaPI5aJioNe3vexUv94tvIRpOwxj1Ujt723qvO3UI,9906
19
19
  aid_runtime/tracing.py,sha256=zGZi7faB87IRv5873B-sV2d3J_JGiQS4pbHFqjTElUs,12247
20
20
  aid_runtime/types.py,sha256=91hwvBkjTkvCJ-WdQO3ezZZCyqzXmS7Ns1WP1m0EQzc,10916
21
- aid_runtime/agents/__init__.py,sha256=H_WKu9u0fvF56W7ccTByEv1RdayzwUfRzEKsXXDRr2A,3113
21
+ aid_runtime/agents/__init__.py,sha256=rf3k0hxHDO60S1TrON6d2-rTv1N8V4WvF47xsJ5bhE0,3709
22
22
  aid_runtime/agents/chat_model.py,sha256=fZdCmSpoECuBVGZE1s8NmT2erT33RhDuLh3yJM6kAJE,14808
23
23
  aid_runtime/agents/deep_agents.py,sha256=Eg_BLm2cg7T_tXSxR7ag8SEvTMCFBLHoIvln3BoWORw,26966
24
24
  aid_runtime/agents/engine.py,sha256=3cXCYY806URDblYD500cfw7873IoVCy8BH1d4h2YAsc,5789
25
25
  aid_runtime/agents/guardrails.py,sha256=0HhbToZBxPZHEDRLyD9BGS_jmV-TkKPGEhRynYxLXx8,32813
26
26
  aid_runtime/agents/ir.py,sha256=MgqX5gEkq7vimXojtSNb5MuVeTIZaWkZCFitxAqSAe0,32855
27
- aid_runtime/agents/loop.py,sha256=4NA3RokG_KogiXgOYJk3agEaci-s5Cv_bb5az3lOllQ,54237
27
+ aid_runtime/agents/loop.py,sha256=Byi7Z2OpnSKTJ2_7-elPXH-9WvoQUf5swPYYKk8oZhs,55984
28
28
  aid_runtime/agents/managed.py,sha256=SFyx6Rca2aoiMzA9q6B4Nfes6ZCjn_5_zN0SxzemIII,23247
29
29
  aid_runtime/agents/memory.py,sha256=6_D6k2bzAiR2euNvzr6HB28wsUUq-R-WTQc12gkB8ao,9156
30
- aid_runtime/agents/policy.py,sha256=ael0EW_hWfLu95rbqFMrR4WyqAPtgiSNvNw97xnthdw,6122
31
- aid_runtime/agents/state.py,sha256=4itT7BWv2JKSeWpRrDyxLguOOVnz9gGH_qgRdCbWCaw,6086
30
+ aid_runtime/agents/policy.py,sha256=IbJ9LQDPOumwup5K_eeyFAfCLFuMqEK6iSvBrM6o16Q,6610
31
+ aid_runtime/agents/resume.py,sha256=FM2SbsQZEOCKtHkEsu8riIcbsXYf9ieaioZ32UBN-to,17306
32
+ aid_runtime/agents/state.py,sha256=feXZtQeD3vcKpNUPsCXby0J15UqkoD4_Gi-aT3Up8RI,7174
32
33
  aid_runtime/evals/__init__.py,sha256=5_qUGwiKR2l4p-F8RZ9QnxzFOxtNj7DWoEsA8uNyHIs,1991
33
- aid_runtime/evals/agent_runner.py,sha256=E1Vg48gNAeQzGGSyp0cK8H5mxGlVEPBq-FTaaTQ-CLE,12594
34
+ aid_runtime/evals/agent_runner.py,sha256=sffFGqZDBLmKkce6t82IaWJLHNq-q7HuSmIM61uEkoU,13513
34
35
  aid_runtime/evals/dataset.py,sha256=ZmTP-jWx9f2udYPyzvTtOuUse5Mp-uj5WNBPy-7aHKM,5946
35
36
  aid_runtime/evals/gate.py,sha256=uYUOw57MaGqSOsMvbB0C6MrjW4IbUJ57izyD6FSxkxw,17676
36
37
  aid_runtime/evals/metrics.py,sha256=LvzKgW-7CNxcB0MmDXakDnwdgyzjpH8ceHq7mdi8mw4,28541
@@ -62,7 +63,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
62
63
  aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
63
64
  aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
64
65
  aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
65
- aid_runtime_python-0.1.162.dist-info/METADATA,sha256=qAn1akp78XLDV7BYtyv2O2uOsBBkovoiO8nAL1bfCQ8,17163
66
- aid_runtime_python-0.1.162.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
67
- aid_runtime_python-0.1.162.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
68
- aid_runtime_python-0.1.162.dist-info/RECORD,,
66
+ aid_runtime_python-0.1.164.dist-info/METADATA,sha256=GBlFqJjmGPFPh8i0p9I47WUlTEMiJEJbdYoNfEt8N2k,17163
67
+ aid_runtime_python-0.1.164.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
68
+ aid_runtime_python-0.1.164.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
69
+ aid_runtime_python-0.1.164.dist-info/RECORD,,